aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.md28
-rw-r--r--.github/ISSUE_TEMPLATE/feature_request.md18
-rw-r--r--.github/ISSUE_TEMPLATE/question.md7
-rw-r--r--.gitignore5
-rw-r--r--.travis.yml90
-rw-r--r--BUILD95
-rw-r--r--CHANGES.txt12
-rw-r--r--CONTRIBUTING.md85
-rw-r--r--Makefile.am22
-rw-r--r--Protobuf.podspec4
-rw-r--r--README.md6
-rw-r--r--WORKSPACE16
-rw-r--r--appveyor.bat14
-rw-r--r--appveyor.yml20
-rw-r--r--benchmarks/Makefile.am185
-rw-r--r--benchmarks/README.md43
-rw-r--r--benchmarks/cpp/cpp_benchmark.cc2
-rw-r--r--[-rwxr-xr-x]benchmarks/java/pom.xml5
-rw-r--r--[-rwxr-xr-x]benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java32
-rw-r--r--benchmarks/js/benchmark_suite.js33
-rw-r--r--benchmarks/js/js_benchmark.js70
-rw-r--r--benchmarks/php/PhpBenchmark.php157
-rw-r--r--benchmarks/php/autoload.php25
-rw-r--r--benchmarks/protobuf.js/generate_pbjs_files.js25
-rw-r--r--benchmarks/protobuf.js/protobufjs_benchmark.js66
-rwxr-xr-xbenchmarks/python/py_benchmark.py17
-rwxr-xr-xbenchmarks/util/big_query_utils.py27
-rw-r--r--benchmarks/util/data_proto2_to_proto3_util.h64
-rw-r--r--benchmarks/util/gogo_data_scrubber.cc39
-rw-r--r--benchmarks/util/proto3_data_stripper.cc74
-rw-r--r--benchmarks/util/protoc-gen-gogoproto.cc4
-rw-r--r--benchmarks/util/protoc-gen-proto2_to_proto3.cc115
-rwxr-xr-xbenchmarks/util/result_parser.py (renamed from benchmarks/util/run_and_upload.py)226
-rwxr-xr-xbenchmarks/util/result_uploader.py94
-rw-r--r--benchmarks/util/schema_proto2_to_proto3_util.h61
-rw-r--r--cmake/CMakeLists.txt11
-rw-r--r--cmake/README.md4
-rw-r--r--cmake/conformance.cmake48
-rw-r--r--cmake/extract_includes.bat.in3
-rw-r--r--cmake/install.cmake14
-rw-r--r--cmake/libprotobuf-lite.cmake2
-rw-r--r--cmake/libprotobuf.cmake2
-rw-r--r--cmake/libprotoc.cmake7
-rw-r--r--cmake/protobuf-config.cmake.in22
-rw-r--r--cmake/protoc.cmake2
-rw-r--r--cmake/tests.cmake14
-rw-r--r--configure.ac2
-rw-r--r--conformance/ConformanceJava.java10
-rw-r--r--conformance/Makefile.am1
-rw-r--r--conformance/README.md6
-rw-r--r--conformance/conformance.proto17
-rw-r--r--conformance/conformance_cpp.cc8
-rwxr-xr-xconformance/conformance_php.php8
-rwxr-xr-xconformance/conformance_python.py6
-rw-r--r--conformance/conformance_test.cc2390
-rw-r--r--conformance/conformance_test.h203
-rw-r--r--conformance/conformance_test_impl.cc2367
-rw-r--r--conformance/conformance_test_runner.cc312
-rw-r--r--conformance/failure_list_php_c.txt110
-rw-r--r--conformance/failure_list_ruby.txt8
-rw-r--r--csharp/Google.Protobuf.Tools.nuspec6
-rw-r--r--csharp/Google.Protobuf.Tools.targets11
-rw-r--r--csharp/README.md2
-rw-r--r--csharp/build_packages.bat2
-rw-r--r--csharp/compatibility_tests/v3.0.0/protos/csharp/protos/unittest_issues.proto4
-rw-r--r--csharp/protos/unittest_issues.proto4
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Conformance.cs77
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Program.cs3
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/ByteStringTest.cs2
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf.Test/FieldCodecTest.cs0
-rw-r--r--csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs99
-rw-r--r--csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs101
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/ByteString.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Collections/RepeatedField.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs0
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs0
-rw-r--r--csharp/src/Google.Protobuf/Google.Protobuf.csproj12
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/JsonFormatter.cs0
-rw-r--r--csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs8
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs12
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs63
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs10
-rw-r--r--csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs16
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Any.cs3
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs50
-rw-r--r--[-rwxr-xr-x]csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs0
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs105
-rw-r--r--docs/options.md196
-rw-r--r--docs/performance.md4
-rw-r--r--docs/third_party.md7
-rw-r--r--examples/WORKSPACE8
-rw-r--r--examples/add_person.go2
-rw-r--r--examples/add_person_test.go2
-rw-r--r--examples/list_people.go2
-rw-r--r--examples/list_people_test.go2
-rwxr-xr-xgenerate_changelog.py7
-rwxr-xr-xgenerate_descriptor_proto.sh14
-rw-r--r--java/README.md18
-rwxr-xr-xjava/compatibility_tests/v2.5.0/test.sh2
-rw-r--r--java/core/pom.xml15
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessage.java206
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractParser.java34
-rw-r--r--java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java35
-rw-r--r--java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/BlockingService.java25
-rw-r--r--java/core/src/main/java/com/google/protobuf/BooleanArrayList.java21
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java32
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteOutput.java22
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteString.java702
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java130
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedOutputStream.java465
-rw-r--r--java/core/src/main/java/com/google/protobuf/Descriptors.java1089
-rw-r--r--java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/DoubleArrayList.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/DynamicMessage.java156
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExperimentalApi.java27
-rw-r--r--java/core/src/main/java/com/google/protobuf/Extension.java15
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionLite.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java184
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java11
-rw-r--r--java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java88
-rw-r--r--java/core/src/main/java/com/google/protobuf/FieldSet.java485
-rw-r--r--java/core/src/main/java/com/google/protobuf/FloatArrayList.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java539
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java107
-rw-r--r--java/core/src/main/java/com/google/protobuf/IntArrayList.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/Internal.java355
-rw-r--r--java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java53
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyField.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyFieldLite.java123
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/LazyStringList.java102
-rw-r--r--java/core/src/main/java/com/google/protobuf/LongArrayList.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntry.java108
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntryLite.java60
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapField.java105
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapFieldLite.java51
-rw-r--r--java/core/src/main/java/com/google/protobuf/Message.java165
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageLite.java285
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java23
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java102
-rw-r--r--java/core/src/main/java/com/google/protobuf/MessageReflection.java332
-rw-r--r--java/core/src/main/java/com/google/protobuf/MutabilityOracle.java21
-rw-r--r--java/core/src/main/java/com/google/protobuf/NioByteString.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/Parser.java203
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java18
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java15
-rw-r--r--java/core/src/main/java/com/google/protobuf/ProtocolStringList.java12
-rw-r--r--java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java221
-rw-r--r--java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java203
-rw-r--r--java/core/src/main/java/com/google/protobuf/RopeByteString.java232
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcCallback.java13
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcChannel.java43
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcController.java76
-rw-r--r--java/core/src/main/java/com/google/protobuf/RpcUtil.java50
-rw-r--r--java/core/src/main/java/com/google/protobuf/Service.java86
-rw-r--r--java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java92
-rw-r--r--java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java80
-rw-r--r--java/core/src/main/java/com/google/protobuf/SmallSortedMap.java182
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormat.java924
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java125
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java41
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java7
-rw-r--r--java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java37
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java311
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java139
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java8
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java41
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeUtil.java44
-rw-r--r--java/core/src/main/java/com/google/protobuf/Utf8.java407
-rw-r--r--java/core/src/main/java/com/google/protobuf/WireFormat.java187
-rw-r--r--java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java197
-rw-r--r--java/core/src/test/java/com/google/protobuf/AnyTest.java8
-rw-r--r--java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java50
-rw-r--r--java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java30
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteStringTest.java305
-rw-r--r--java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java13
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java2
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java93
-rw-r--r--java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java24
-rw-r--r--java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java83
-rw-r--r--java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java54
-rw-r--r--java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java118
-rw-r--r--java/core/src/test/java/com/google/protobuf/EnumTest.java28
-rw-r--r--java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java121
-rw-r--r--java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java54
-rw-r--r--java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java9
-rw-r--r--java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java573
-rw-r--r--java/core/src/test/java/com/google/protobuf/IntArrayListTest.java12
-rw-r--r--java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java51
-rw-r--r--java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java158
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyFieldTest.java10
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java174
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java62
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java61
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteTest.java61
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java281
-rw-r--r--java/core/src/test/java/com/google/protobuf/LongArrayListTest.java12
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java117
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapTest.java268
-rw-r--r--java/core/src/test/java/com/google/protobuf/MessageTest.java210
-rw-r--r--java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java77
-rw-r--r--java/core/src/test/java/com/google/protobuf/NioByteStringTest.java323
-rw-r--r--java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java53
-rw-r--r--java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java208
-rw-r--r--java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java37
-rw-r--r--java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java38
-rw-r--r--java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/ServiceTest.java16
-rw-r--r--java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java66
-rw-r--r--java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java75
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java36
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java14
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtil.java4532
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtilLite.java496
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java7
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java934
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java103
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java121
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java262
-rw-r--r--java/core/src/test/java/com/google/protobuf/WireFormatTest.java306
-rw-r--r--java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto2
-rw-r--r--java/core/src/test/proto/com/google/protobuf/lite_equals_and_hash.proto1
-rw-r--r--java/pom.xml4
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Durations.java3
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java18
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/FieldMaskUtil.java2
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/JsonFormat.java19
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/FieldMaskTreeTest.java150
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java56
-rw-r--r--js/README.md11
-rw-r--r--js/binary/constants.js2
-rw-r--r--js/binary/reader.js17
-rw-r--r--js/binary/reader_test.js15
-rw-r--r--js/binary/utils.js5
-rw-r--r--js/commonjs/strict_test.js67
-rw-r--r--js/gulpfile.js18
-rw-r--r--js/map.js14
-rw-r--r--js/message.js50
-rw-r--r--js/message_test.js1
-rw-r--r--js/package.json4
-rw-r--r--js/test.proto7
-rw-r--r--js/test10.proto39
-rw-r--r--js/test9.proto39
-rwxr-xr-xkokoro/linux/bazel/build.sh1
-rwxr-xr-xkokoro/linux/benchmark/build.sh19
-rwxr-xr-xkokoro/linux/build_and_run_docker.sh13
-rwxr-xr-xkokoro/linux/pull_request_in_docker.sh50
-rwxr-xr-xkokoro/macos/jruby/build.sh11
-rw-r--r--kokoro/macos/jruby/continuous.cfg5
-rw-r--r--kokoro/macos/jruby/presubmit.cfg5
-rw-r--r--kokoro/release/collect_all_artifacts.cfg7
-rwxr-xr-xkokoro/release/collect_all_artifacts.sh62
-rwxr-xr-xkokoro/release/protoc/linux/build.sh16
-rw-r--r--objectivec/GPBCodedInputStream.m4
-rw-r--r--objectivec/GPBDescriptor.h34
-rw-r--r--objectivec/GPBDescriptor.m35
-rw-r--r--objectivec/GPBUnknownField.m1
-rw-r--r--objectivec/README.md9
-rw-r--r--objectivec/Tests/GPBDescriptorTests.m57
-rw-r--r--objectivec/Tests/GPBMessageTests.m2
-rw-r--r--objectivec/Tests/GPBTestUtilities.m2
-rw-r--r--objectivec/Tests/unittest_objc.proto2
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.h3
-rw-r--r--objectivec/google/protobuf/FieldMask.pbobjc.h44
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.h2
-rw-r--r--php/README.md4
-rw-r--r--php/composer.json11
-rw-r--r--php/ext/google/protobuf/encode_decode.c7
-rw-r--r--php/ext/google/protobuf/message.c102
-rw-r--r--php/ext/google/protobuf/protobuf.h9
-rw-r--r--php/ext/google/protobuf/upb.c749
-rw-r--r--php/ext/google/protobuf/upb.h9
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php16
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php16
-rw-r--r--php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php16
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php16
-rw-r--r--php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php16
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions_CType.php16
-rw-r--r--php/src/Google/Protobuf/Internal/FieldOptions_JSType.php16
-rw-r--r--php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php16
-rw-r--r--php/src/Google/Protobuf/Internal/GPBJsonWire.php2
-rw-r--r--php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php16
-rw-r--r--php/src/Google/Protobuf/Internal/Message.php2
-rw-r--r--php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php16
-rw-r--r--php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php16
-rw-r--r--php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php16
-rw-r--r--php/src/Google/Protobuf/Timestamp.php17
-rwxr-xr-xphp/tests/compatibility_test.sh3
-rw-r--r--php/tests/encode_decode_test.php81
-rw-r--r--php/tests/memory_leak_test.php2
-rw-r--r--php/tests/undefined_test.php2
-rw-r--r--php/tests/well_known_test.php4
-rw-r--r--protobuf.bzl123
-rw-r--r--protoc-artifacts/README.md13
-rwxr-xr-xprotoc-artifacts/build-zip.sh2
-rw-r--r--protoc-artifacts/pom.xml4
-rw-r--r--python/README.md4
-rwxr-xr-xpython/compatibility_tests/v2.5.0/setup.py2
-rwxr-xr-xpython/compatibility_tests/v2.5.0/tests/google/protobuf/internal/text_format_test.py9
-rw-r--r--python/google/protobuf/descriptor_database.py17
-rw-r--r--python/google/protobuf/descriptor_pool.py196
-rwxr-xr-xpython/google/protobuf/internal/__init__.py30
-rwxr-xr-xpython/google/protobuf/internal/api_implementation.py26
-rwxr-xr-xpython/google/protobuf/internal/containers.py127
-rwxr-xr-xpython/google/protobuf/internal/decoder.py196
-rw-r--r--python/google/protobuf/internal/descriptor_database_test.py13
-rw-r--r--python/google/protobuf/internal/descriptor_pool_test.py63
-rwxr-xr-xpython/google/protobuf/internal/descriptor_test.py11
-rw-r--r--python/google/protobuf/internal/factory_test1.proto14
-rw-r--r--python/google/protobuf/internal/json_format_test.py3
-rw-r--r--python/google/protobuf/internal/message_factory_test.py4
-rwxr-xr-xpython/google/protobuf/internal/message_test.py279
-rw-r--r--python/google/protobuf/internal/no_package.proto30
-rwxr-xr-xpython/google/protobuf/internal/python_message.py145
-rwxr-xr-xpython/google/protobuf/internal/reflection_test.py57
-rwxr-xr-xpython/google/protobuf/internal/text_format_test.py398
-rwxr-xr-xpython/google/protobuf/internal/type_checkers.py8
-rwxr-xr-xpython/google/protobuf/internal/unknown_fields_test.py165
-rw-r--r--python/google/protobuf/internal/well_known_types.py15
-rw-r--r--python/google/protobuf/internal/well_known_types_test.py37
-rw-r--r--python/google/protobuf/json_format.py8
-rwxr-xr-xpython/google/protobuf/message.py4
-rw-r--r--python/google/protobuf/message_factory.py15
-rw-r--r--python/google/protobuf/proto_api.h91
-rw-r--r--python/google/protobuf/pyext/descriptor.cc51
-rw-r--r--python/google/protobuf/pyext/descriptor.h2
-rw-r--r--python/google/protobuf/pyext/descriptor_containers.cc12
-rw-r--r--python/google/protobuf/pyext/descriptor_containers.h2
-rw-r--r--python/google/protobuf/pyext/descriptor_database.cc39
-rw-r--r--python/google/protobuf/pyext/descriptor_database.h15
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.cc47
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.h8
-rw-r--r--python/google/protobuf/pyext/extension_dict.cc92
-rw-r--r--python/google/protobuf/pyext/extension_dict.h19
-rwxr-xr-xpython/google/protobuf/pyext/field.cc142
-rwxr-xr-x[-rw-r--r--]python/google/protobuf/pyext/field.h (renamed from src/google/protobuf/compiler/js/well_known_types/timestamp.js)46
-rw-r--r--python/google/protobuf/pyext/map_container.cc138
-rw-r--r--python/google/protobuf/pyext/map_container.h2
-rw-r--r--python/google/protobuf/pyext/message.cc672
-rw-r--r--python/google/protobuf/pyext/message.h49
-rw-r--r--python/google/protobuf/pyext/message_factory.cc6
-rw-r--r--python/google/protobuf/pyext/message_factory.h7
-rw-r--r--python/google/protobuf/pyext/message_module.cc73
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.cc26
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.h4
-rw-r--r--python/google/protobuf/pyext/repeated_scalar_container.cc11
-rw-r--r--python/google/protobuf/pyext/repeated_scalar_container.h2
-rw-r--r--python/google/protobuf/pyext/safe_numerics.h12
-rw-r--r--python/google/protobuf/pyext/thread_unsafe_shared_ptr.h2
-rwxr-xr-xpython/google/protobuf/pyext/unknown_fields.cc355
-rwxr-xr-xpython/google/protobuf/pyext/unknown_fields.h90
-rw-r--r--python/google/protobuf/python_protobuf.h2
-rwxr-xr-xpython/google/protobuf/reflection.py52
-rw-r--r--python/google/protobuf/text_encoding.py84
-rwxr-xr-xpython/google/protobuf/text_format.py149
-rwxr-xr-xpython/release.sh2
-rwxr-xr-xpython/release/wheel/protobuf_optimized_pip.sh2
-rwxr-xr-xpython/setup.py21
-rwxr-xr-xpython/stubout.py3
-rw-r--r--ruby/ext/google/protobuf_c/defs.c10
-rw-r--r--ruby/ext/google/protobuf_c/encode_decode.c4
-rw-r--r--ruby/ext/google/protobuf_c/message.c6
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.c2
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.h1
-rw-r--r--ruby/ext/google/protobuf_c/storage.c34
-rw-r--r--ruby/ext/google/protobuf_c/wrap_memcpy.c2
-rw-r--r--ruby/lib/google/protobuf.rb1
-rw-r--r--ruby/lib/google/protobuf/well_known_types.rb12
-rw-r--r--ruby/pom.xml4
-rw-r--r--ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java2
-rw-r--r--ruby/tests/basic.rb60
-rw-r--r--ruby/tests/well_known_types_test.rb14
-rw-r--r--src/Makefile.am20
-rw-r--r--src/README.md8
-rw-r--r--src/google/protobuf/any.h16
-rw-r--r--src/google/protobuf/any.pb.cc222
-rw-r--r--src/google/protobuf/any.pb.h59
-rw-r--r--src/google/protobuf/any.proto3
-rw-r--r--src/google/protobuf/any_test.cc57
-rw-r--r--src/google/protobuf/api.pb.cc753
-rw-r--r--src/google/protobuf/api.pb.h96
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/arena.cc34
-rw-r--r--src/google/protobuf/arena.h125
-rw-r--r--src/google/protobuf/arena_impl.h20
-rw-r--r--src/google/protobuf/arena_test_util.h19
-rw-r--r--src/google/protobuf/arena_unittest.cc65
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/arenastring.h19
-rw-r--r--src/google/protobuf/arenastring_unittest.cc9
-rw-r--r--src/google/protobuf/compiler/annotation_test_util.h32
-rw-r--r--src/google/protobuf/compiler/code_generator.h28
-rw-r--r--src/google/protobuf/compiler/command_line_interface.cc135
-rw-r--r--src/google/protobuf/compiler/command_line_interface.h95
-rw-r--r--src/google/protobuf/compiler/command_line_interface_unittest.cc54
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc31
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.cc350
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.h26
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.cc639
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.h9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.cc112
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.h22
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.cc75
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.h73
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.cc1504
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.h105
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_generator.cc74
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_generator.h27
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.cc1072
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.h560
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.cc345
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.h9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.cc3888
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.h75
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.cc925
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.h16
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_options.h46
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.cc396
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.h9
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_service.cc367
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_service.h16
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.cc1083
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.h7
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.cc4
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.h2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.inc86
-rw-r--r--src/google/protobuf/compiler/cpp/metadata_test.cc7
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_enum.h2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_field_base.h2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_generator.h8
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_helpers.cc2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_helpers.h8
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_names.h20
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_reflection_class.h2
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_source_generator_base.h1
-rw-r--r--src/google/protobuf/compiler/importer.cc2
-rw-r--r--src/google/protobuf/compiler/importer.h94
-rw-r--r--src/google/protobuf/compiler/importer_unittest.cc4
-rw-r--r--src/google/protobuf/compiler/java/java_context.h4
-rw-r--r--src/google/protobuf/compiler/java/java_doc_comment.h16
-rw-r--r--src/google/protobuf/compiler/java/java_enum.cc30
-rw-r--r--src/google/protobuf/compiler/java/java_enum.h26
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field.cc8
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field.h41
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field_lite.cc56
-rw-r--r--src/google/protobuf/compiler/java/java_enum_field_lite.h47
-rw-r--r--src/google/protobuf/compiler/java/java_enum_lite.cc59
-rw-r--r--src/google/protobuf/compiler/java/java_enum_lite.h26
-rw-r--r--src/google/protobuf/compiler/java/java_extension.cc4
-rw-r--r--src/google/protobuf/compiler/java/java_extension.h37
-rw-r--r--src/google/protobuf/compiler/java/java_extension_lite.h4
-rw-r--r--src/google/protobuf/compiler/java/java_field.cc56
-rw-r--r--src/google/protobuf/compiler/java/java_field.h47
-rw-r--r--src/google/protobuf/compiler/java/java_file.cc13
-rw-r--r--src/google/protobuf/compiler/java/java_file.h46
-rw-r--r--src/google/protobuf/compiler/java/java_generator.cc3
-rw-r--r--src/google/protobuf/compiler/java/java_generator.h12
-rw-r--r--src/google/protobuf/compiler/java/java_generator_factory.h24
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.cc70
-rw-r--r--src/google/protobuf/compiler/java/java_helpers.h95
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field.cc814
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field.h121
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc725
-rw-r--r--src/google/protobuf/compiler/java/java_lazy_message_field_lite.h121
-rw-r--r--src/google/protobuf/compiler/java/java_map_field.h6
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.cc14
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.h14
-rw-r--r--src/google/protobuf/compiler/java/java_message.cc220
-rw-r--r--src/google/protobuf/compiler/java/java_message.h29
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.cc36
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.h22
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder_lite.cc20
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder_lite.h24
-rw-r--r--src/google/protobuf/compiler/java/java_message_field.cc21
-rw-r--r--src/google/protobuf/compiler/java/java_message_field.h62
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.cc54
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.h48
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.cc195
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.h2
-rw-r--r--src/google/protobuf/compiler/java/java_name_resolver.h38
-rw-r--r--src/google/protobuf/compiler/java/java_names.h35
-rw-r--r--src/google/protobuf/compiler/java/java_options.h2
-rw-r--r--src/google/protobuf/compiler/java/java_plugin_unittest.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field.cc112
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field.h42
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field_lite.cc51
-rw-r--r--src/google/protobuf/compiler/java/java_primitive_field_lite.h45
-rw-r--r--src/google/protobuf/compiler/java/java_service.cc14
-rw-r--r--src/google/protobuf/compiler/java/java_service.h24
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.h28
-rw-r--r--src/google/protobuf/compiler/java/java_string_field.h41
-rw-r--r--src/google/protobuf/compiler/java/java_string_field_lite.cc50
-rw-r--r--src/google/protobuf/compiler/java/java_string_field_lite.h47
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/compiler/js/js_generator.cc203
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/compiler/js/js_generator.h75
-rw-r--r--src/google/protobuf/compiler/js/well_known_types/struct.js168
-rw-r--r--src/google/protobuf/compiler/js/well_known_types_embed.cc30
-rw-r--r--src/google/protobuf/compiler/main.cc51
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.cc8
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.h52
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.h7
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.cc9
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.h99
-rw-r--r--src/google/protobuf/compiler/package_info.h1
-rw-r--r--src/google/protobuf/compiler/parser.cc22
-rw-r--r--src/google/protobuf/compiler/parser.h51
-rw-r--r--src/google/protobuf/compiler/parser_unittest.cc12
-rw-r--r--src/google/protobuf/compiler/php/php_generator.h12
-rw-r--r--src/google/protobuf/compiler/plugin.h12
-rw-r--r--src/google/protobuf/compiler/plugin.pb.cc827
-rw-r--r--src/google/protobuf/compiler/plugin.pb.h334
-rw-r--r--src/google/protobuf/compiler/python/python_generator.cc40
-rw-r--r--src/google/protobuf/compiler/python/python_generator.h42
-rw-r--r--src/google/protobuf/compiler/python/python_plugin_unittest.cc4
-rw-r--r--src/google/protobuf/compiler/ruby/ruby_generator.h6
-rw-r--r--src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc4
-rw-r--r--src/google/protobuf/compiler/scc.cc111
-rw-r--r--src/google/protobuf/compiler/scc.h99
-rw-r--r--src/google/protobuf/compiler/subprocess.h14
-rw-r--r--src/google/protobuf/compiler/test_plugin.cc17
-rw-r--r--src/google/protobuf/compiler/zip_writer.h4
-rw-r--r--src/google/protobuf/descriptor.cc315
-rw-r--r--src/google/protobuf/descriptor.h365
-rw-r--r--src/google/protobuf/descriptor.pb.cc6393
-rw-r--r--src/google/protobuf/descriptor.pb.h2594
-rw-r--r--src/google/protobuf/descriptor_database.cc16
-rw-r--r--src/google/protobuf/descriptor_database.h133
-rw-r--r--src/google/protobuf/descriptor_database_unittest.cc18
-rw-r--r--src/google/protobuf/descriptor_unittest.cc504
-rw-r--r--src/google/protobuf/drop_unknown_fields_test.cc54
-rw-r--r--src/google/protobuf/duration.pb.cc206
-rw-r--r--src/google/protobuf/duration.pb.h56
-rw-r--r--src/google/protobuf/dynamic_message.cc44
-rw-r--r--src/google/protobuf/dynamic_message.h28
-rw-r--r--src/google/protobuf/empty.pb.cc172
-rw-r--r--src/google/protobuf/empty.pb.h54
-rw-r--r--src/google/protobuf/extension_set.cc454
-rw-r--r--src/google/protobuf/extension_set.h670
-rw-r--r--src/google/protobuf/extension_set_heavy.cc500
-rw-r--r--src/google/protobuf/extension_set_unittest.cc66
-rw-r--r--src/google/protobuf/field_mask.pb.cc231
-rw-r--r--src/google/protobuf/field_mask.pb.h83
-rw-r--r--src/google/protobuf/field_mask.proto45
-rw-r--r--src/google/protobuf/generated_enum_reflection.h23
-rw-r--r--src/google/protobuf/generated_enum_util.h6
-rw-r--r--src/google/protobuf/generated_message_reflection.cc150
-rw-r--r--src/google/protobuf/generated_message_reflection.h460
-rw-r--r--src/google/protobuf/generated_message_reflection_unittest.cc24
-rw-r--r--src/google/protobuf/generated_message_table_driven.h16
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.cc19
-rw-r--r--src/google/protobuf/generated_message_table_driven_lite.h125
-rw-r--r--src/google/protobuf/generated_message_util.cc64
-rw-r--r--src/google/protobuf/generated_message_util.h138
-rw-r--r--src/google/protobuf/has_bits.h21
-rw-r--r--src/google/protobuf/implicit_weak_message.cc24
-rw-r--r--src/google/protobuf/implicit_weak_message.h63
-rw-r--r--src/google/protobuf/inlined_string_field.h92
-rw-r--r--src/google/protobuf/io/coded_stream.cc90
-rw-r--r--src/google/protobuf/io/coded_stream.h93
-rw-r--r--src/google/protobuf/io/coded_stream_inl.h2
-rw-r--r--src/google/protobuf/io/coded_stream_unittest.cc8
-rw-r--r--src/google/protobuf/io/gzip_stream.h14
-rw-r--r--src/google/protobuf/io/package_info.h1
-rw-r--r--src/google/protobuf/io/printer.cc259
-rw-r--r--src/google/protobuf/io/printer.h133
-rw-r--r--src/google/protobuf/io/printer_unittest.cc134
-rw-r--r--src/google/protobuf/io/strtod.h2
-rw-r--r--src/google/protobuf/io/tokenizer.h44
-rw-r--r--src/google/protobuf/io/zero_copy_stream.h12
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl.h96
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.cc6
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl_lite.h71
-rw-r--r--src/google/protobuf/io/zero_copy_stream_unittest.cc8
-rw-r--r--src/google/protobuf/lite_arena_unittest.cc10
-rw-r--r--src/google/protobuf/lite_unittest.cc429
-rw-r--r--src/google/protobuf/map.h35
-rw-r--r--src/google/protobuf/map_entry.h31
-rw-r--r--src/google/protobuf/map_entry_lite.h145
-rw-r--r--src/google/protobuf/map_field.cc121
-rw-r--r--src/google/protobuf/map_field.h167
-rw-r--r--src/google/protobuf/map_field_inl.h21
-rw-r--r--src/google/protobuf/map_field_lite.h15
-rw-r--r--src/google/protobuf/map_field_test.cc10
-rw-r--r--src/google/protobuf/map_lite_test_util.h2
-rw-r--r--src/google/protobuf/map_test.cc204
-rw-r--r--src/google/protobuf/map_test_util.h12
-rw-r--r--src/google/protobuf/map_test_util_impl.h4
-rw-r--r--src/google/protobuf/map_type_handler.h177
-rw-r--r--src/google/protobuf/message.cc708
-rw-r--r--src/google/protobuf/message.h244
-rw-r--r--src/google/protobuf/message_lite.cc476
-rw-r--r--src/google/protobuf/message_lite.h107
-rw-r--r--src/google/protobuf/message_unittest.cc6
-rw-r--r--src/google/protobuf/message_unittest.inc103
-rw-r--r--src/google/protobuf/metadata.h6
-rw-r--r--src/google/protobuf/metadata_lite.h65
-rw-r--r--src/google/protobuf/no_field_presence_test.cc73
-rw-r--r--src/google/protobuf/package_info.h8
-rw-r--r--src/google/protobuf/port.h6
-rw-r--r--src/google/protobuf/port_def.inc308
-rw-r--r--src/google/protobuf/port_undef.inc62
-rw-r--r--src/google/protobuf/preserve_unknown_enum_test.cc100
-rw-r--r--src/google/protobuf/proto3_arena_lite_unittest.cc2
-rw-r--r--src/google/protobuf/proto3_arena_unittest.cc29
-rw-r--r--src/google/protobuf/proto3_lite_unittest.cc111
-rw-r--r--src/google/protobuf/proto3_lite_unittest.inc139
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/reflection.h26
-rw-r--r--src/google/protobuf/reflection_internal.h159
-rw-r--r--src/google/protobuf/reflection_ops.cc1
-rw-r--r--src/google/protobuf/reflection_ops.h16
-rw-r--r--src/google/protobuf/repeated_field.cc25
-rw-r--r--src/google/protobuf/repeated_field.h266
-rw-r--r--src/google/protobuf/repeated_field_unittest.cc2
-rw-r--r--src/google/protobuf/service.cc2
-rw-r--r--src/google/protobuf/service.h20
-rw-r--r--src/google/protobuf/source_context.pb.cc198
-rw-r--r--src/google/protobuf/source_context.pb.h54
-rw-r--r--src/google/protobuf/struct.pb.cc630
-rw-r--r--src/google/protobuf/struct.pb.h129
-rw-r--r--src/google/protobuf/stubs/bytestream.cc2
-rw-r--r--src/google/protobuf/stubs/bytestream.h47
-rw-r--r--src/google/protobuf/stubs/callback.h41
-rw-r--r--src/google/protobuf/stubs/casts.h4
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/stubs/common.cc15
-rw-r--r--src/google/protobuf/stubs/common.h42
-rw-r--r--src/google/protobuf/stubs/common_unittest.cc14
-rw-r--r--src/google/protobuf/stubs/fastmem.h6
-rw-r--r--src/google/protobuf/stubs/hash.h324
-rw-r--r--src/google/protobuf/stubs/int128.cc69
-rw-r--r--src/google/protobuf/stubs/int128.h16
-rw-r--r--src/google/protobuf/stubs/int128_unittest.cc130
-rw-r--r--src/google/protobuf/stubs/io_win32.cc18
-rw-r--r--src/google/protobuf/stubs/io_win32.h41
-rw-r--r--src/google/protobuf/stubs/io_win32_unittest.cc28
-rw-r--r--src/google/protobuf/stubs/logging.h18
-rw-r--r--src/google/protobuf/stubs/map_util.h32
-rw-r--r--src/google/protobuf/stubs/mathlimits.h122
-rw-r--r--src/google/protobuf/stubs/mutex.h38
-rw-r--r--src/google/protobuf/stubs/platform_macros.h8
-rw-r--r--src/google/protobuf/stubs/port.h182
-rw-r--r--src/google/protobuf/stubs/singleton.h4
-rw-r--r--src/google/protobuf/stubs/status.h9
-rw-r--r--src/google/protobuf/stubs/status_macros.h10
-rw-r--r--src/google/protobuf/stubs/statusor.h20
-rw-r--r--src/google/protobuf/stubs/stl_util.h6
-rw-r--r--src/google/protobuf/stubs/stringpiece.cc2
-rw-r--r--src/google/protobuf/stubs/stringpiece.h53
-rw-r--r--src/google/protobuf/stubs/stringpiece_unittest.cc22
-rw-r--r--src/google/protobuf/stubs/stringprintf.cc2
-rw-r--r--src/google/protobuf/stubs/stringprintf.h19
-rw-r--r--src/google/protobuf/stubs/stringprintf_unittest.cc4
-rw-r--r--src/google/protobuf/stubs/strutil.cc145
-rw-r--r--src/google/protobuf/stubs/strutil.h286
-rw-r--r--src/google/protobuf/stubs/strutil_unittest.cc10
-rw-r--r--src/google/protobuf/stubs/substitute.cc4
-rw-r--r--src/google/protobuf/stubs/substitute.h56
-rw-r--r--src/google/protobuf/stubs/time.cc38
-rw-r--r--src/google/protobuf/stubs/time.h15
-rw-r--r--src/google/protobuf/test_util.h27
-rw-r--r--src/google/protobuf/test_util2.h73
-rw-r--r--src/google/protobuf/test_util_lite.h2
-rw-r--r--src/google/protobuf/testing/file.cc4
-rw-r--r--src/google/protobuf/testing/file.h7
-rw-r--r--src/google/protobuf/text_format.cc354
-rw-r--r--src/google/protobuf/text_format.h111
-rw-r--r--src/google/protobuf/text_format_unittest.cc52
-rw-r--r--src/google/protobuf/timestamp.pb.cc206
-rw-r--r--src/google/protobuf/timestamp.pb.h56
-rw-r--r--src/google/protobuf/timestamp.proto2
-rw-r--r--src/google/protobuf/type.pb.cc1234
-rw-r--r--src/google/protobuf/type.pb.h210
-rw-r--r--src/google/protobuf/unittest_proto3.proto14
-rw-r--r--src/google/protobuf/unknown_field_set.cc131
-rw-r--r--src/google/protobuf/unknown_field_set.h67
-rw-r--r--src/google/protobuf/unknown_field_set_unittest.cc8
-rw-r--r--src/google/protobuf/util/delimited_message_util.cc2
-rw-r--r--src/google/protobuf/util/delimited_message_util.h25
-rw-r--r--src/google/protobuf/util/delimited_message_util_test.cc2
-rw-r--r--src/google/protobuf/util/field_comparator.cc17
-rw-r--r--src/google/protobuf/util/field_comparator.h77
-rw-r--r--src/google/protobuf/util/field_comparator_test.cc4
-rw-r--r--src/google/protobuf/util/field_mask_util.cc54
-rw-r--r--src/google/protobuf/util/field_mask_util.h58
-rw-r--r--src/google/protobuf/util/field_mask_util_test.cc69
-rw-r--r--src/google/protobuf/util/internal/constants.h3
-rw-r--r--src/google/protobuf/util/internal/datapiece.cc33
-rw-r--r--src/google/protobuf/util/internal/datapiece.h38
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.cc97
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.h95
-rw-r--r--src/google/protobuf/util/internal/error_listener.h32
-rw-r--r--src/google/protobuf/util/internal/expecting_objectwriter.h59
-rw-r--r--src/google/protobuf/util/internal/field_mask_utility.cc40
-rw-r--r--src/google/protobuf/util/internal/field_mask_utility.h6
-rw-r--r--src/google/protobuf/util/internal/json_escaping.cc4
-rw-r--r--src/google/protobuf/util/internal/json_escaping.h2
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.cc16
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.h37
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter_test.cc4
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.cc30
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.h42
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser_test.cc56
-rw-r--r--src/google/protobuf/util/internal/location_tracker.h10
-rw-r--r--src/google/protobuf/util/internal/mock_error_listener.h15
-rw-r--r--src/google/protobuf/util/internal/object_location_tracker.h6
-rw-r--r--src/google/protobuf/util/internal/object_source.h8
-rw-r--r--src/google/protobuf/util/internal/object_writer.cc4
-rw-r--r--src/google/protobuf/util/internal/object_writer.h11
-rw-r--r--src/google/protobuf/util/internal/proto_writer.cc65
-rw-r--r--src/google/protobuf/util/internal/proto_writer.h58
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.cc139
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.h52
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource_test.cc123
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.cc118
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.h85
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter_test.cc402
-rw-r--r--src/google/protobuf/util/internal/structured_objectwriter.h10
-rw-r--r--src/google/protobuf/util/internal/testdata/anys.proto2
-rw-r--r--src/google/protobuf/util/internal/testdata/books.proto5
-rw-r--r--src/google/protobuf/util/internal/testdata/maps.proto3
-rw-r--r--src/google/protobuf/util/internal/type_info.cc32
-rw-r--r--src/google/protobuf/util/internal/type_info.h8
-rw-r--r--src/google/protobuf/util/internal/type_info_test_helper.cc1
-rw-r--r--src/google/protobuf/util/internal/type_info_test_helper.h8
-rw-r--r--src/google/protobuf/util/internal/utility.cc17
-rw-r--r--src/google/protobuf/util/internal/utility.h75
-rw-r--r--src/google/protobuf/util/json_format.proto (renamed from src/google/protobuf/compiler/js/well_known_types/any.js)111
-rw-r--r--src/google/protobuf/util/json_format_proto3.proto4
-rw-r--r--src/google/protobuf/util/json_util.cc60
-rw-r--r--src/google/protobuf/util/json_util.h84
-rw-r--r--src/google/protobuf/util/json_util_test.cc92
-rw-r--r--src/google/protobuf/util/message_differencer.cc67
-rw-r--r--src/google/protobuf/util/message_differencer.h83
-rw-r--r--[-rwxr-xr-x]src/google/protobuf/util/message_differencer_unittest.cc68
-rw-r--r--src/google/protobuf/util/time_util.cc13
-rw-r--r--src/google/protobuf/util/time_util.h49
-rw-r--r--src/google/protobuf/util/type_resolver.h14
-rw-r--r--src/google/protobuf/util/type_resolver_util.cc12
-rw-r--r--src/google/protobuf/util/type_resolver_util.h11
-rw-r--r--src/google/protobuf/wire_format.cc119
-rw-r--r--src/google/protobuf/wire_format.h138
-rw-r--r--src/google/protobuf/wire_format_lite.cc34
-rw-r--r--src/google/protobuf/wire_format_lite.h450
-rw-r--r--src/google/protobuf/wire_format_lite_inl.h92
-rw-r--r--src/google/protobuf/wire_format_unittest.cc33
-rw-r--r--src/google/protobuf/wrappers.pb.cc1107
-rw-r--r--src/google/protobuf/wrappers.pb.h210
-rw-r--r--src/google/protobuf/wrappers.proto5
-rwxr-xr-xtests.sh33
761 files changed, 49681 insertions, 36922 deletions
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..2f6d0263
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,28 @@
+---
+name: Bug report
+about: Create a report to help us improve
+
+---
+
+**What version of protobuf and what language are you using?**
+Version: master/v3.6.0/v3.5.0 etc.
+Language: C++/Java/Python/C#/Ruby/PHP/Objective-C/Javascript
+
+**What operating system (Linux, Windows, ...) and version?**
+
+**What runtime / compiler are you using (e.g., python version or gcc version)**
+
+**What did you do?**
+Steps to reproduce the behavior:
+1. Go to '...'
+2. Click on '....'
+3. Scroll down to '....'
+4. See error
+
+**What did you expect to see**
+
+**What did you see instead?**
+
+Make sure you include information that can help us debug (full error message, exception listing, stack trace, logs).
+
+**Anything else we should know about your project / environment**
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 00000000..722db4ce
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,18 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+
+---
+
+**What language does this apply to?**
+If it's a proto syntax change, is it for proto2 or proto3?
+If it's about generated code change, what programming language?
+
+**Describe the problem you are trying to solve.**
+
+**Describe the solution you'd like**
+
+**Describe alternatives you've considered**
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md
new file mode 100644
index 00000000..bfa6ddea
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.md
@@ -0,0 +1,7 @@
+---
+name: Question
+about: Questions and troubleshooting
+
+---
+
+
diff --git a/.gitignore b/.gitignore
index db8a893a..a8de0e54 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,7 +53,7 @@ src/google/protobuf/util/**/*.pb.h
*.pyc
*.egg-info
*_pb2.py
-python/*.egg
+python/**/*.egg
python/.eggs/
python/.tox
python/build/
@@ -186,3 +186,6 @@ cmake/cmake-build-debug/
# Common build subdirectories.
./.build/
./_build/
+
+# Visual Studio 2017
+.vs
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 74d4ea7b..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,90 +0,0 @@
-# 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
-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:
- include:
- # -----------------------------------------------------------------
- # macOS hosted tests for Objective-C
-
- - os: osx
- env: CONFIG=objectivec_osx
- osx_image: xcode9.3
- 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=objectivec_ios_debug
- osx_image: xcode9.3
- language: objective-c
- - os: osx
- env: CONFIG=objectivec_ios_release
- osx_image: xcode9.3
- language: objective-c
- - os: osx
- env: CONFIG=objectivec_cocoapods_integration
- osx_image: xcode9.3
- language: objective-c
-
- # -----------------------------------------------------------------
- # macOS hosted tests for other languages.
-
- - os: osx
- env: CONFIG=cpp
- - os: osx
- 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
- - os: osx
- env: CONFIG=php7.0_mac
-
- # -----------------------------------------------------------------
- # 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
- dotnet: 2.0.3
- mono: none
- # Install the .NET Core 1.0 runtime as that's what we test against
- addons:
- apt:
- sources:
- - sourceline: 'deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main'
- key_url: 'https://packages.microsoft.com/keys/microsoft.asc'
- packages:
- - dotnet-sharedframework-microsoft.netcore.app-1.0.5
- # This test is kept on travis because it doesn't play nicely with other
- # tests on jenkins running in parallel.
- - os: linux
- env: CONFIG=cpp_distcheck
- # The Java compatibility test currently only runs on Linux because it will
- # fetch pre-built Linux protoc binaries in the test.
- - os: linux
- env: CONFIG=java_compatibility
- 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 19f07c54..25c41a42 100644
--- a/BUILD
+++ b/BUILD
@@ -1,4 +1,4 @@
-# Bazel (http://bazel.io/) BUILD file for Protobuf.
+# Bazel (https://bazel.build/) BUILD file for Protobuf.
licenses(["notice"])
@@ -22,7 +22,20 @@ config_setting(
MSVC_COPTS = [
"/DHAVE_PTHREAD",
"/wd4018", # -Wno-sign-compare
+ "/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'
"/wd4514", # -Wno-unused-function
+ "/wd4800", # 'type' : forcing value to bool 'true' or 'false' (performance warning)
+ "/wd4996", # The compiler encountered a deprecated declaration.
]
COPTS = select({
@@ -30,12 +43,12 @@ COPTS = select({
"//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",
+ "-Wno-write-strings",
],
})
@@ -54,7 +67,10 @@ config_setting(
# Android and MSVC builds do not need to link in a separate pthread library.
LINK_OPTS = select({
":android": [],
- ":msvc": [],
+ ":msvc": [
+ # Suppress linker warnings about files with no symbols defined.
+ "-ignore:4221",
+ ],
"//conditions:default": ["-lpthread", "-lm"],
})
@@ -95,7 +111,7 @@ cc_library(
"src/google/protobuf/stubs/time.cc",
"src/google/protobuf/wire_format_lite.cc",
],
- hdrs = glob(["src/google/protobuf/**/*.h"]),
+ hdrs = glob(["src/google/protobuf/**/*.h", "src/google/protobuf/**/*.inc"]),
copts = COPTS,
includes = ["src/"],
linkopts = LINK_OPTS,
@@ -162,7 +178,7 @@ cc_library(
"src/google/protobuf/wire_format.cc",
"src/google/protobuf/wrappers.pb.cc",
],
- hdrs = glob(["src/**/*.h"]),
+ hdrs = glob(["src/**/*.h", "src/**/*.inc"]),
copts = COPTS,
includes = ["src/"],
linkopts = LINK_OPTS,
@@ -306,8 +322,6 @@ cc_library(
"src/google/protobuf/compiler/java/java_generator.cc",
"src/google/protobuf/compiler/java/java_generator_factory.cc",
"src/google/protobuf/compiler/java/java_helpers.cc",
- "src/google/protobuf/compiler/java/java_lazy_message_field.cc",
- "src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc",
"src/google/protobuf/compiler/java/java_map_field.cc",
"src/google/protobuf/compiler/java/java_map_field_lite.cc",
"src/google/protobuf/compiler/java/java_message.cc",
@@ -342,12 +356,31 @@ cc_library(
"src/google/protobuf/compiler/plugin.pb.cc",
"src/google/protobuf/compiler/python/python_generator.cc",
"src/google/protobuf/compiler/ruby/ruby_generator.cc",
+ "src/google/protobuf/compiler/scc.cc",
"src/google/protobuf/compiler/subprocess.cc",
"src/google/protobuf/compiler/zip_writer.cc",
],
copts = COPTS,
includes = ["src/"],
- linkopts = LINK_OPTS,
+ linkopts = LINK_OPTS + select({
+ ":msvc": [
+ # Linking to setargv.obj makes the default command line argument
+ # parser expand wildcards, so the main method's argv will contain the
+ # expanded list instead of the wildcards.
+ #
+ # Adding dummy "-DEFAULTLIB:kernel32.lib", because:
+ # - Microsoft ships this object file next to default libraries
+ # - but this file is not a library, just a precompiled object
+ # - "-WHOLEARCHIVE" and "-DEFAULTLIB" only accept library,
+ # not precompiled object.
+ # - Bazel would assume linkopt that does not start with "-" or "$"
+ # as a label to a target, so we add a harmless "-DEFAULTLIB:kernel32.lib"
+ # before "setargv.obj".
+ # See https://msdn.microsoft.com/en-us/library/8bch7bkk.aspx
+ "-DEFAULTLIB:kernel32.lib setargv.obj",
+ ],
+ "//conditions:default": [],
+ }),
visibility = ["//visibility:public"],
deps = [":protobuf"],
)
@@ -404,6 +437,7 @@ RELATIVE_TEST_PROTOS = [
"google/protobuf/unittest_optimize_for.proto",
"google/protobuf/unittest_preserve_unknown_enum.proto",
"google/protobuf/unittest_preserve_unknown_enum2.proto",
+ "google/protobuf/unittest_proto3.proto",
"google/protobuf/unittest_proto3_arena.proto",
"google/protobuf/unittest_proto3_arena_lite.proto",
"google/protobuf/unittest_proto3_lite.proto",
@@ -419,6 +453,7 @@ RELATIVE_TEST_PROTOS = [
"google/protobuf/util/internal/testdata/struct.proto",
"google/protobuf/util/internal/testdata/timestamp_duration.proto",
"google/protobuf/util/internal/testdata/wrappers.proto",
+ "google/protobuf/util/json_format.proto",
"google/protobuf/util/json_format_proto3.proto",
"google/protobuf/util/message_differencer_unittest.proto",
]
@@ -513,6 +548,7 @@ cc_test(
"src/google/protobuf/proto3_arena_lite_unittest.cc",
"src/google/protobuf/proto3_arena_unittest.cc",
"src/google/protobuf/proto3_lite_unittest.cc",
+ "src/google/protobuf/proto3_lite_unittest.inc",
"src/google/protobuf/reflection_ops_unittest.cc",
"src/google/protobuf/repeated_field_reflection_unittest.cc",
"src/google/protobuf/repeated_field_unittest.cc",
@@ -610,6 +646,7 @@ py_library(
name = "python_srcs",
srcs = glob(
[
+ "python/google/__init__.py",
"python/google/protobuf/*.py",
"python/google/protobuf/**/*.py",
],
@@ -658,6 +695,7 @@ cc_binary(
linkstatic = 1,
deps = [
":protobuf",
+ ":proto_api",
] + select({
"//conditions:default": [],
":use_fast_cpp_protos": ["//external:python_headers"],
@@ -800,6 +838,15 @@ internal_protobuf_py_tests(
deps = [":python_tests"],
)
+cc_library(
+ name = "proto_api",
+ hdrs = ["python/google/protobuf/proto_api.h"],
+ deps = [
+ "//external:python_headers",
+ ],
+ visibility = ["//visibility:public"],
+)
+
proto_lang_toolchain(
name = "cc_toolchain",
command_line = "--cpp_out=$(OUT)",
@@ -889,9 +936,41 @@ OBJC_SRCS = [
objc_library(
name = "objectivec",
hdrs = OBJC_HDRS + OBJC_PRIVATE_HDRS,
+ copts = [
+ "-Wno-vla",
+ ],
includes = [
"objectivec",
],
non_arc_srcs = OBJC_SRCS,
visibility = ["//visibility:public"],
)
+
+################################################################################
+# Test generated proto support
+################################################################################
+
+genrule(
+ name = "generated_protos",
+ srcs = ["src/google/protobuf/unittest_import.proto"],
+ outs = ["unittest_gen.proto"],
+ cmd = "cat $(SRCS) | sed 's|google/|src/google/|' > $(OUTS)"
+)
+
+proto_library(
+ name = "generated_protos_proto",
+ srcs = [
+ "unittest_gen.proto",
+ "src/google/protobuf/unittest_import_public.proto",
+ ],
+)
+
+py_proto_library(
+ name = "generated_protos_py",
+ srcs = [
+ "unittest_gen.proto",
+ "src/google/protobuf/unittest_import_public.proto",
+ ],
+ default_runtime = "",
+ protoc = ":protoc",
+)
diff --git a/CHANGES.txt b/CHANGES.txt
index a381084a..5d11940b 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -102,7 +102,7 @@
Planned Future Changes
* Make C++ implementation C++11 only: we plan to require C++11 to build
protobuf code starting from 3.6.0 release. Please join this github issue:
- https://github.com/google/protobuf/issues/2780 to provide your feedback.
+ https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback.
protoc
* Fixed a bug introduced in 3.5.0 and protoc in Windows now accepts non-ascii
@@ -133,7 +133,7 @@
Planned Future Changes
* Make C++ implementation C++11 only: we plan to require C++11 to build
protobuf code starting from 3.6.0 release. Please join this github issue:
- https://github.com/google/protobuf/issues/2780 to provide your feedback.
+ https://github.com/protocolbuffers/protobuf/issues/2780 to provide your feedback.
General
* Unknown fields are now preserved in proto3 for most of the language
@@ -220,14 +220,14 @@
For issues and discussions:
- https://github.com/google/protobuf/issues/272
+ https://github.com/protocolbuffers/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
+ https://github.com/protocolbuffers/protobuf/issues/2780
to provide your feedback.
@@ -347,14 +347,14 @@
for the timeline and follow up this github issue:
- https://github.com/google/protobuf/issues/272
+ https://github.com/protocolbuffers/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
+ https://github.com/protocolbuffers/protobuf/issues/2780
to provide your feedback.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..49b19410
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,85 @@
+# Contributing to Protocol Buffers
+
+We welcome your contributions to protocol buffers. This doc describes the
+process to contribute patches to protobuf and the general guidelines we
+expect contributors to follow.
+
+## Before You Start
+
+We accept patches in the form of github pull requests. If you are new to
+github, please read [How to create github pull requests](https://help.github.com/articles/about-pull-requests/)
+first.
+
+### Contributor License Agreements
+
+Contributions to this project must be accompanied by a Contributor License
+Agreement. You (or your employer) retain the copyright to your contribution,
+this simply gives us permission to use and redistribute your contributions
+as part of the project.
+
+* If you are an individual writing original source code and you're sure you
+ own the intellectual property, then you'll need to sign an [individual CLA](https://cla.developers.google.com/about/google-individual?csw=1).
+* If you work for a company that wants to allow you to contribute your work,
+ then you'll need to sign a [corporate CLA](https://cla.developers.google.com/about/google-corporate?csw=1).
+
+### Coding Style
+
+This project follows [Google’s Coding Style Guides](https://github.com/google/styleguide).
+Before sending out your pull request, please familiarize yourself with the
+corresponding style guides and make sure the proposed code change is style
+conforming.
+
+## Contributing Process
+
+Most pull requests should go to the master branch and the change will be
+included in the next major/minor version release (e.g., 3.6.0 release). If you
+need to include a bug fix in a patch release (e.g., 3.5.2), make sure it’s
+already merged to master, and then create a pull request cherry-picking the
+commits from master branch to the release branch (e.g., branch 3.5.x).
+
+For each pull request, a protobuf team member will be assigned to review the
+pull request. For minor cleanups, the pull request may be merged right away
+after an initial review. For larger changes, you will likely receive multiple
+rounds of comments and it may take some time to complete. We will try to keep
+our response time within 7-days but if you don’t get any response in a few
+days, feel free to comment on the threads to get our attention. We also expect
+you to respond to our comments within a reasonable amount of time. If we don’t
+hear from you for 2 weeks or longer, we may close the pull request. You can
+still send the pull request again once you have time to work on it.
+
+Once a pull request is merged, we will take care of the rest and get it into
+the final release.
+
+## Pull Request Guidelines
+
+* If you are a Googler, it is preferable to first create an internal CL and
+ have it reviewed and submitted. The code propagation process will deliver the
+ change to GitHub.
+* Create small PRs that are narrowly focused on addressing a single concern.
+ We often receive PRs that are trying to fix several things at a time, but if
+ only one fix is considered acceptable, nothing gets merged and both author's
+ & review's time is wasted. Create more PRs to address different concerns and
+ everyone will be happy.
+* For speculative changes, consider opening an issue and discussing it first.
+ If you are suggesting a behavioral or API change, make sure you get explicit
+ support from a protobuf team member before sending us the pull request.
+* Provide a good PR description as a record of what change is being made and
+ why it was made. Link to a GitHub issue if it exists.
+* Don't fix code style and formatting unless you are already changing that
+ line to address an issue. PRs with irrelevant changes won't be merged. If
+ you do want to fix formatting or style, do that in a separate PR.
+* Unless your PR is trivial, you should expect there will be reviewer comments
+ that you'll need to address before merging. We expect you to be reasonably
+ responsive to those comments, otherwise the PR will be closed after 2-3 weeks
+ of inactivity.
+* Maintain clean commit history and use meaningful commit messages. PRs with
+ messy commit history are difficult to review and won't be merged. Use rebase
+ -i upstream/master to curate your commit history and/or to bring in latest
+ changes from master (but avoid rebasing in the middle of a code review).
+* Keep your PR up to date with upstream/master (if there are merge conflicts,
+ we can't really merge your change).
+* All tests need to be passing before your change can be merged. We recommend
+ you run tests locally before creating your PR to catch breakages early on.
+ Ultimately, the green signal will be provided by our testing infrastructure.
+ The reviewer will help you if there are test failures that seem not related
+ to the change you are making.
diff --git a/Makefile.am b/Makefile.am
index 8334db60..b0913a58 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -51,6 +51,7 @@ pkgconfig_DATA = protobuf.pc protobuf-lite.pc
csharp_EXTRA_DIST= \
csharp/.gitignore \
csharp/CHANGES.txt \
+ csharp/Google.Protobuf.Tools.targets \
csharp/Google.Protobuf.Tools.nuspec \
csharp/README.md \
csharp/build_packages.bat \
@@ -688,6 +689,18 @@ php_EXTRA_DIST= \
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/Internal/DescriptorProto_ExtensionRange.php \
+ php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php \
+ php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php \
+ php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php \
+ php/src/Google/Protobuf/Internal/FieldOptions_CType.php \
+ php/src/Google/Protobuf/Internal/FieldOptions_JSType.php \
+ php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php \
+ php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php \
+ php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php \
+ php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.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 \
@@ -804,6 +817,7 @@ python_EXTRA_DIST= \
python/google/protobuf/message.py \
python/google/protobuf/message_factory.py \
python/google/protobuf/python_protobuf.h \
+ python/google/protobuf/proto_api.h \
python/google/protobuf/proto_builder.py \
python/google/protobuf/pyext/README \
python/google/protobuf/pyext/__init__.py \
@@ -822,6 +836,10 @@ python_EXTRA_DIST= \
python/google/protobuf/pyext/map_container.h \
python/google/protobuf/pyext/message.cc \
python/google/protobuf/pyext/message.h \
+ python/google/protobuf/pyext/field.cc \
+ python/google/protobuf/pyext/field.h \
+ python/google/protobuf/pyext/unknown_fields.cc \
+ python/google/protobuf/pyext/unknown_fields.h \
python/google/protobuf/pyext/message_factory.cc \
python/google/protobuf/pyext/message_factory.h \
python/google/protobuf/pyext/message_module.cc \
@@ -933,6 +951,7 @@ js_EXTRA_DIST= \
js/commonjs/import_test.js \
js/commonjs/jasmine.json \
js/commonjs/rewrite_tests_for_commonjs.js \
+ js/commonjs/strict_test.js \
js/commonjs/test6/test6.proto \
js/commonjs/test7/test7.proto \
js/compatibility_tests/v3.0.0/binary/arith_test.js \
@@ -1004,6 +1023,8 @@ js_EXTRA_DIST= \
js/test4.proto \
js/test5.proto \
js/test8.proto \
+ js/test9.proto \
+ js/test10.proto \
js/test_bootstrap.js \
js/testbinary.proto \
js/testempty.proto
@@ -1022,6 +1043,7 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
WORKSPACE \
cmake/CMakeLists.txt \
cmake/README.md \
+ cmake/conformance.cmake \
cmake/examples.cmake \
cmake/extract_includes.bat.in \
cmake/install.cmake \
diff --git a/Protobuf.podspec b/Protobuf.podspec
index f282f540..1338b8d9 100644
--- a/Protobuf.podspec
+++ b/Protobuf.podspec
@@ -7,12 +7,12 @@ Pod::Spec.new do |s|
s.name = 'Protobuf'
s.version = '3.6.1'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
- s.homepage = 'https://github.com/google/protobuf'
+ s.homepage = 'https://github.com/protocolbuffers/protobuf'
s.license = '3-Clause BSD License'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.cocoapods_version = '>= 1.0'
- s.source = { :git => 'https://github.com/google/protobuf.git',
+ s.source = { :git => 'https://github.com/protocolbuffers/protobuf.git',
:tag => "v#{s.version}" }
s.source_files = 'objectivec/*.{h,m}',
diff --git a/README.md b/README.md
index 1a45ee60..c16ddf15 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ with the C++ runtime.
For non-C++ users, the simplest way to install the protocol compiler is to
download a pre-built binary from our release page:
- [https://github.com/google/protobuf/releases](https://github.com/google/protobuf/releases)
+ [https://github.com/protocolbuffers/protobuf/releases](https://github.com/protocolbuffers/protobuf/releases)
In the downloads section of each release, you can find pre-built binaries in
zip packages: protoc-$VERSION-$PLATFORM.zip. It contains the protoc binary
@@ -54,13 +54,13 @@ how to install protobuf runtime for that specific language:
| Language | Source | Ubuntu | MacOS | Windows |
|--------------------------------------|-------------------------------------------------------------|--------|-------|---------|
-| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) |
+| C++ (include C++ runtime and protoc) | [src](src) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-bazel.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fbazel%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) |
| Java | [java](java) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_compatibility%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_jdk7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_jdk7%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-java_oracle7.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjava_oracle7%2Fcontinuous) | | |
| Python | [python](python) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_cpp%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous) | |
| Objective-C | [objectivec](objectivec) | | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_cocoapods_integration.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_debug.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_osx.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous) | |
| C# | [csharp](csharp) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-csharp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcsharp%2Fcontinuous) | | [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) |
| JavaScript | [js](js) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous) | |
-| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_all%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby21.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby21%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby22.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby22%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-jruby.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjruby%2Fcontinuous) | |
+| Ruby | [ruby](ruby) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-ruby_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fruby_all%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby21.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby21%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-ruby22.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fruby22%2Fcontinuous) | |
| Go | [golang/protobuf](https://github.com/golang/protobuf) | | | |
| PHP | [php](php) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-php_all.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fphp_all%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-32-bit.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2F32-bit%2Fcontinuous) | [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php5.6_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp5.6_mac%2Fcontinuous)<br/>[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-php7.0_mac.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fphp7.0_mac%2Fcontinuous) | |
| Dart | [dart-lang/protobuf](https://github.com/dart-lang/protobuf) | | | |
diff --git a/WORKSPACE b/WORKSPACE
index 06a8a841..f3020843 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,16 +1,24 @@
workspace(name = "com_google_protobuf")
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
new_local_repository(
name = "submodule_gmock",
path = "third_party/googletest",
- build_file = "third_party/googletest/BUILD.bazel"
+ build_file = "@//:third_party/googletest/BUILD.bazel"
)
-new_http_archive(
+http_archive(
name = "six_archive",
- build_file = "six.BUILD",
+ build_file = "@//:six.BUILD",
sha256 = "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a",
- url = "https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55",
+ urls = ["https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55"],
+)
+
+http_archive(
+ name = "bazel_skylib",
+ sha256 = "bbccf674aa441c266df9894182d80de104cabd19be98be002f6d478aaa31574d",
+ strip_prefix = "bazel-skylib-2169ae1c374aab4a09aa90e65efe1a3aad4e279b",
+ urls = ["https://github.com/bazelbuild/bazel-skylib/archive/2169ae1c374aab4a09aa90e65efe1a3aad4e279b.tar.gz"],
)
bind(
diff --git a/appveyor.bat b/appveyor.bat
index e59ebccc..29ec4922 100644
--- a/appveyor.bat
+++ b/appveyor.bat
@@ -1,11 +1,23 @@
setlocal
+IF %platform%==MinGW GOTO build_mingw
IF %language%==cpp GOTO build_cpp
IF %language%==csharp GOTO build_csharp
-echo Unsupported language %language%. Exiting.
+echo Unsupported language %language% and platform %platform%. Exiting.
goto :error
+:build_mingw
+echo Building MinGW
+set PATH=C:\mingw-w64\x86_64-7.2.0-posix-seh-rt_v5-rev1\mingw64\bin;%PATH:C:\Program Files\Git\usr\bin;=%
+mkdir build_mingw
+cd build_mingw
+cmake -G "%generator%" -Dprotobuf_BUILD_SHARED_LIBS=%BUILD_DLL% -Dprotobuf_UNICODE=%UNICODE% -Dprotobuf_BUILD_TESTS=0 ../cmake
+mingw32-make -j8 all || goto error
+rem cd %configuration%
+rem tests.exe || goto error
+goto :EOF
+
:build_cpp
echo Building C++
mkdir build_msvc
diff --git a/appveyor.yml b/appveyor.yml
index 9644e066..91f737a8 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -1,22 +1,29 @@
-platform:
- - Win64
-
configuration:
- Debug
environment:
matrix:
- - language: cpp
+ # Only test few combinations: "Visual Studio 2015 (14) + Win64/MinGW + Debug + DLL". We can
+ # test more combinations but AppVeyor just takes too long to finish (each
+ # combination takes ~15mins).
+ - platform: MinGW
+ language: cpp
+ image: Visual Studio 2015
+
+ - platform: Win64
+ language: cpp
image: Visual Studio 2015
BUILD_DLL: ON
UNICODE: ON
- - language: cpp
+ - platform: Win64
+ language: cpp
image: Visual Studio 2017
BUILD_DLL: OFF
UNICODE: ON
- - language: csharp
+ - platform: Win64
+ language: csharp
image: Visual Studio 2017
# Our build scripts run tests automatically; we don't want AppVeyor
@@ -27,6 +34,7 @@ install:
- git submodule update --init --recursive
before_build:
+ - if %platform%==MinGW set generator=MinGW Makefiles
- if %platform%==Win32 set generator=Visual Studio 14
- if %platform%==Win64 set generator=Visual Studio 14 Win64
- if %platform%==Win32 set vcplatform=Win32
diff --git a/benchmarks/Makefile.am b/benchmarks/Makefile.am
index 3ae14ffb..c758ee6b 100644
--- a/benchmarks/Makefile.am
+++ b/benchmarks/Makefile.am
@@ -36,7 +36,7 @@ protoc_middleman2: make_tmp_dir $(top_srcdir)/src/protoc$(EXEEXT) $(benchmarks_
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd/cpp --java_out=$$oldpwd/tmp/java/src/main/java --python_out=$$oldpwd/tmp $(benchmarks_protoc_inputs_proto2) )
touch protoc_middleman2
-all_data = $$(find $(srcdir) -type f -name "dataset.*.pb" -not -path "./tmp/*")
+all_data = $$(find $$(cd $(srcdir) && pwd) -type f -name "dataset.*.pb" -not -path "$$(cd $(srcdir) && pwd)/tmp/*")
############# CPP RULES ##############
@@ -90,8 +90,7 @@ $(benchmarks_protoc_outputs_proto2_header): protoc_middleman2
initialize_submodule:
oldpwd=`pwd`
- cd $(top_srcdir)/third_party
- git submodule update --init -r
+ cd $(top_srcdir) && git submodule update --init -r third_party/benchmark
cd $(top_srcdir)/third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make
cd $$oldpwd
touch initialize_submodule
@@ -127,8 +126,10 @@ java_benchmark_testing_files = \
java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
javac_middleman: $(java_benchmark_testing_files) protoc_middleman protoc_middleman2
- cp -r $(srcdir)/java tmp && cd tmp/java && mvn clean compile assembly:single
- cd ../..
+ cp -r $(srcdir)/java tmp
+ mkdir -p tmp/java/lib
+ cp $(top_srcdir)/java/core/target/*.jar tmp/java/lib/protobuf-java.jar
+ cd tmp/java && mvn clean compile assembly:single -Dprotobuf.version=$(PACKAGE_VERSION) && cd ../..
@touch javac_middleman
java-benchmark: javac_middleman
@@ -138,10 +139,10 @@ java-benchmark: javac_middleman
@echo 'conf=()' >> java-benchmark
@echo 'data_files=""' >> java-benchmark
@echo 'for arg in $$@; do if [[ $${arg:0:1} == "-" ]]; then conf+=($$arg); else data_files+="$$arg,"; fi; done' >> java-benchmark
- @echo 'java -cp '"tmp/java/target/*.jar"' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark
- @echo '-b serializeToByteString,serializeToByteArray,serializeToMemoryStream,'"\\" >> java-benchmark
- @echo 'deserializeFromByteString,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark
- @echo '-DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark
+ @echo 'java -cp '\"tmp/java/target/*:$(top_srcdir)/java/core/target/*:$(top_srcdir)/java/util/target/*\"" \\" >>java-benchmark
+ @echo ' com.google.caliper.runner.CaliperMain com.google.protobuf.ProtoCaliperBenchmark -i runtime '"\\" >> java-benchmark
+ @echo ' -b serializeToByteArray,serializeToMemoryStream,deserializeFromByteArray,deserializeFromMemoryStream '"\\" >> java-benchmark
+ @echo ' -DdataFile=$${data_files:0:-1} $${conf[*]}' >> java-benchmark
@chmod +x java-benchmark
java: protoc_middleman protoc_middleman2 java-benchmark
@@ -180,8 +181,8 @@ nodist_libbenchmark_messages_la_SOURCES = \
python-pure-python-benchmark: python_add_init
@echo "Writing shortcut script python-pure-python-benchmark..."
@echo '#! /bin/bash' > python-pure-python-benchmark
- @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark
- @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-pure-python-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-pure-python-benchmark
@echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'python\' >> python-pure-python-benchmark
@echo cp $(srcdir)/python/py_benchmark.py tmp >> python-pure-python-benchmark
@echo python tmp/py_benchmark.py '$$@' >> python-pure-python-benchmark
@@ -190,8 +191,8 @@ python-pure-python-benchmark: python_add_init
python-cpp-reflection-benchmark: python_add_init
@echo "Writing shortcut script python-cpp-reflection-benchmark..."
@echo '#! /bin/bash' > python-cpp-reflection-benchmark
- @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark
- @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-reflection-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-reflection-benchmark
@echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-reflection-benchmark
@echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-reflection-benchmark
@echo python tmp/py_benchmark.py '$$@' >> python-cpp-reflection-benchmark
@@ -200,8 +201,8 @@ python-cpp-reflection-benchmark: python_add_init
python-cpp-generated-code-benchmark: python_add_init libbenchmark_messages.la
@echo "Writing shortcut script python-cpp-generated-code-benchmark..."
@echo '#! /bin/bash' > python-cpp-generated-code-benchmark
- @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark
- @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/libprotobuf.la >> python-cpp-generated-code-benchmark
+ @echo export LD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark
+ @echo export DYLD_LIBRARY_PATH=$(top_srcdir)/src/.libs >> python-cpp-generated-code-benchmark
@echo export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=\'cpp\' >> python-cpp-generated-code-benchmark
@echo cp $(srcdir)/python/py_benchmark.py tmp >> python-cpp-generated-code-benchmark
@echo python tmp/py_benchmark.py --cpp_generated '$$@' >> python-cpp-generated-code-benchmark
@@ -348,11 +349,11 @@ gogo_proto_middleman: protoc-gen-gogoproto
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --plugin=protoc-gen-gogoproto --gogoproto_out=$$oldpwd/tmp/gogo_proto $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) )
touch gogo_proto_middleman
-new_data = $$(for data in $(all_data); do echo "tmp$${data\#$(srcdir)}"; done | xargs)
+gogo_data = $$(for data in $(all_data); do echo "tmp/gogo_data$${data\#$(srcdir)}"; done | xargs)
generate_gogo_data: protoc_middleman protoc_middleman2 gogo-data-scrubber
- mkdir -p `dirname $(new_data)`
- ./gogo-data-scrubber $(all_data) $(new_data)
+ mkdir -p `dirname $(gogo_data)`
+ ./gogo-data-scrubber $(all_data) $(gogo_data)
touch generate_gogo_data
make_tmp_dir_gogo:
@@ -407,8 +408,6 @@ gogoslick_protoc_middleman: make_tmp_dir_gogo $(top_srcdir)/src/protoc$(EXEEXT)
oldpwd=`pwd` && ( cd $(srcdir)/tmp/gogo_proto && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$$oldpwd/$(top_srcdir)/src --gogoslick_out=$$oldpwd/tmp/gogoslick $(benchmarks_protoc_inputs_proto2_message4) )
touch gogoslick_protoc_middleman
-gogo_data = $$(find . -type f -name "dataset.*.pb" -path "./tmp/*")
-
generate-gogo-benchmark-code:
@echo '#! /bin/bash' > generate-gogo-benchmark-code
@echo 'cp $(srcdir)/go/go_benchmark_test.go tmp/$$1/benchmark_code/$$1_benchmark1_test.go' >> generate-gogo-benchmark-code
@@ -452,7 +451,7 @@ gogoslick: gogoslick_protoc_middleman generate_gogo_data gogo-benchmark generat
############ UTIL RULES BEGIN ############
-bin_PROGRAMS += protoc-gen-gogoproto gogo-data-scrubber
+bin_PROGRAMS += protoc-gen-gogoproto gogo-data-scrubber protoc-gen-proto2_to_proto3 proto3-data-stripper
protoc_gen_gogoproto_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la
protoc_gen_gogoproto_SOURCES = util/protoc-gen-gogoproto.cc
@@ -467,9 +466,138 @@ nodist_gogo_data_scrubber_SOURCES = \
$(benchmarks_protoc_outputs_proto2) \
$(benchmarks_protoc_outputs_proto2_header) \
$(benchmarks_protoc_outputs_header)
+
+protoc_gen_proto2_to_proto3_LDADD = $(top_srcdir)/src/libprotobuf.la $(top_srcdir)/src/libprotoc.la
+protoc_gen_proto2_to_proto3_SOURCES = util/protoc-gen-proto2_to_proto3.cc
+protoc_gen_proto2_to_proto3_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util
+
+proto3_data_stripper_LDADD = $(top_srcdir)/src/libprotobuf.la
+proto3_data_stripper_SOURCES = util/proto3_data_stripper.cc
+proto3_data_stripper_CPPFLAGS = -I$(top_srcdir)/src -I$(srcdir)/cpp -I$(srcdir)/util
+util/proto3_data_stripper-proto3_data_stripper.$(OBJEXT): $(benchmarks_protoc_outputs) $(benchmarks_protoc_outputs_proto2) $(benchmarks_protoc_outputs_header) $(benchmarks_protoc_outputs_proto2_header)
+nodist_proto3_data_stripper_SOURCES = \
+ $(benchmarks_protoc_outputs) \
+ $(benchmarks_protoc_outputs_proto2) \
+ $(benchmarks_protoc_outputs_proto2_header) \
+ $(benchmarks_protoc_outputs_header)
+
############ UTIL RULES END ############
+############ PROTO3 PREPARATION BEGIN #############
+
+proto3_proto_middleman: protoc-gen-proto2_to_proto3
+ mkdir -p "tmp/proto3_proto"
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --plugin=protoc-gen-proto2_to_proto3 --proto2_to_proto3_out=$$oldpwd/tmp/proto3_proto $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) )
+ touch proto3_proto_middleman
+
+full_srcdir = $$(cd $(srcdir) && pwd)
+proto3_data = $$(for data in $(all_data); do echo $(full_srcdir)"/tmp/proto3_data$${data\#$(full_srcdir)}"; done | xargs)
+
+generate_proto3_data: protoc_middleman protoc_middleman2 proto3-data-stripper
+ mkdir -p `dirname $(proto3_data)`
+ ./proto3-data-stripper $(all_data) $(proto3_data)
+ touch generate_proto3_data
+
+############ PROTO3 PREPARATION END #############
+
+############ PHP RULES BEGIN #################
+
+proto3_middleman_php: proto3_proto_middleman
+ mkdir -p "tmp/php"
+ oldpwd=`pwd` && ( cd tmp/proto3_proto && $$oldpwd/../src/protoc$(EXEEXT) -I$(srcdir) -I$(top_srcdir) --php_out=$$oldpwd/tmp/php $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2) )
+ touch proto3_middleman_php
+
+php-benchmark: proto3_middleman_php generate_proto3_data
+ mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark"
+ cp php/autoload.php "tmp/php"
+ @echo "Writing shortcut script php-benchmark..."
+ @echo '#! /bin/bash' > php-benchmark
+ @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-benchmark
+ @echo 'cd tmp/php' >> php-benchmark
+ @echo 'export CURRENT_DIR=$$(pwd)' >> php-benchmark
+ @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-benchmark
+ @echo 'cd ../..' >> php-benchmark
+ @chmod +x php-benchmark
+
+php: php-benchmark proto3_middleman_php
+ ./php-benchmark $(proto3_data)
+
+php_c_extension:
+ cd $(top_srcdir)/php/ext/google/protobuf && ./configure CFLAGS='-O3' && make -j8
+
+php-c-benchmark: proto3_middleman_php generate_proto3_data php_c_extension php_c_extension
+ mkdir -p "tmp/php/Google/Protobuf/Benchmark" && cp php/PhpBenchmark.php "tmp/php/Google/Protobuf/Benchmark"
+ cp php/autoload.php "tmp/php"
+ @echo "Writing shortcut script php-c-benchmark..."
+ @echo '#! /bin/bash' > php-c-benchmark
+ @echo 'export PROTOBUF_PHP_SRCDIR="$$(cd $(top_srcdir) && pwd)/php/src"' >> php-c-benchmark
+ @echo 'export PROTOBUF_PHP_EXTDIR="$$PROTOBUF_PHP_SRCDIR/../ext/google/protobuf/modules"' >> php-c-benchmark
+ @echo 'echo "$$PROTOBUF_PHP_EXTDIR/protobuf.so"' >> php-c-benchmark
+ @echo 'cd tmp/php' >> php-c-benchmark
+ @echo 'export CURRENT_DIR=$$(pwd)' >> php-c-benchmark
+ @echo 'php -d auto_prepend_file="autoload.php" -d include_path="$$(pwd)" -d extension="$$PROTOBUF_PHP_EXTDIR/protobuf.so" Google/Protobuf/Benchmark/PhpBenchmark.php $$@' >> php-c-benchmark
+ @echo 'cd ../..' >> php-c-benchmark
+ @chmod +x php-c-benchmark
+
+php_c: php-c-benchmark proto3_middleman_php
+ ./php-c-benchmark $(proto3_data)
+
+
+############ PHP RULES END #################
+
+############ protobuf.js RULE BEGIN #############
+
+pbjs_preparation:
+ mkdir -p tmp/protobuf.js
+ cd tmp/protobuf.js && git clone https://github.com/dcodeIO/protobuf.js.git && \
+ cd protobuf.js && npm install && npm run build
+ cd tmp/protobuf.js && npm install benchmark
+ cp protobuf.js/* tmp/protobuf.js
+ cp js/benchmark_suite.js tmp/protobuf.js
+ touch pbjs_preparation
+
+pbjs_middleman: pbjs_preparation
+ export OLDDIR=$$(pwd) && cd tmp/protobuf.js && node generate_pbjs_files.js --target static-module --include_path=$$OLDDIR -o generated_bundle_code.js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2)
+ touch pbjs_middleman
+
+pbjs-benchmark: pbjs_middleman
+ @echo '#! /bin/bash' > pbjs-benchmark
+ @echo 'cd tmp/protobuf.js' >> pbjs-benchmark
+ @echo 'sed -i "s/protobufjs/.\/protobuf.js/g" generated_bundle_code.js' >> pbjs-benchmark
+ @echo 'env NODE_PATH=".:./node_modules:$$NODE_PATH" node protobufjs_benchmark.js $$@' >> pbjs-benchmark
+ @chmod +x pbjs-benchmark
+
+pbjs: pbjs-benchmark
+ ./pbjs-benchmark $(all_data)
+
+############ protobuf.js RULE END #############
+
+############ JS RULE BEGIN #############
+
+js_preparation:
+ mkdir -p tmp/js
+ oldpwd=$$(pwd) && cd $(top_srcdir)/js && npm install && npm test
+ cd tmp/js && npm install benchmark
+ cp js/* tmp/js
+ touch js_preparation
+
+js_middleman: js_preparation
+ oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --js_out=import_style=commonjs,binary:$$oldpwd/tmp/js $(benchmarks_protoc_inputs) $(benchmarks_protoc_inputs_benchmark_wrapper) $(benchmarks_protoc_inputs_proto2))
+ touch js_middleman
+
+js-benchmark: js_middleman
+ @echo '#! /bin/bash' > js-benchmark
+ @echo 'export TOP_JS_SRCDIR=$$(cd $(top_srcdir)/js && pwd)' >> js-benchmark
+ @echo 'cd tmp/js' >> js-benchmark
+ @echo 'env NODE_PATH="$$TOP_JS_SRCDIR:.:./node_modules:$$NODE_PATH" node --max-old-space-size=4096 js_benchmark.js $$@' >> js-benchmark
+ @chmod +x js-benchmark
+
+js: js-benchmark
+ ./js-benchmark $(all_data)
+
+############ JS RULE END #############
+
MAINTAINERCLEANFILES = \
Makefile.in
@@ -512,8 +640,19 @@ CLEANFILES = \
gogoslick_protoc_middleman \
gogoslick \
gogo-benchmark \
- gogo/cpp_no_group/cpp_benchmark.*
-
+ gogo/cpp_no_group/cpp_benchmark.* \
+ proto3_proto_middleman \
+ generate_proto3_data \
+ php-benchmark \
+ php-c-benchmark \
+ proto3_middleman_php \
+ pbjs_preparation \
+ pbjs_middleman \
+ pbjs-benchmark \
+ js_preparation \
+ js_middleman \
+ js-benchmark
clean-local:
-rm -rf tmp/*
+
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 21cd7352..72885886 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -5,7 +5,7 @@ This directory contains benchmarking schemas and data sets that you
can use to test a variety of performance scenarios against your
protobuf language runtime. If you are looking for performance
numbers of officially support languages, see [here](
-https://github.com/google/protobuf/blob/master/docs/Performance.md)
+https://github.com/protocolbuffers/protobuf/blob/master/docs/performance.md)
## Prerequisite
@@ -58,6 +58,13 @@ $ export PATH=$PATH:$(go env GOPATH)/bin
The first command installs `protoc-gen-go` into the `bin` directory in your local `GOPATH`.
The second command adds the `bin` directory to your `PATH` so that `protoc` can locate the plugin later.
+### PHP
+PHP benchmark's requirement is the same as PHP protobuf's requirements. The benchmark will automaticly
+include PHP protobuf's src and build the c extension if required.
+
+### Node.js
+Node.js benchmark need [node](https://nodejs.org/en/)(higher than V6) and [npm](https://www.npmjs.com/) package manager installed. This benchmark is using the [benchmark](https://www.npmjs.com/package/benchmark) framework to test, which needn't to manually install. And another prerequisite is [protobuf js](https://github.com/protocolbuffers/protobuf/tree/master/js), which needn't to manually install either
+
### Big data
There's some optional big testing data which is not included in the directory
@@ -120,6 +127,23 @@ $ make python-cpp-generated-code
$ make go
```
+
+### PHP
+We have two version of php protobuf implemention: pure php, php with c extension. To run these version benchmark, you need to:
+#### Pure PHP
+```
+$ make php
+```
+#### PHP with c extension
+```
+$ make php_c
+```
+
+### Node.js
+```
+$ make js
+```
+
To run a specific dataset or run with specific options:
### Java:
@@ -167,6 +191,23 @@ $ make go-benchmark
$ ./go-benchmark $(specific generated dataset file name) [go testing options]
```
+### PHP
+#### Pure PHP
+```
+$ make php-benchmark
+$ ./php-benchmark $(specific generated dataset file name)
+```
+#### PHP with c extension
+```
+$ make php-c-benchmark
+$ ./php-c-benchmark $(specific generated dataset file name)
+```
+
+### Node.js
+```
+$ make js-benchmark
+$ ./js-benchmark $(specific generated dataset file name)
+```
## Benchmark datasets
diff --git a/benchmarks/cpp/cpp_benchmark.cc b/benchmarks/cpp/cpp_benchmark.cc
index f8b55291..036d234f 100644
--- a/benchmarks/cpp/cpp_benchmark.cc
+++ b/benchmarks/cpp/cpp_benchmark.cc
@@ -30,7 +30,7 @@
#include <fstream>
#include <iostream>
-#include "benchmark/benchmark_api.h"
+#include "benchmark/benchmark.h"
#include "benchmarks.pb.h"
#include "datasets/google_message1/proto2/benchmark_message1_proto2.pb.h"
#include "datasets/google_message1/proto3/benchmark_message1_proto3.pb.h"
diff --git a/benchmarks/java/pom.xml b/benchmarks/java/pom.xml
index c2cd78a1..570bd664 100755..100644
--- a/benchmarks/java/pom.xml
+++ b/benchmarks/java/pom.xml
@@ -14,7 +14,10 @@
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
- <version>3.5.0</version>
+ <version>${protobuf.version}</version>
+ <type>jar</type>
+ <scope>system</scope>
+ <systemPath>${project.basedir}/lib/protobuf-java.jar</systemPath>
</dependency>
<dependency>
<groupId>com.google.caliper</groupId>
diff --git a/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
index 94568aea..c766d74e 100755..100644
--- a/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
+++ b/benchmarks/java/src/main/java/com/google/protobuf/ProtoCaliperBenchmark.java
@@ -5,6 +5,7 @@ import com.google.caliper.BeforeExperiment;
import com.google.caliper.AfterExperiment;
import com.google.caliper.Benchmark;
import com.google.caliper.Param;
+import com.google.caliper.api.VmOptions;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.ExtensionRegistry;
@@ -22,6 +23,12 @@ import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
+// Caliper set CICompilerCount to 1 for making sure compilation doesn't run in parallel with itself,
+// This makes TieredCompilation not working. We just disable TieredCompilation by default. In master
+// branch this has been disabled by default in caliper:
+// https://github.com/google/caliper/blob/master/caliper-runner/src/main/java/com/google/caliper/runner/target/Jvm.java#L38:14
+// But this haven't been added into most recent release.
+@VmOptions("-XX:-TieredCompilation")
public class ProtoCaliperBenchmark {
public enum BenchmarkMessageType {
GOOGLE_MESSAGE1_PROTO3 {
@@ -152,18 +159,6 @@ public class ProtoCaliperBenchmark {
@Benchmark
- void serializeToByteString(int reps) throws IOException {
- if (sampleMessageList.size() == 0) {
- return;
- }
- for (int i = 0; i < reps; i++) {
- for (int j = 0; j < sampleMessageList.size(); j++) {
- sampleMessageList.get(j).toByteString();
- }
- }
- }
-
- @Benchmark
void serializeToByteArray(int reps) throws IOException {
if (sampleMessageList.size() == 0) {
return;
@@ -189,19 +184,6 @@ public class ProtoCaliperBenchmark {
}
@Benchmark
- void deserializeFromByteString(int reps) throws IOException {
- if (inputStringList.size() == 0) {
- return;
- }
- for (int i = 0; i < reps; i++) {
- for (int j = 0; j < inputStringList.size(); j++) {
- benchmarkMessageType.getDefaultInstance().getParserForType().parseFrom(
- inputStringList.get(j), extensions);
- }
- }
- }
-
- @Benchmark
void deserializeFromByteArray(int reps) throws IOException {
if (inputDataList.size() == 0) {
return;
diff --git a/benchmarks/js/benchmark_suite.js b/benchmarks/js/benchmark_suite.js
new file mode 100644
index 00000000..c95024b2
--- /dev/null
+++ b/benchmarks/js/benchmark_suite.js
@@ -0,0 +1,33 @@
+var benchmark = require("benchmark");
+
+function newBenchmark(messageName, filename, language) {
+ var benches = [];
+ return {
+ suite: new benchmark.Suite(messageName + filename + language )
+ .on("add", function(event) {
+ benches.push(event.target);
+ })
+ .on("start", function() {
+ process.stdout.write(
+ "benchmarking message " + messageName
+ + " of dataset file " + filename
+ + "'s performance ..." + "\n\n");
+ })
+ .on("cycle", function(event) {
+ process.stdout.write(String(event.target) + "\n");
+ })
+ .on("complete", function() {
+ var getHz = function(bench) {
+ return 1 / (bench.stats.mean + bench.stats.moe);
+ }
+ benches.forEach(function(val, index) {
+ benches[index] = getHz(val);
+ });
+ }),
+ benches: benches
+ }
+}
+
+module.exports = {
+ newBenchmark: newBenchmark
+}
diff --git a/benchmarks/js/js_benchmark.js b/benchmarks/js/js_benchmark.js
new file mode 100644
index 00000000..14905e31
--- /dev/null
+++ b/benchmarks/js/js_benchmark.js
@@ -0,0 +1,70 @@
+require('./datasets/google_message1/proto2/benchmark_message1_proto2_pb.js');
+require('./datasets/google_message1/proto3/benchmark_message1_proto3_pb.js');
+require('./datasets/google_message2/benchmark_message2_pb.js');
+require('./datasets/google_message3/benchmark_message3_pb.js');
+require('./datasets/google_message4/benchmark_message4_pb.js');
+require('./benchmarks_pb.js');
+
+var fs = require('fs');
+var benchmarkSuite = require("./benchmark_suite.js");
+
+
+function getNewPrototype(name) {
+ var message = eval("proto." + name);
+ if (typeof(message) == "undefined") {
+ throw "type " + name + " is undefined";
+ }
+ return message;
+}
+
+var results = [];
+
+console.log("#####################################################");
+console.log("Js Benchmark: ");
+process.argv.forEach(function(filename, index) {
+ if (index < 2) {
+ return;
+ }
+ var benchmarkDataset =
+ proto.benchmarks.BenchmarkDataset.deserializeBinary(fs.readFileSync(filename));
+ var messageList = [];
+ var totalBytes = 0;
+ benchmarkDataset.getPayloadList().forEach(function(onePayload) {
+ var message = getNewPrototype(benchmarkDataset.getMessageName());
+ messageList.push(message.deserializeBinary(onePayload));
+ totalBytes += onePayload.length;
+ });
+
+ var senarios = benchmarkSuite.newBenchmark(
+ benchmarkDataset.getMessageName(), filename, "js");
+ senarios.suite
+ .add("js deserialize", function() {
+ benchmarkDataset.getPayloadList().forEach(function(onePayload) {
+ var protoType = getNewPrototype(benchmarkDataset.getMessageName());
+ protoType.deserializeBinary(onePayload);
+ });
+ })
+ .add("js serialize", function() {
+ var protoType = getNewPrototype(benchmarkDataset.getMessageName());
+ messageList.forEach(function(message) {
+ message.serializeBinary();
+ });
+ })
+ .run({"Async": false});
+
+ results.push({
+ filename: filename,
+ benchmarks: {
+ protobufjs_decoding: senarios.benches[0] * totalBytes,
+ protobufjs_encoding: senarios.benches[1] * totalBytes
+ }
+ })
+
+ console.log("Throughput for deserialize: "
+ + senarios.benches[0] * totalBytes / 1024 / 1024 + "MB/s" );
+ console.log("Throughput for serialize: "
+ + senarios.benches[1] * totalBytes / 1024 / 1024 + "MB/s" );
+ console.log("");
+});
+console.log("#####################################################");
+
diff --git a/benchmarks/php/PhpBenchmark.php b/benchmarks/php/PhpBenchmark.php
new file mode 100644
index 00000000..058940d1
--- /dev/null
+++ b/benchmarks/php/PhpBenchmark.php
@@ -0,0 +1,157 @@
+<?php
+
+namespace Google\Protobuf\Benchmark;
+
+const NAME = "PhpBenchmark.php";
+
+function _require_all($dir, &$prefix) {
+ // require all php files
+ foreach (glob("$dir/*") as $path) {
+ if (preg_match('/\.php$/', $path) &&
+ substr($path, -strlen(NAME)) != NAME) {
+ require_once(substr($path, strlen($prefix) + 1));
+ } elseif (is_dir($path)) {
+ _require_all($path, $prefix);
+ }
+ }
+}
+// include all file
+foreach (explode(PATH_SEPARATOR, get_include_path()) as $one_include_path) {
+ _require_all($one_include_path, $one_include_path);
+}
+
+use Benchmarks\BenchmarkDataset;
+
+class BenchmarkMethod
+{
+ // $args[0]: dataset
+ // $args[1]: message class
+ static function parse(&$args) {
+ $payloads = $args[0]->getPayload();
+ for ($i = $payloads->count() - 1; $i >= 0; $i--) {
+ (new $args[1]())->mergeFromString($payloads->offsetGet($i));
+ }
+ }
+
+ // $args: array of message
+ static function serialize(&$args) {
+ foreach ($args as &$temp_message) {
+ $temp_message->serializeToString();
+ }
+ }
+}
+
+class Benchmark
+{
+ private $benchmark_name;
+ private $args;
+ private $benchmark_time;
+ private $total_bytes;
+ private $coefficient;
+
+ public function __construct($benchmark_name, $args, $total_bytes,
+ $benchmark_time = 5.0) {
+ $this->args = $args;
+ $this->benchmark_name = $benchmark_name;
+ $this->benchmark_time = $benchmark_time;
+ $this->total_bytes = $total_bytes;
+ $this->coefficient = pow (10, 0) / pow(2, 20);
+ }
+
+ public function runBenchmark() {
+ $t = $this->runBenchmarkWithTimes(1);
+ $times = ceil($this->benchmark_time / $t);
+ return $this->total_bytes * $times /
+ $this->runBenchmarkWithTimes($times) *
+ $this->coefficient;
+ }
+
+ private function runBenchmarkWithTimes($times) {
+ $st = microtime(true);
+ for ($i = 0; $i < $times; $i++) {
+ call_user_func_array($this->benchmark_name, array(&$this->args));
+ }
+ $en = microtime(true);
+ return $en - $st;
+ }
+}
+
+function getMessageName(&$dataset) {
+ switch ($dataset->getMessageName()) {
+ case "benchmarks.proto3.GoogleMessage1":
+ return "\Benchmarks\Proto3\GoogleMessage1";
+ case "benchmarks.proto2.GoogleMessage1":
+ return "\Benchmarks\Proto2\GoogleMessage1";
+ case "benchmarks.proto2.GoogleMessage2":
+ return "\Benchmarks\Proto2\GoogleMessage2";
+ case "benchmarks.google_message3.GoogleMessage3":
+ return "\Benchmarks\Google_message3\GoogleMessage3";
+ case "benchmarks.google_message4.GoogleMessage4":
+ return "\Benchmarks\Google_message4\GoogleMessage4";
+ default:
+ exit("Message " . $dataset->getMessageName() . " not found !");
+ }
+}
+
+function runBenchmark($file) {
+ $datafile = fopen($file, "r") or die("Unable to open file " . $file);
+ $bytes = fread($datafile, filesize($file));
+ $dataset = new BenchmarkDataset(NULL);
+ $dataset->mergeFromString($bytes);
+ $message_name = getMessageName($dataset);
+ $message_list = array();
+ $total_bytes = 0;
+ $payloads = $dataset->getPayload();
+ for ($i = $payloads->count() - 1; $i >= 0; $i--) {
+ $new_message = new $message_name();
+ $new_message->mergeFromString($payloads->offsetGet($i));
+ array_push($message_list, $new_message);
+ $total_bytes += strlen($payloads->offsetGet($i));
+ }
+
+ $parse_benchmark = new Benchmark(
+ "\Google\Protobuf\Benchmark\BenchmarkMethod::parse",
+ array($dataset, $message_name), $total_bytes);
+ $serialize_benchmark = new Benchmark(
+ "\Google\Protobuf\Benchmark\BenchmarkMethod::serialize",
+ $message_list, $total_bytes);
+
+ return array(
+ "filename" => $file,
+ "benchmarks" => array(
+ "parse_php" => $parse_benchmark->runBenchmark(),
+ "serailize_php" => $serialize_benchmark->runBenchmark()
+ ),
+ "message_name" => $dataset->getMessageName()
+ );
+}
+
+// main
+$json_output = false;
+$results = array();
+foreach ($argv as $index => $arg) {
+ if ($index == 0) {
+ continue;
+ }
+ if ($arg == "--json") {
+ $json_output = true;
+ continue;
+ } else {
+ array_push($results, runBenchmark($arg));
+ }
+}
+
+if ($json_output) {
+ print json_encode($results);
+} else {
+ print "PHP protobuf benchmark result:\n\n";
+ foreach ($results as $result) {
+ printf("result for test data file: %s\n", $result["filename"]);
+ foreach ($result["benchmarks"] as $benchmark => $throughput) {
+ printf(" Throughput for benchmark %s: %.2f MB/s\n",
+ $benchmark, $throughput);
+ }
+ }
+}
+
+?>
diff --git a/benchmarks/php/autoload.php b/benchmarks/php/autoload.php
new file mode 100644
index 00000000..52a8741f
--- /dev/null
+++ b/benchmarks/php/autoload.php
@@ -0,0 +1,25 @@
+<?php
+
+define("GOOGLE_INTERNAL_NAMESPACE", "Google\\Protobuf\\Internal\\");
+define("GOOGLE_NAMESPACE", "Google\\Protobuf\\");
+define("GOOGLE_GPBMETADATA_NAMESPACE", "GPBMetadata\\Google\\Protobuf\\");
+define("BENCHMARK_NAMESPACE", "Benchmarks");
+define("BENCHMARK_GPBMETADATA_NAMESPACE", "GPBMetadata\\Benchmarks");
+
+function protobuf_autoloader_impl($class, $prefix, $include_path) {
+ $length = strlen($prefix);
+ if ((substr($class, 0, $length) === $prefix)) {
+ $path = $include_path . '/' . implode('/', array_map('ucwords', explode('\\', $class))) . '.php';
+ include_once $path;
+ }
+}
+
+function protobuf_autoloader($class) {
+ protobuf_autoloader_impl($class, GOOGLE_INTERNAL_NAMESPACE, getenv('PROTOBUF_PHP_SRCDIR'));
+ protobuf_autoloader_impl($class, GOOGLE_NAMESPACE, getenv('PROTOBUF_PHP_SRCDIR'));
+ protobuf_autoloader_impl($class, GOOGLE_GPBMETADATA_NAMESPACE, getenv('PROTOBUF_PHP_SRCDIR'));
+ protobuf_autoloader_impl($class, BENCHMARK_NAMESPACE, getenv('CURRENT_DIR'));
+ protobuf_autoloader_impl($class, BENCHMARK_GPBMETADATA_NAMESPACE, getenv('CURRENT_DIR'));
+}
+
+spl_autoload_register('protobuf_autoloader');
diff --git a/benchmarks/protobuf.js/generate_pbjs_files.js b/benchmarks/protobuf.js/generate_pbjs_files.js
new file mode 100644
index 00000000..11945bf9
--- /dev/null
+++ b/benchmarks/protobuf.js/generate_pbjs_files.js
@@ -0,0 +1,25 @@
+var pbjs = require("./protobuf.js/cli").pbjs
+
+var argv = [];
+var protoFiles = [];
+var prefix = "";
+process.argv.forEach(function(val, index) {
+ var arg = val;
+ if (arg.length > 6 && arg.substring(arg.length - 6) == ".proto") {
+ protoFiles.push(arg);
+ } else if (arg.length > 15 && arg.substring(0, 15) == "--include_path=") {
+ prefix = arg.substring(15);
+ } else if (index >= 2) {
+ argv.push(arg);
+ }
+});
+protoFiles.forEach(function(val) {
+ argv.push(prefix + "/" + val);
+});
+
+pbjs.main(argv, function(err, output){
+ if (err) {
+ console.log(err);
+ }
+});
+
diff --git a/benchmarks/protobuf.js/protobufjs_benchmark.js b/benchmarks/protobuf.js/protobufjs_benchmark.js
new file mode 100644
index 00000000..2629e9f4
--- /dev/null
+++ b/benchmarks/protobuf.js/protobufjs_benchmark.js
@@ -0,0 +1,66 @@
+var root = require("./generated_bundle_code.js");
+var fs = require('fs');
+var benchmark = require("./node_modules/benchmark");
+var benchmarkSuite = require("./benchmark_suite.js");
+
+
+function getNewPrototype(name) {
+ var message = eval("root." + name);
+ if (typeof(message) == "undefined") {
+ throw "type " + name + " is undefined";
+ }
+ return message;
+}
+
+
+var results = [];
+
+console.log("#####################################################");
+console.log("ProtobufJs Benchmark: ");
+process.argv.forEach(function(filename, index) {
+ if (index < 2) {
+ return;
+ }
+ var benchmarkDataset =
+ root.benchmarks.BenchmarkDataset.decode(fs.readFileSync(filename));
+ var messageList = [];
+ var totalBytes = 0;
+ benchmarkDataset.payload.forEach(function(onePayload) {
+ var message = getNewPrototype(benchmarkDataset.messageName);
+ messageList.push(message.decode(onePayload));
+ totalBytes += onePayload.length;
+ });
+
+ var senarios = benchmarkSuite.newBenchmark(
+ benchmarkDataset.messageName, filename, "protobufjs");
+ senarios.suite
+ .add("protobuf.js static decoding", function() {
+ benchmarkDataset.payload.forEach(function(onePayload) {
+ var protoType = getNewPrototype(benchmarkDataset.messageName);
+ protoType.decode(onePayload);
+ });
+ })
+ .add("protobuf.js static encoding", function() {
+ var protoType = getNewPrototype(benchmarkDataset.messageName);
+ messageList.forEach(function(message) {
+ protoType.encode(message).finish();
+ });
+ })
+ .run({"Async": false});
+
+ results.push({
+ filename: filename,
+ benchmarks: {
+ protobufjs_decoding: senarios.benches[0] * totalBytes,
+ protobufjs_encoding: senarios.benches[1] * totalBytes
+ }
+ })
+
+ console.log("Throughput for decoding: "
+ + senarios.benches[0] * totalBytes / 1024 / 1024 + "MB/s" );
+ console.log("Throughput for encoding: "
+ + senarios.benches[1] * totalBytes / 1024 / 1024 + "MB/s" );
+ console.log("");
+});
+console.log("#####################################################");
+
diff --git a/benchmarks/python/py_benchmark.py b/benchmarks/python/py_benchmark.py
index 6942d208..e86b61e7 100755
--- a/benchmarks/python/py_benchmark.py
+++ b/benchmarks/python/py_benchmark.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import sys
import os
import timeit
@@ -138,15 +139,15 @@ if __name__ == "__main__":
results.append(run_one_test(file))
if args.json != "no":
- print json.dumps(results)
+ print(json.dumps(results))
else:
for result in results:
- print "Message %s of dataset file %s" % \
- (result["message_name"], result["filename"])
- print "Average time for parse_from_benchmark: %.2f ns" % \
+ print("Message %s of dataset file %s" % \
+ (result["message_name"], result["filename"]))
+ print("Average time for parse_from_benchmark: %.2f ns" % \
(result["benchmarks"][ \
- args.behavior_prefix + "_parse_from_benchmark"])
- print "Average time for serialize_to_benchmark: %.2f ns" % \
+ args.behavior_prefix + "_parse_from_benchmark"]))
+ print("Average time for serialize_to_benchmark: %.2f ns" % \
(result["benchmarks"][ \
- args.behavior_prefix + "_serialize_to_benchmark"])
- print ""
+ args.behavior_prefix + "_serialize_to_benchmark"]))
+ print("")
diff --git a/benchmarks/util/big_query_utils.py b/benchmarks/util/big_query_utils.py
index 14105aa6..aea55bbd 100755
--- a/benchmarks/util/big_query_utils.py
+++ b/benchmarks/util/big_query_utils.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python2.7
+from __future__ import print_function
import argparse
import json
import uuid
@@ -37,11 +38,11 @@ def create_dataset(biq_query, project_id, dataset_id):
dataset_req.execute(num_retries=NUM_RETRIES)
except HttpError as http_error:
if http_error.resp.status == 409:
- print 'Warning: The dataset %s already exists' % dataset_id
+ print('Warning: The dataset %s already exists' % dataset_id)
else:
# Note: For more debugging info, print "http_error.content"
- print 'Error in creating dataset: %s. Err: %s' % (dataset_id,
- http_error)
+ print('Error in creating dataset: %s. Err: %s' % (dataset_id,
+ http_error))
is_success = False
return is_success
@@ -109,13 +110,13 @@ def create_table2(big_query,
table_req = big_query.tables().insert(
projectId=project_id, datasetId=dataset_id, body=body)
res = table_req.execute(num_retries=NUM_RETRIES)
- print 'Successfully created %s "%s"' % (res['kind'], res['id'])
+ print('Successfully created %s "%s"' % (res['kind'], res['id']))
except HttpError as http_error:
if http_error.resp.status == 409:
- print 'Warning: Table %s already exists' % table_id
+ print('Warning: Table %s already exists' % table_id)
else:
- print 'Error in creating table: %s. Err: %s' % (table_id,
- http_error)
+ print('Error in creating table: %s. Err: %s' % (table_id,
+ http_error))
is_success = False
return is_success
@@ -141,9 +142,9 @@ def patch_table(big_query, project_id, dataset_id, table_id, fields_schema):
tableId=table_id,
body=body)
res = table_req.execute(num_retries=NUM_RETRIES)
- print 'Successfully patched %s "%s"' % (res['kind'], res['id'])
+ print('Successfully patched %s "%s"' % (res['kind'], res['id']))
except HttpError as http_error:
- print 'Error in creating table: %s. Err: %s' % (table_id, http_error)
+ print('Error in creating table: %s. Err: %s' % (table_id, http_error))
is_success = False
return is_success
@@ -159,10 +160,10 @@ def insert_rows(big_query, project_id, dataset_id, table_id, rows_list):
body=body)
res = insert_req.execute(num_retries=NUM_RETRIES)
if res.get('insertErrors', None):
- print 'Error inserting rows! Response: %s' % res
+ print('Error inserting rows! Response: %s' % res)
is_success = False
except HttpError as http_error:
- print 'Error inserting rows to the table %s' % table_id
+ print('Error inserting rows to the table %s' % table_id)
is_success = False
return is_success
@@ -176,8 +177,8 @@ def sync_query_job(big_query, project_id, query, timeout=5000):
projectId=project_id,
body=query_data).execute(num_retries=NUM_RETRIES)
except HttpError as http_error:
- print 'Query execute job failed with error: %s' % http_error
- print http_error.content
+ print('Query execute job failed with error: %s' % http_error)
+ print(http_error.content)
return query_job
diff --git a/benchmarks/util/data_proto2_to_proto3_util.h b/benchmarks/util/data_proto2_to_proto3_util.h
new file mode 100644
index 00000000..5eea8509
--- /dev/null
+++ b/benchmarks/util/data_proto2_to_proto3_util.h
@@ -0,0 +1,64 @@
+#ifndef PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
+#define PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
+
+#include "google/protobuf/message.h"
+#include "google/protobuf/descriptor.h"
+
+using google::protobuf::FieldDescriptor;
+using google::protobuf::Message;
+using google::protobuf::Reflection;
+
+namespace google {
+namespace protobuf {
+namespace util {
+
+class DataStripper {
+ public:
+ void StripMessage(Message *message) {
+ std::vector<const FieldDescriptor*> set_fields;
+ const Reflection* reflection = message->GetReflection();
+ reflection->ListFields(*message, &set_fields);
+
+ for (size_t i = 0; i < set_fields.size(); i++) {
+ const FieldDescriptor* field = set_fields[i];
+ if (ShouldBeClear(field)) {
+ reflection->ClearField(message, field);
+ continue;
+ }
+ if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
+ if (field->is_repeated()) {
+ for (int j = 0; j < reflection->FieldSize(*message, field); j++) {
+ StripMessage(reflection->MutableRepeatedMessage(message, field, j));
+ }
+ } else {
+ StripMessage(reflection->MutableMessage(message, field));
+ }
+ }
+ }
+
+ reflection->MutableUnknownFields(message)->Clear();
+ }
+ private:
+ virtual bool ShouldBeClear(const FieldDescriptor *field) = 0;
+};
+
+class GogoDataStripper : public DataStripper {
+ private:
+ virtual bool ShouldBeClear(const FieldDescriptor *field) {
+ return field->type() == FieldDescriptor::TYPE_GROUP;
+ }
+};
+
+class Proto3DataStripper : public DataStripper {
+ private:
+ virtual bool ShouldBeClear(const FieldDescriptor *field) {
+ return field->type() == FieldDescriptor::TYPE_GROUP ||
+ field->is_extension();
+ }
+};
+
+} // namespace util
+} // namespace protobuf
+} // namespace google
+
+#endif // PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
diff --git a/benchmarks/util/gogo_data_scrubber.cc b/benchmarks/util/gogo_data_scrubber.cc
index fb9af6e2..9ef57b0d 100644
--- a/benchmarks/util/gogo_data_scrubber.cc
+++ b/benchmarks/util/gogo_data_scrubber.cc
@@ -4,43 +4,11 @@
#include "datasets/google_message2/benchmark_message2.pb.h"
#include "datasets/google_message3/benchmark_message3.pb.h"
#include "datasets/google_message4/benchmark_message4.pb.h"
-
-#include "google/protobuf/message.h"
-#include "google/protobuf/descriptor.h"
+#include "data_proto2_to_proto3_util.h"
#include <fstream>
-using google::protobuf::FieldDescriptor;
-using google::protobuf::Message;
-using google::protobuf::Reflection;
-
-
-class DataGroupStripper {
- public:
- static void StripMessage(Message *message) {
- std::vector<const FieldDescriptor*> set_fields;
- const Reflection* reflection = message->GetReflection();
- reflection->ListFields(*message, &set_fields);
-
- for (size_t i = 0; i < set_fields.size(); i++) {
- const FieldDescriptor* field = set_fields[i];
- if (field->type() == FieldDescriptor::TYPE_GROUP) {
- reflection->ClearField(message, field);
- }
- if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
- if (field->is_repeated()) {
- for (int j = 0; j < reflection->FieldSize(*message, field); j++) {
- StripMessage(reflection->MutableRepeatedMessage(message, field, j));
- }
- } else {
- StripMessage(reflection->MutableMessage(message, field));
- }
- }
- }
-
- reflection->MutableUnknownFields(message)->Clear();
- }
-};
+using google::protobuf::util::GogoDataStripper;
std::string ReadFile(const std::string& name) {
std::ifstream file(name.c_str());
@@ -91,7 +59,8 @@ int main(int argc, char *argv[]) {
for (int i = 0; i < dataset.payload_size(); i++) {
message->ParseFromString(dataset.payload(i));
- DataGroupStripper::StripMessage(message);
+ GogoDataStripper stripper;
+ stripper.StripMessage(message);
dataset.set_payload(i, message->SerializeAsString());
}
diff --git a/benchmarks/util/proto3_data_stripper.cc b/benchmarks/util/proto3_data_stripper.cc
new file mode 100644
index 00000000..3096c4c1
--- /dev/null
+++ b/benchmarks/util/proto3_data_stripper.cc
@@ -0,0 +1,74 @@
+#include "benchmarks.pb.h"
+#include "datasets/google_message1/proto2/benchmark_message1_proto2.pb.h"
+#include "datasets/google_message1/proto3/benchmark_message1_proto3.pb.h"
+#include "datasets/google_message2/benchmark_message2.pb.h"
+#include "datasets/google_message3/benchmark_message3.pb.h"
+#include "datasets/google_message4/benchmark_message4.pb.h"
+#include "data_proto2_to_proto3_util.h"
+
+#include <fstream>
+
+using google::protobuf::util::Proto3DataStripper;
+
+std::string ReadFile(const std::string& name) {
+ std::ifstream file(name.c_str());
+ GOOGLE_CHECK(file.is_open()) << "Couldn't find file '"
+ << name
+ << "', please make sure you are running this command from the benchmarks"
+ << " directory.\n";
+ return std::string((std::istreambuf_iterator<char>(file)),
+ std::istreambuf_iterator<char>());
+}
+
+int main(int argc, char *argv[]) {
+ if (argc % 2 == 0 || argc == 1) {
+ std::cerr << "Usage: [input_files] [output_file_names] where " <<
+ "input_files are one to one mapping to output_file_names." <<
+ std::endl;
+ return 1;
+ }
+
+ for (int i = argc / 2; i > 0; i--) {
+ const std::string &input_file = argv[i];
+ const std::string &output_file = argv[i + argc / 2];
+
+ std::cerr << "Generating " << input_file
+ << " to " << output_file << std::endl;
+ benchmarks::BenchmarkDataset dataset;
+ Message* message;
+ std::string dataset_payload = ReadFile(input_file);
+ GOOGLE_CHECK(dataset.ParseFromString(dataset_payload))
+ << "Can' t parse data file " << input_file;
+
+ if (dataset.message_name() == "benchmarks.proto3.GoogleMessage1") {
+ message = new benchmarks::proto3::GoogleMessage1;
+ } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage1") {
+ message = new benchmarks::proto2::GoogleMessage1;
+ } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage2") {
+ message = new benchmarks::proto2::GoogleMessage2;
+ } else if (dataset.message_name() ==
+ "benchmarks.google_message3.GoogleMessage3") {
+ message = new benchmarks::google_message3::GoogleMessage3;
+ } else if (dataset.message_name() ==
+ "benchmarks.google_message4.GoogleMessage4") {
+ message = new benchmarks::google_message4::GoogleMessage4;
+ } else {
+ std::cerr << "Unknown message type: " << dataset.message_name();
+ exit(1);
+ }
+
+ for (int i = 0; i < dataset.payload_size(); i++) {
+ message->ParseFromString(dataset.payload(i));
+ Proto3DataStripper stripper;
+ stripper.StripMessage(message);
+ dataset.set_payload(i, message->SerializeAsString());
+ }
+
+ std::ofstream ofs(output_file);
+ ofs << dataset.SerializeAsString();
+ ofs.close();
+ }
+
+
+ return 0;
+}
diff --git a/benchmarks/util/protoc-gen-gogoproto.cc b/benchmarks/util/protoc-gen-gogoproto.cc
index bfa6a5e5..9c1b3d04 100644
--- a/benchmarks/util/protoc-gen-gogoproto.cc
+++ b/benchmarks/util/protoc-gen-gogoproto.cc
@@ -12,7 +12,7 @@ using google::protobuf::FileDescriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::io::Printer;
using google::protobuf::util::SchemaGroupStripper;
-using google::protobuf::util::SchemaAddZeroEnumValue;
+using google::protobuf::util::EnumScrubber;
namespace google {
namespace protobuf {
@@ -74,7 +74,7 @@ class GoGoProtoGenerator : public CodeGenerator {
file->CopyTo(&new_file);
SchemaGroupStripper::StripFile(file, &new_file);
- SchemaAddZeroEnumValue enum_scrubber;
+ EnumScrubber enum_scrubber;
enum_scrubber.ScrubFile(&new_file);
string filename = file->name();
diff --git a/benchmarks/util/protoc-gen-proto2_to_proto3.cc b/benchmarks/util/protoc-gen-proto2_to_proto3.cc
new file mode 100644
index 00000000..d0a89023
--- /dev/null
+++ b/benchmarks/util/protoc-gen-proto2_to_proto3.cc
@@ -0,0 +1,115 @@
+#include "google/protobuf/compiler/code_generator.h"
+#include "google/protobuf/io/zero_copy_stream.h"
+#include "google/protobuf/io/printer.h"
+#include "google/protobuf/descriptor.h"
+#include "google/protobuf/descriptor.pb.h"
+#include "schema_proto2_to_proto3_util.h"
+
+#include "google/protobuf/compiler/plugin.h"
+
+using google::protobuf::FileDescriptorProto;
+using google::protobuf::FileDescriptor;
+using google::protobuf::DescriptorPool;
+using google::protobuf::io::Printer;
+using google::protobuf::util::SchemaGroupStripper;
+using google::protobuf::util::EnumScrubber;
+using google::protobuf::util::ExtensionStripper;
+using google::protobuf::util::FieldScrubber;
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+
+namespace {
+
+string StripProto(string filename) {
+ return filename.substr(0, filename.rfind(".proto"));
+}
+
+DescriptorPool* GetPool() {
+ static DescriptorPool *pool = new DescriptorPool();
+ return pool;
+}
+
+} // namespace
+
+class Proto2ToProto3Generator final : public CodeGenerator {
+ public:
+ bool GenerateAll(const std::vector<const FileDescriptor*>& files,
+ const string& parameter,
+ GeneratorContext* context,
+ string* error) const {
+ for (int i = 0; i < files.size(); i++) {
+ for (auto file : files) {
+ if (CanGenerate(file)) {
+ Generate(file, parameter, context, error);
+ break;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ bool Generate(const FileDescriptor* file,
+ const string& parameter,
+ GeneratorContext* context,
+ string* error) const {
+ FileDescriptorProto new_file;
+ file->CopyTo(&new_file);
+ SchemaGroupStripper::StripFile(file, &new_file);
+
+ EnumScrubber enum_scrubber;
+ enum_scrubber.ScrubFile(&new_file);
+ ExtensionStripper::StripFile(&new_file);
+ FieldScrubber::ScrubFile(&new_file);
+ new_file.set_syntax("proto3");
+
+ string filename = file->name();
+ string basename = StripProto(filename);
+
+ std::vector<std::pair<string,string>> option_pairs;
+ ParseGeneratorParameter(parameter, &option_pairs);
+
+ std::unique_ptr<google::protobuf::io::ZeroCopyOutputStream> output(
+ context->Open(basename + ".proto"));
+ string content = GetPool()->BuildFile(new_file)->DebugString();
+ Printer printer(output.get(), '$');
+ printer.WriteRaw(content.c_str(), content.size());
+
+ return true;
+ }
+ private:
+ bool CanGenerate(const FileDescriptor* file) const {
+ if (GetPool()->FindFileByName(file->name()) != nullptr) {
+ return false;
+ }
+ for (int j = 0; j < file->dependency_count(); j++) {
+ if (GetPool()->FindFileByName(file->dependency(j)->name()) == nullptr) {
+ return false;
+ }
+ }
+ for (int j = 0; j < file->public_dependency_count(); j++) {
+ if (GetPool()->FindFileByName(
+ file->public_dependency(j)->name()) == nullptr) {
+ return false;
+ }
+ }
+ for (int j = 0; j < file->weak_dependency_count(); j++) {
+ if (GetPool()->FindFileByName(
+ file->weak_dependency(j)->name()) == nullptr) {
+ return false;
+ }
+ }
+ return true;
+ }
+};
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
+int main(int argc, char* argv[]) {
+ google::protobuf::compiler::Proto2ToProto3Generator generator;
+ return google::protobuf::compiler::PluginMain(argc, argv, &generator);
+}
diff --git a/benchmarks/util/run_and_upload.py b/benchmarks/util/result_parser.py
index ae22a668..32f35a97 100755
--- a/benchmarks/util/run_and_upload.py
+++ b/benchmarks/util/result_parser.py
@@ -1,45 +1,34 @@
-import argparse
-import os
-import re
-import copy
-import uuid
-import calendar
-import time
-import big_query_utils
-import datetime
-import json
# This import depends on the automake rule protoc_middleman, please make sure
# protoc_middleman has been built before run this file.
-import os.path, sys
+import json
+import re
+import os.path
+# BEGIN OPENSOURCE
+import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
+# END OPENSOURCE
import tmp.benchmarks_pb2 as benchmarks_pb2
-from click.types import STRING
-_PROJECT_ID = 'grpc-testing'
-_DATASET = 'protobuf_benchmark_result'
-_TABLE = 'opensource_result_v1'
-_NOW = "%d%02d%02d" % (datetime.datetime.now().year,
- datetime.datetime.now().month,
- datetime.datetime.now().day)
+__file_size_map = {}
-file_size_map = {}
-
-def get_data_size(file_name):
- if file_name in file_size_map:
- return file_size_map[file_name]
+def __get_data_size(filename):
+ if filename[0] != '/':
+ filename = os.path.dirname(os.path.abspath(__file__)) + "/../" + filename
+ if filename in __file_size_map:
+ return __file_size_map[filename]
benchmark_dataset = benchmarks_pb2.BenchmarkDataset()
benchmark_dataset.ParseFromString(
- open(os.path.dirname(os.path.abspath(__file__)) + "/../" + file_name).read())
+ open(filename).read())
size = 0
count = 0
for payload in benchmark_dataset.payload:
size += len(payload)
count += 1
- file_size_map[file_name] = (size, 1.0 * size / count)
+ __file_size_map[filename] = (size, 1.0 * size / count)
return size, 1.0 * size / count
-def extract_file_name(file_name):
+def __extract_file_name(file_name):
name_list = re.split("[/\.]", file_name)
short_file_name = ""
for name in name_list:
@@ -48,28 +37,25 @@ def extract_file_name(file_name):
return short_file_name
-cpp_result = []
-python_result = []
-java_result = []
-go_result = []
+__results = []
# CPP results example:
-# [
-# "benchmarks": [
+# [
+# "benchmarks": [
# {
# "bytes_per_second": int,
-# "cpu_time": int,
+# "cpu_time_ns": double,
+# "iterations": int,
# "name: string,
-# "time_unit: string,
+# "real_time_ns: double,
# ...
# },
-# ...
+# ...
# ],
-# ...
+# ...
# ]
-def parse_cpp_result(filename):
- global cpp_result
+def __parse_cpp_result(filename):
if filename == "":
return
if filename[0] != '/':
@@ -80,31 +66,62 @@ def parse_cpp_result(filename):
data_filename = "".join(
re.split("(_parse_|_serialize)", benchmark["name"])[0])
behavior = benchmark["name"][len(data_filename) + 1:]
- cpp_result.append({
+ if data_filename[:2] == "BM":
+ data_filename = data_filename[3:]
+ __results.append({
"language": "cpp",
- "dataFileName": data_filename,
+ "dataFilename": data_filename,
"behavior": behavior,
"throughput": benchmark["bytes_per_second"] / 2.0 ** 20
})
+# Synthetic benchmark results example:
+# [
+# "benchmarks": [
+# {
+# "cpu_time_ns": double,
+# "iterations": int,
+# "name: string,
+# "real_time_ns: double,
+# ...
+# },
+# ...
+# ],
+# ...
+# ]
+def __parse_synthetic_result(filename):
+ if filename == "":
+ return
+ if filename[0] != "/":
+ filename = os.path.dirname(os.path.abspath(__file__)) + "/" + filename
+ with open(filename) as f:
+ results = json.loads(f.read())
+ for benchmark in results["benchmarks"]:
+ __results.append({
+ "language": "cpp",
+ "dataFilename": "",
+ "behavior": "synthetic",
+ "throughput": 10.0**9 / benchmark["cpu_time_ns"]
+ })
+
+
# Python results example:
-# [
-# [
+# [
+# [
# {
# "filename": string,
# "benchmarks": {
-# behavior: results,
+# behavior: results,
# ...
# },
# "message_name": STRING
# },
-# ...
+# ...
# ], #pure-python
-# ...
+# ...
# ]
-def parse_python_result(filename):
- global python_result
+def __parse_python_result(filename):
if filename == "":
return
if filename[0] != '/':
@@ -113,11 +130,11 @@ def parse_python_result(filename):
results_list = json.loads(f.read())
for results in results_list:
for result in results:
- _, avg_size = get_data_size(result["filename"])
+ _, avg_size = __get_data_size(result["filename"])
for behavior in result["benchmarks"]:
- python_result.append({
+ __results.append({
"language": "python",
- "dataFileName": extract_file_name(result["filename"]),
+ "dataFilename": __extract_file_name(result["filename"]),
"behavior": behavior,
"throughput": avg_size /
result["benchmarks"][behavior] * 1e9 / 2 ** 20
@@ -125,7 +142,7 @@ def parse_python_result(filename):
# Java results example:
-# [
+# [
# {
# "id": string,
# "instrumentSpec": {...},
@@ -151,12 +168,11 @@ def parse_python_result(filename):
# },
# ...
# }
-#
-# },
-# ...
+#
+# },
+# ...
# ]
-def parse_java_result(filename):
- global average_bytes_per_message, java_result
+def __parse_java_result(filename):
if filename == "":
return
if filename[0] != '/':
@@ -170,13 +186,13 @@ def parse_java_result(filename):
total_weight += measurement["weight"]
total_value += measurement["value"]["magnitude"]
avg_time = total_value * 1.0 / total_weight
- total_size, _ = get_data_size(
+ total_size, _ = __get_data_size(
result["scenario"]["benchmarkSpec"]["parameters"]["dataFile"])
- java_result.append({
+ __results.append({
"language": "java",
"throughput": total_size / avg_time * 1e9 / 2 ** 20,
"behavior": result["scenario"]["benchmarkSpec"]["methodName"],
- "dataFileName": extract_file_name(
+ "dataFilename": __extract_file_name(
result["scenario"]["benchmarkSpec"]["parameters"]["dataFile"])
})
@@ -192,8 +208,7 @@ def parse_java_result(filename):
# Benchmark/.././datasets/google_message2/dataset.google_message2.pb/Merge-12 300 4108632 ns/op
# PASS
# ok _/usr/local/google/home/yilunchong/mygit/protobuf/benchmarks 124.173s
-def parse_go_result(filename):
- global go_result
+def __parse_go_result(filename):
if filename == "":
return
if filename[0] != '/':
@@ -206,85 +221,36 @@ def parse_go_result(filename):
first_slash_index = result_list[0].find('/')
last_slash_index = result_list[0].rfind('/')
full_filename = result_list[0][first_slash_index+4:last_slash_index] # delete ../ prefix
- total_bytes, _ = get_data_size(full_filename)
+ total_bytes, _ = __get_data_size(full_filename)
behavior_with_suffix = result_list[0][last_slash_index+1:]
last_dash = behavior_with_suffix.rfind("-")
if last_dash == -1:
behavior = behavior_with_suffix
else:
behavior = behavior_with_suffix[:last_dash]
- go_result.append({
- "dataFilename": extract_file_name(full_filename),
+ __results.append({
+ "dataFilename": __extract_file_name(full_filename),
"throughput": total_bytes / float(result_list[2]) * 1e9 / 2 ** 20,
"behavior": behavior,
"language": "go"
})
-def get_metadata():
- build_number = os.getenv('BUILD_NUMBER')
- build_url = os.getenv('BUILD_URL')
- job_name = os.getenv('JOB_NAME')
- git_commit = os.getenv('GIT_COMMIT')
- # actual commit is the actual head of PR that is getting tested
- git_actual_commit = os.getenv('ghprbActualCommit')
-
- utc_timestamp = str(calendar.timegm(time.gmtime()))
- metadata = {'created': utc_timestamp}
-
- if build_number:
- metadata['buildNumber'] = build_number
- if build_url:
- metadata['buildUrl'] = build_url
- if job_name:
- metadata['jobName'] = job_name
- if git_commit:
- metadata['gitCommit'] = git_commit
- if git_actual_commit:
- metadata['gitActualCommit'] = git_actual_commit
-
- return metadata
-
-
-def upload_result(result_list, metadata):
- for result in result_list:
- new_result = copy.deepcopy(result)
- new_result['metadata'] = metadata
- bq = big_query_utils.create_big_query()
- row = big_query_utils.make_row(str(uuid.uuid4()), new_result)
- if not big_query_utils.insert_rows(bq, _PROJECT_ID, _DATASET,
- _TABLE + "$" + _NOW,
- [row]):
- print 'Error when uploading result', new_result
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser()
- parser.add_argument("-cpp", "--cpp_input_file",
- help="The CPP benchmark result file's name",
- default="")
- parser.add_argument("-java", "--java_input_file",
- help="The Java benchmark result file's name",
- default="")
- parser.add_argument("-python", "--python_input_file",
- help="The Python benchmark result file's name",
- default="")
- parser.add_argument("-go", "--go_input_file",
- help="The golang benchmark result file's name",
- default="")
- args = parser.parse_args()
-
- parse_cpp_result(args.cpp_input_file)
- parse_python_result(args.python_input_file)
- parse_java_result(args.java_input_file)
- parse_go_result(args.go_input_file)
+def get_result_from_file(cpp_file="",
+ java_file="",
+ python_file="",
+ go_file="",
+ synthetic_file=""):
+ results = {}
+ if cpp_file != "":
+ __parse_cpp_result(cpp_file)
+ if java_file != "":
+ __parse_java_result(java_file)
+ if python_file != "":
+ __parse_python_result(python_file)
+ if go_file != "":
+ __parse_go_result(go_file)
+ if synthetic_file != "":
+ __parse_synthetic_result(synthetic_file)
- metadata = get_metadata()
- print "uploading cpp results..."
- upload_result(cpp_result, metadata)
- print "uploading java results..."
- upload_result(java_result, metadata)
- print "uploading python results..."
- upload_result(python_result, metadata)
- print "uploading go results..."
- upload_result(go_result, metadata)
+ return __results
diff --git a/benchmarks/util/result_uploader.py b/benchmarks/util/result_uploader.py
new file mode 100755
index 00000000..a667da02
--- /dev/null
+++ b/benchmarks/util/result_uploader.py
@@ -0,0 +1,94 @@
+from __future__ import print_function
+from __future__ import absolute_import
+import argparse
+import os
+import re
+import copy
+import uuid
+import calendar
+import time
+import datetime
+
+from util import big_query_utils
+from util import result_parser
+
+_PROJECT_ID = 'grpc-testing'
+_DATASET = 'protobuf_benchmark_result'
+_TABLE = 'opensource_result_v2'
+_NOW = "%d%02d%02d" % (datetime.datetime.now().year,
+ datetime.datetime.now().month,
+ datetime.datetime.now().day)
+
+_INITIAL_TIME = calendar.timegm(time.gmtime())
+
+def get_metadata():
+ build_number = os.getenv('BUILD_NUMBER')
+ build_url = os.getenv('BUILD_URL')
+ job_name = os.getenv('JOB_NAME')
+ git_commit = os.getenv('GIT_COMMIT')
+ # actual commit is the actual head of PR that is getting tested
+ git_actual_commit = os.getenv('ghprbActualCommit')
+
+ utc_timestamp = str(calendar.timegm(time.gmtime()))
+ metadata = {'created': utc_timestamp}
+
+ if build_number:
+ metadata['buildNumber'] = build_number
+ if build_url:
+ metadata['buildUrl'] = build_url
+ if job_name:
+ metadata['jobName'] = job_name
+ if git_commit:
+ metadata['gitCommit'] = git_commit
+ if git_actual_commit:
+ metadata['gitActualCommit'] = git_actual_commit
+
+ return metadata
+
+
+def upload_result(result_list, metadata):
+ for result in result_list:
+ new_result = {}
+ new_result["metric"] = "throughput"
+ new_result["value"] = result["throughput"]
+ new_result["unit"] = "MB/s"
+ new_result["test"] = "protobuf_benchmark"
+ new_result["product_name"] = "protobuf"
+ labels_string = ""
+ for key in result:
+ labels_string += ",|%s:%s|" % (key, result[key])
+ new_result["labels"] = labels_string[1:]
+ new_result["timestamp"] = _INITIAL_TIME
+
+ bq = big_query_utils.create_big_query()
+ row = big_query_utils.make_row(str(uuid.uuid4()), new_result)
+ if not big_query_utils.insert_rows(bq, _PROJECT_ID, _DATASET,
+ _TABLE + "$" + _NOW,
+ [row]):
+ print('Error when uploading result', new_result)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-cpp", "--cpp_input_file",
+ help="The CPP benchmark result file's name",
+ default="")
+ parser.add_argument("-java", "--java_input_file",
+ help="The Java benchmark result file's name",
+ default="")
+ parser.add_argument("-python", "--python_input_file",
+ help="The Python benchmark result file's name",
+ default="")
+ parser.add_argument("-go", "--go_input_file",
+ help="The golang benchmark result file's name",
+ default="")
+ args = parser.parse_args()
+
+ metadata = get_metadata()
+ print("uploading results...")
+ upload_result(result_parser.get_result_from_file(
+ cpp_file=args.cpp_input_file,
+ java_file=args.java_input_file,
+ python_file=args.python_input_file,
+ go_file=args.go_input_file
+ ), metadata) \ No newline at end of file
diff --git a/benchmarks/util/schema_proto2_to_proto3_util.h b/benchmarks/util/schema_proto2_to_proto3_util.h
index 089012dd..0079f6f1 100644
--- a/benchmarks/util/schema_proto2_to_proto3_util.h
+++ b/benchmarks/util/schema_proto2_to_proto3_util.h
@@ -74,10 +74,10 @@ class SchemaGroupStripper {
};
-class SchemaAddZeroEnumValue {
+class EnumScrubber {
public:
- SchemaAddZeroEnumValue()
+ EnumScrubber()
: total_added_(0) {
}
@@ -130,6 +130,63 @@ class SchemaAddZeroEnumValue {
int total_added_;
};
+class ExtensionStripper {
+ public:
+ static void StripFile(FileDescriptorProto *file) {
+ for (int i = 0; i < file->mutable_message_type()->size(); i++) {
+ StripMessage(file->mutable_message_type(i));
+ }
+ file->mutable_extension()->Clear();
+ }
+ private:
+ static void StripMessage(DescriptorProto *message_type) {
+ message_type->mutable_extension()->Clear();
+ message_type->clear_extension_range();
+ for (int i = 0; i < message_type->mutable_nested_type()->size(); i++) {
+ StripMessage(message_type->mutable_nested_type(i));
+ }
+ }
+};
+
+
+class FieldScrubber {
+ public:
+ static void ScrubFile(FileDescriptorProto *file) {
+ for (int i = 0; i < file->mutable_message_type()->size(); i++) {
+ ScrubMessage(file->mutable_message_type(i));
+ }
+ for (int i = 0; i < file->mutable_extension()->size(); i++) {
+ file->mutable_extension(i)->clear_default_value();
+ if (ShouldClearLabel(file->mutable_extension(i))) {
+ file->mutable_extension(i)->clear_label();
+ }
+ }
+ }
+ private:
+ static bool ShouldClearLabel(const FieldDescriptorProto *field) {
+ return field->label() == FieldDescriptorProto::LABEL_REQUIRED;
+ }
+
+ static void ScrubMessage(DescriptorProto *message_type) {
+ message_type->mutable_extension()->Clear();
+ for (int i = 0; i < message_type->mutable_extension()->size(); i++) {
+ message_type->mutable_extension(i)->clear_default_value();
+ if (ShouldClearLabel(message_type->mutable_extension(i))) {
+ message_type->mutable_extension(i)->clear_label();
+ }
+ }
+ for (int i = 0; i < message_type->mutable_field()->size(); i++) {
+ message_type->mutable_field(i)->clear_default_value();
+ if (ShouldClearLabel(message_type->mutable_field(i))) {
+ message_type->mutable_field(i)->clear_label();
+ }
+ }
+ for (int i = 0; i < message_type->mutable_nested_type()->size(); i++) {
+ ScrubMessage(message_type->mutable_nested_type(i));
+ }
+ }
+};
+
} // namespace util
} // namespace protobuf
} // namespace google
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index ada9dc25..06436c3a 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -7,7 +7,11 @@ endif()
# CMake policies
cmake_policy(SET CMP0022 NEW)
-
+# On MacOS use @rpath/ for target's install name prefix path
+if (POLICY CMP0042)
+ cmake_policy(SET CMP0042 NEW)
+endif ()
+# Clear VERSION variables when no VERSION is given to project()
if(POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif()
@@ -26,6 +30,7 @@ endif()
# Options
option(protobuf_BUILD_TESTS "Build tests" ON)
+option(protobuf_BUILD_CONFORMANCE "Build conformance tests" OFF)
option(protobuf_BUILD_EXAMPLES "Build examples" OFF)
option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON)
if (BUILD_SHARED_LIBS)
@@ -214,6 +219,10 @@ if (protobuf_BUILD_TESTS)
include(tests.cmake)
endif (protobuf_BUILD_TESTS)
+if (protobuf_BUILD_CONFORMANCE)
+ include(conformance.cmake)
+endif (protobuf_BUILD_CONFORMANCE)
+
include(install.cmake)
if (protobuf_BUILD_EXAMPLES)
diff --git a/cmake/README.md b/cmake/README.md
index 26a516c7..1f370568 100644
--- a/cmake/README.md
+++ b/cmake/README.md
@@ -43,7 +43,7 @@ Getting Sources
You can get the latest stable source packages from the release page:
- https://github.com/google/protobuf/releases/latest
+ https://github.com/protocolbuffers/protobuf/releases/latest
For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if
you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package
@@ -52,7 +52,7 @@ download `protobuf-all-[VERSION].tar.gz`.
Or you can use git to clone from protobuf git repository.
- C:\Path\to> git clone -b [release_tag] https://github.com/google/protobuf.git
+ C:\Path\to> git clone -b [release_tag] https://github.com/protocolbuffers/protobuf.git
Where *[release_tag]* is a git tag like *v3.0.0-beta-1* or a branch name like *master*
if you want to get the latest code.
diff --git a/cmake/conformance.cmake b/cmake/conformance.cmake
new file mode 100644
index 00000000..ec1f9e00
--- /dev/null
+++ b/cmake/conformance.cmake
@@ -0,0 +1,48 @@
+
+add_custom_command(
+ OUTPUT ${protobuf_source_dir}/conformance/conformance.pb.cc
+ DEPENDS protoc ${protobuf_source_dir}/conformance/conformance.proto
+ COMMAND protoc ${protobuf_source_dir}/conformance/conformance.proto
+ --proto_path=${protobuf_source_dir}/conformance
+ --cpp_out=${protobuf_source_dir}/conformance
+)
+
+add_custom_command(
+ OUTPUT ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc
+ DEPENDS protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
+ protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto
+ COMMAND protoc ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.proto
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.proto
+ --proto_path=${protobuf_source_dir}/src
+ --cpp_out=${protobuf_source_dir}/src
+)
+
+add_executable(conformance_test_runner
+ ${protobuf_source_dir}/conformance/conformance.pb.cc
+ ${protobuf_source_dir}/conformance/conformance_test.cc
+ ${protobuf_source_dir}/conformance/conformance_test_impl.cc
+ ${protobuf_source_dir}/conformance/conformance_test_runner.cc
+ ${protobuf_source_dir}/conformance/third_party/jsoncpp/json.h
+ ${protobuf_source_dir}/conformance/third_party/jsoncpp/jsoncpp.cpp
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc
+)
+
+add_executable(conformance_cpp
+ ${protobuf_source_dir}/conformance/conformance.pb.cc
+ ${protobuf_source_dir}/conformance/conformance_cpp.cc
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc
+ ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc
+)
+
+target_include_directories(
+ conformance_test_runner
+ PUBLIC ${protobuf_source_dir}/conformance)
+
+target_include_directories(
+ conformance_cpp
+ PUBLIC ${protobuf_source_dir}/conformance)
+
+target_link_libraries(conformance_test_runner libprotobuf)
+target_link_libraries(conformance_cpp libprotobuf)
diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in
index 9fd9de0d..3818c4ef 100644
--- a/cmake/extract_includes.bat.in
+++ b/cmake/extract_includes.bat.in
@@ -72,6 +72,9 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\message.h" include\go
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\port.h" include\google\protobuf\port.h
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port_def.inc" include\google\protobuf\port_def.inc
+copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port_undef.inc" include\google\protobuf\port_undef.inc
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
diff --git a/cmake/install.cmake b/cmake/install.cmake
index 82036cb6..9b2ae93c 100644
--- a/cmake/install.cmake
+++ b/cmake/install.cmake
@@ -15,6 +15,13 @@ foreach(_library ${_protobuf_libraries})
PROPERTY INTERFACE_INCLUDE_DIRECTORIES
$<BUILD_INTERFACE:${protobuf_source_dir}/src>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
+ if (UNIX AND NOT APPLE)
+ set_property(TARGET ${_library}
+ PROPERTY INSTALL_RPATH "$ORIGIN")
+ elseif (APPLE)
+ set_property(TARGET ${_library}
+ PROPERTY INSTALL_RPATH "@loader_path")
+ endif()
install(TARGETS ${_library} EXPORT protobuf-targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT ${_library}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library}
@@ -24,6 +31,13 @@ endforeach()
if (protobuf_BUILD_PROTOC_BINARIES)
install(TARGETS protoc EXPORT protobuf-targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc)
+ if (UNIX AND NOT APPLE)
+ set_property(TARGET protoc
+ PROPERTY INSTALL_RPATH "$ORIGIN/../lib")
+ elseif (APPLE)
+ set_property(TARGET protoc
+ PROPERTY INSTALL_RPATH "@loader_path/../lib")
+ endif()
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")
diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake
index 82b954a1..1d0b0b84 100644
--- a/cmake/libprotobuf-lite.cmake
+++ b/cmake/libprotobuf-lite.cmake
@@ -49,7 +49,7 @@ set(libprotobuf_lite_includes
)
if (MSVC)
-set(libprotoc_rc_files
+set(libprotobuf_lite_rc_files
${CMAKE_CURRENT_BINARY_DIR}/version.rc
)
endif()
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index 463d65a3..bd570be7 100644
--- a/cmake/libprotobuf.cmake
+++ b/cmake/libprotobuf.cmake
@@ -113,7 +113,7 @@ set(libprotobuf_includes
)
if (MSVC)
-set(libprotoc_rc_files
+set(libprotobuf_rc_files
${CMAKE_CURRENT_BINARY_DIR}/version.rc
)
endif()
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake
index 92dfd306..850a85a6 100644
--- a/cmake/libprotoc.cmake
+++ b/cmake/libprotoc.cmake
@@ -44,8 +44,6 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field.cc
- ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.cc
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.cc
@@ -80,6 +78,7 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.cc
${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.cc
${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/scc.cc
${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.cc
${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.cc
)
@@ -128,8 +127,6 @@ set(libprotoc_headers
${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.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
@@ -157,6 +154,7 @@ set(libprotoc_headers
${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/scc.h
${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.h
${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h
)
@@ -181,3 +179,4 @@ set_target_properties(libprotoc PROPERTIES
OUTPUT_NAME ${LIB_PREFIX}protoc
DEBUG_POSTFIX "${protobuf_DEBUG_POSTFIX}")
add_library(protobuf::libprotoc ALIAS libprotoc)
+
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index acedcc7a..69d63e3e 100644
--- a/cmake/protobuf-config.cmake.in
+++ b/cmake/protobuf-config.cmake.in
@@ -11,7 +11,7 @@ function(protobuf_generate)
include(CMakeParseArguments)
set(_options APPEND_PATH)
- set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO)
+ set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR)
if(COMMAND target_sources)
list(APPEND _singleargs TARGET)
endif()
@@ -34,15 +34,19 @@ function(protobuf_generate)
endif()
string(TOLOWER ${protobuf_generate_LANGUAGE} protobuf_generate_LANGUAGE)
+ if(NOT protobuf_generate_PROTOC_OUT_DIR)
+ set(protobuf_generate_PROTOC_OUT_DIR ${CMAKE_CURRENT_BINARY_DIR})
+ endif()
+
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(NOT protobuf_generate_GENERATE_EXTENSIONS)
if(protobuf_generate_LANGUAGE STREQUAL cpp)
- set(protobuf_GENERATE_EXTENSIONS .pb.h .pb.cc)
+ set(protobuf_generate_GENERATE_EXTENSIONS .pb.h .pb.cc)
elseif(protobuf_generate_LANGUAGE STREQUAL python)
- set(protobuf_GENERATE_EXTENSIONS _pb2.py)
+ set(protobuf_generate_GENERATE_EXTENSIONS _pb2.py)
else()
message(SEND_ERROR "Error: protobuf_generate given unknown Language ${LANGUAGE}, please provide a value for GENERATE_EXTENSIONS")
return()
@@ -88,19 +92,21 @@ function(protobuf_generate)
set(_generated_srcs_all)
foreach(_proto ${protobuf_generate_PROTOS})
get_filename_component(_abs_file ${_proto} ABSOLUTE)
+ get_filename_component(_abs_dir ${_abs_file} DIRECTORY)
get_filename_component(_basename ${_proto} NAME_WE)
+ file(RELATIVE_PATH _rel_dir ${CMAKE_CURRENT_SOURCE_DIR} ${_abs_dir})
set(_generated_srcs)
- foreach(_ext ${protobuf_GENERATE_EXTENSIONS})
- list(APPEND _generated_srcs "${CMAKE_CURRENT_BINARY_DIR}/${_basename}${_ext}")
+ foreach(_ext ${protobuf_generate_GENERATE_EXTENSIONS})
+ list(APPEND _generated_srcs "${protobuf_generate_PROTOC_OUT_DIR}/${_rel_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
+ ARGS --${protobuf_generate_LANGUAGE}_out ${_dll_export_decl}${protobuf_generate_PROTOC_OUT_DIR}/${_rel_dir} ${_protobuf_include_path} ${_abs_file}
+ DEPENDS ${_abs_file} protobuf::protoc
COMMENT "Running ${protobuf_generate_LANGUAGE} protocol buffer compiler on ${_proto}"
VERBATIM )
endforeach()
diff --git a/cmake/protoc.cmake b/cmake/protoc.cmake
index 9bf6f5a9..bb160f47 100644
--- a/cmake/protoc.cmake
+++ b/cmake/protoc.cmake
@@ -2,9 +2,11 @@ set(protoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/main.cc
)
+if (MSVC)
set(protoc_rc_files
${CMAKE_CURRENT_BINARY_DIR}/version.rc
)
+endif()
add_executable(protoc ${protoc_files} ${protoc_rc_files})
target_link_libraries(protoc libprotobuf libprotoc)
diff --git a/cmake/tests.cmake b/cmake/tests.cmake
index ec790e33..f4679d1a 100644
--- a/cmake/tests.cmake
+++ b/cmake/tests.cmake
@@ -63,6 +63,7 @@ set(tests_protos
google/protobuf/unittest_optimize_for.proto
google/protobuf/unittest_preserve_unknown_enum.proto
google/protobuf/unittest_preserve_unknown_enum2.proto
+ google/protobuf/unittest_proto3.proto
google/protobuf/unittest_proto3_arena.proto
google/protobuf/unittest_proto3_arena_lite.proto
google/protobuf/unittest_proto3_lite.proto
@@ -78,6 +79,7 @@ set(tests_protos
google/protobuf/util/internal/testdata/struct.proto
google/protobuf/util/internal/testdata/timestamp_duration.proto
google/protobuf/util/internal/testdata/wrappers.proto
+ google/protobuf/util/json_format.proto
google/protobuf/util/json_format_proto3.proto
google/protobuf/util/message_differencer_unittest.proto
)
@@ -166,6 +168,7 @@ set(tests_files
${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc
${protobuf_source_dir}/src/google/protobuf/proto3_arena_unittest.cc
${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc
+ ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.inc
${protobuf_source_dir}/src/google/protobuf/reflection_ops_unittest.cc
${protobuf_source_dir}/src/google/protobuf/repeated_field_reflection_unittest.cc
${protobuf_source_dir}/src/google/protobuf/repeated_field_unittest.cc
@@ -204,6 +207,17 @@ if(protobuf_ABSOLUTE_TEST_PLUGIN_PATH)
add_compile_options(-DGOOGLE_PROTOBUF_TEST_PLUGIN_PATH="$<TARGET_FILE:test_plugin>")
endif()
+if(MINGW)
+ set_source_files_properties(${tests_files} PROPERTIES COMPILE_FLAGS "-Wno-narrowing")
+
+ # required for tests on MinGW Win64
+ if (CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj")
+ endif()
+
+endif()
+
add_executable(tests ${tests_files} ${common_test_files} ${tests_proto_files} ${lite_test_proto_files})
target_link_libraries(tests libprotoc libprotobuf gmock_main)
diff --git a/configure.ac b/configure.ac
index 7d668276..8e1c308c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -190,7 +190,7 @@ AM_CONDITIONAL([HAVE_PTHREAD], [test "x$ax_pthread_ok" = "xyes"])
AC_CXX_STL_HASH
case "$target_os" in
- mingw* | cygwin* | win* | aix*)
+ mingw* | cygwin* | win* | aix* | *android* )
;;
*)
# Need to link against rt on Solaris
diff --git a/conformance/ConformanceJava.java b/conformance/ConformanceJava.java
index 596d113a..d1ce4059 100644
--- a/conformance/ConformanceJava.java
+++ b/conformance/ConformanceJava.java
@@ -233,10 +233,14 @@ class ConformanceJava {
}
case JSON_PAYLOAD: {
try {
- TestMessagesProto3.TestAllTypesProto3.Builder builder =
+ TestMessagesProto3.TestAllTypesProto3.Builder builder =
TestMessagesProto3.TestAllTypesProto3.newBuilder();
- JsonFormat.parser().usingTypeRegistry(typeRegistry)
- .merge(request.getJsonPayload(), builder);
+ JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(typeRegistry);
+ if (request.getTestCategory()
+ == Conformance.TestCategory.JSON_IGNORE_UNKNOWN_PARSING_TEST) {
+ parser = parser.ignoringUnknownFields();
+ }
+ parser.merge(request.getJsonPayload(), builder);
testMessage = builder.build();
} catch (InvalidProtocolBufferException e) {
return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
diff --git a/conformance/Makefile.am b/conformance/Makefile.am
index e51ab80a..29d9a981 100644
--- a/conformance/Makefile.am
+++ b/conformance/Makefile.am
@@ -206,6 +206,7 @@ EXTRA_DIST = \
conformance_test_runner_LDADD = $(top_srcdir)/src/libprotobuf.la
conformance_test_runner_SOURCES = conformance_test.h conformance_test.cc \
+ conformance_test_impl.cc \
conformance_test_runner.cc \
third_party/jsoncpp/json.h \
third_party/jsoncpp/jsoncpp.cpp
diff --git a/conformance/README.md b/conformance/README.md
index 971fe8f6..06925dbb 100644
--- a/conformance/README.md
+++ b/conformance/README.md
@@ -1,8 +1,6 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf)
-
Copyright 2008 Google Inc.
This directory contains conformance tests for testing completeness and
@@ -59,10 +57,10 @@ Testing other Protocol Buffer implementations
To run these tests against a new Protocol Buffers implementation, write a
program in your language that uses the protobuf implementation you want
to test. This program should implement the testing protocol defined in
-[conformance.proto](https://github.com/google/protobuf/blob/master/conformance/conformance.proto).
+[conformance.proto](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance.proto).
This is designed to be as easy as possible: the C++ version is only
150 lines and is a good example for what this program should look like
-(see [conformance_cpp.cc](https://github.com/google/protobuf/blob/master/conformance/conformance_cpp.cc)).
+(see [conformance_cpp.cc](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance_cpp.cc)).
The program only needs to be able to read from stdin and write to stdout.
Portability
diff --git a/conformance/conformance.proto b/conformance/conformance.proto
index 525140e9..af89152d 100644
--- a/conformance/conformance.proto
+++ b/conformance/conformance.proto
@@ -57,6 +57,18 @@ enum WireFormat {
JSON = 2;
}
+enum TestCategory {
+ UNSPECIFIED_TEST = 0;
+ BINARY_TEST = 1; // Test binary wire format.
+ JSON_TEST = 2; // Test json wire format.
+ // Similar to JSON_TEST. However, during parsing json, testee should ignore
+ // unknown fields. This feature is optional. Each implementation can descide
+ // whether to support it. See
+ // https://developers.google.com/protocol-buffers/docs/proto3#json_options
+ // for more detail.
+ JSON_IGNORE_UNKNOWN_PARSING_TEST = 3;
+}
+
// Represents a single test case's input. The testee should:
//
// 1. parse this proto (which should always succeed)
@@ -82,6 +94,11 @@ message ConformanceRequest {
// protobuf_test_messages.proto3.TestAllTypesProto3 or
// protobuf_test_messages.proto2.TestAllTypesProto2.
string message_type = 4;
+
+ // Each test is given a specific test category. Some category may need
+ // spedific support in testee programs. Refer to the defintion of TestCategory
+ // for more information.
+ TestCategory test_category = 5;
}
// Represents a single test case's output.
diff --git a/conformance/conformance_cpp.cc b/conformance/conformance_cpp.cc
index 97ae1a7a..ac2f6dea 100644
--- a/conformance/conformance_cpp.cc
+++ b/conformance/conformance_cpp.cc
@@ -46,6 +46,7 @@ using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MessageFactory;
using google::protobuf::util::BinaryToJsonString;
+using google::protobuf::util::JsonParseOptions;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
@@ -112,8 +113,13 @@ void DoTest(const ConformanceRequest& request, ConformanceResponse* response) {
case ConformanceRequest::kJsonPayload: {
string proto_binary;
+ JsonParseOptions options;
+ options.ignore_unknown_fields =
+ (request.test_category() ==
+ conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST);
Status status = JsonToBinaryString(type_resolver, *type_url,
- request.json_payload(), &proto_binary);
+ request.json_payload(), &proto_binary,
+ options);
if (!status.ok()) {
response->set_parse_error(string("Parse error: ") +
status.error_message().as_string());
diff --git a/conformance/conformance_php.php b/conformance/conformance_php.php
index 85fe3d03..799cc3e3 100755
--- a/conformance/conformance_php.php
+++ b/conformance/conformance_php.php
@@ -3,6 +3,7 @@
require_once("Conformance/WireFormat.php");
require_once("Conformance/ConformanceResponse.php");
require_once("Conformance/ConformanceRequest.php");
+require_once("Conformance/TestCategory.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");
@@ -12,6 +13,7 @@ require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedEnum.php");
require_once("GPBMetadata/Conformance.php");
require_once("GPBMetadata/Google/Protobuf/TestMessagesProto3.php");
+use \Conformance\TestCategory;
use \Conformance\WireFormat;
if (!ini_get("date.timezone")) {
@@ -39,8 +41,12 @@ function doTest($request)
trigger_error("Protobuf request doesn't have specific payload type", E_USER_ERROR);
}
} elseif ($request->getPayload() == "json_payload") {
+ $ignore_json_unknown =
+ ($request->getTestCategory() ==
+ TestCategory::JSON_IGNORE_UNKNOWN_PARSING_TEST);
try {
- $test_message->mergeFromJsonString($request->getJsonPayload());
+ $test_message->mergeFromJsonString($request->getJsonPayload(),
+ $ignore_json_unknown);
} catch (Exception $e) {
$response->setParseError($e->getMessage());
return $response;
diff --git a/conformance/conformance_python.py b/conformance/conformance_python.py
index c5ba2467..876642bc 100755
--- a/conformance/conformance_python.py
+++ b/conformance/conformance_python.py
@@ -78,7 +78,11 @@ def do_test(request):
elif request.WhichOneof('payload') == 'json_payload':
try:
- json_format.Parse(request.json_payload, test_message)
+ ignore_unknown_fields = \
+ request.test_category == \
+ conformance_pb2.JSON_IGNORE_UNKNOWN_PARSING_TEST
+ json_format.Parse(request.json_payload, test_message,
+ ignore_unknown_fields)
except Exception as e:
response.parse_error = str(e)
return response
diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc
index 22bbbfb3..2d822c2e 100644
--- a/conformance/conformance_test.cc
+++ b/conformance/conformance_test.cc
@@ -28,168 +28,131 @@
// (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 <set>
#include <stdarg.h>
#include <string>
#include <fstream>
#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>
+#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/field_comparator.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/message_differencer.h>
-#include <google/protobuf/util/type_resolver_util.h>
-#include <google/protobuf/wire_format_lite.h>
-
-#include "third_party/jsoncpp/json.h"
using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
using conformance::WireFormat;
-using google::protobuf::Descriptor;
-using google::protobuf::FieldDescriptor;
-using google::protobuf::internal::WireFormatLite;
using google::protobuf::TextFormat;
using google::protobuf::util::DefaultFieldComparator;
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::TestAllTypesProto3;
-using protobuf_test_messages::proto2::TestAllTypesProto2;
using std::string;
-namespace {
-
-static const char kTypeUrlPrefix[] = "type.googleapis.com";
-
-static string GetTypeUrl(const Descriptor* message) {
- return string(kTypeUrlPrefix) + "/" + message->full_name();
-}
-
-/* Routines for building arbitrary protos *************************************/
-
-// We would use CodedOutputStream except that we want more freedom to build
-// arbitrary protos (even invalid ones).
-
-const string empty;
+namespace google {
+namespace protobuf {
-string cat(const string& a, const string& b,
- const string& c = empty,
- const string& d = empty,
- const string& e = empty,
- const string& f = empty,
- const string& g = empty,
- const string& h = empty,
- const string& i = empty,
- const string& j = empty,
- const string& k = empty,
- const string& l = empty) {
- string ret;
- ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
- g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
- ret.append(a);
- ret.append(b);
- ret.append(c);
- ret.append(d);
- ret.append(e);
- ret.append(f);
- ret.append(g);
- ret.append(h);
- ret.append(i);
- ret.append(j);
- ret.append(k);
- ret.append(l);
- return ret;
-}
+ConformanceTestSuite::ConformanceRequestSetting::ConformanceRequestSetting(
+ ConformanceLevel level,
+ conformance::WireFormat input_format,
+ conformance::WireFormat output_format,
+ conformance::TestCategory test_category,
+ const Message& prototype_message,
+ const string& test_name, const string& input)
+ : level_(level),
+ input_format_(input_format),
+ output_format_(output_format),
+ prototype_message_(prototype_message),
+ test_name_(test_name) {
+ switch (input_format) {
+ case conformance::PROTOBUF: {
+ request_.set_protobuf_payload(input);
+ break;
+ }
-// The maximum number of bytes that it takes to encode a 64-bit varint.
-#define VARINT_MAX_LEN 10
+ case conformance::JSON: {
+ request_.set_json_payload(input);
+ break;
+ }
-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 || 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;
+ default:
+ GOOGLE_LOG(FATAL) << "Unspecified input format";
}
- return i;
-}
-string varint(uint64_t x) {
- char buf[VARINT_MAX_LEN];
- size_t len = vencode64(x, 0, buf);
- return string(buf, len);
-}
+ request_.set_test_category(test_category);
-// 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);
+ request_.set_message_type(prototype_message.GetDescriptor()->full_name());
+ request_.set_requested_output_format(output_format);
}
-// TODO: proper byte-swapping for big-endian machines.
-string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
-string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
+Message* ConformanceTestSuite::ConformanceRequestSetting::
+ GetTestMessage() const {
+ return prototype_message_.New();
+}
-string delim(const string& buf) { return cat(varint(buf.size()), buf); }
-string u32(uint32_t u32) { return fixed32(&u32); }
-string u64(uint64_t u64) { return fixed64(&u64); }
-string flt(float f) { return fixed32(&f); }
-string dbl(double d) { return fixed64(&d); }
-string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
-string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
+string ConformanceTestSuite::ConformanceRequestSetting::
+ GetTestName() const {
+ string rname =
+ prototype_message_.GetDescriptor()->file()->syntax() ==
+ FileDescriptor::SYNTAX_PROTO3 ? "Proto3" : "Proto2";
-string tag(uint32_t fieldnum, char wire_type) {
- return varint((fieldnum << 3) | wire_type);
+ return StrCat(ConformanceLevelToString(level_), ".",
+ rname, ".",
+ InputFormatString(input_format_),
+ ".", test_name_, ".",
+ OutputFormatString(output_format_));
}
-string submsg(uint32_t fn, const string& buf) {
- return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
+string ConformanceTestSuite::ConformanceRequestSetting::
+ ConformanceLevelToString(
+ ConformanceLevel level) const {
+ switch (level) {
+ case REQUIRED: return "Required";
+ case RECOMMENDED: return "Recommended";
+ }
+ GOOGLE_LOG(FATAL) << "Unknown value: " << level;
+ return "";
}
-#define UNKNOWN_FIELD 666
-
-const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
- 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) {
- return f;
- }
+string ConformanceTestSuite::ConformanceRequestSetting::
+ InputFormatString(conformance::WireFormat format) const {
+ switch (format) {
+ case conformance::PROTOBUF:
+ return "ProtobufInput";
+ case conformance::JSON:
+ return "JsonInput";
+ default:
+ GOOGLE_LOG(FATAL) << "Unspecified output format";
}
- GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
- return nullptr;
+ return "";
}
-string UpperCase(string str) {
- for (int i = 0; i < str.size(); i++) {
- str[i] = toupper(str[i]);
+string ConformanceTestSuite::ConformanceRequestSetting::
+ OutputFormatString(conformance::WireFormat format) const {
+ switch (format) {
+ case conformance::PROTOBUF:
+ return "ProtobufOutput";
+ case conformance::JSON:
+ return "JsonOutput";
+ default:
+ GOOGLE_LOG(FATAL) << "Unspecified output format";
}
- return str;
+ return "";
}
-} // anonymous namespace
-
-namespace google {
-namespace protobuf {
+void ConformanceTestSuite::SetFailureList(
+ const string& filename,
+ const std::vector<string>& failure_list) {
+ failure_list_filename_ = filename;
+ expected_to_fail_.clear();
+ std::copy(failure_list.begin(), failure_list.end(),
+ std::inserter(expected_to_fail_, expected_to_fail_.end()));
+}
void ConformanceTestSuite::ReportSuccess(const string& test_name) {
if (expected_to_fail_.erase(test_name) != 0) {
@@ -237,111 +200,37 @@ void ConformanceTestSuite::ReportSkip(const string& test_name,
skipped_.insert(test_name);
}
-string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) {
- switch (level) {
- case REQUIRED: return "Required";
- case RECOMMENDED: return "Recommended";
- }
- GOOGLE_LOG(FATAL) << "Unknown value: " << level;
- return "";
-}
-
-void ConformanceTestSuite::RunTest(const string& test_name,
- const ConformanceRequest& request,
- ConformanceResponse* response) {
- if (test_names_.insert(test_name).second == false) {
- GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
- }
-
- string serialized_request;
- string serialized_response;
- request.SerializeToString(&serialized_request);
-
- runner_->RunTest(test_name, serialized_request, &serialized_response);
-
- if (!response->ParseFromString(serialized_response)) {
- response->Clear();
- response->set_runtime_error("response proto could not be parsed.");
- }
-
- if (verbose_) {
- StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
- test_name.c_str(),
- request.ShortDebugString().c_str(),
- response->ShortDebugString().c_str());
- }
-}
-
void ConformanceTestSuite::RunValidInputTest(
- const string& test_name, ConformanceLevel level, const string& input,
- WireFormat input_format, const string& equivalent_text_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();
+ const ConformanceRequestSetting& setting,
+ const string& equivalent_text_format) {
+ Message* reference_message = setting.GetTestMessage();
GOOGLE_CHECK(
TextFormat::ParseFromString(equivalent_text_format, reference_message))
- << "Failed to parse data for test case: " << test_name
+ << "Failed to parse data for test case: " << setting.GetTestName()
<< ", 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);
+ RunValidBinaryInputTest(setting, equivalent_wire_format);
}
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();
+ const ConformanceRequestSetting& setting,
+ const string& equivalent_wire_format) {
+ const string& test_name = setting.GetTestName();
+ ConformanceLevel level = setting.GetLevel();
+
+ Message* reference_message = setting.GetTestMessage();
GOOGLE_CHECK(
reference_message->ParseFromString(equivalent_wire_format))
<< "Failed to parse wire data for test case: " << test_name;
- ConformanceRequest request;
+ const ConformanceRequest& request = setting.GetRequest();
ConformanceResponse response;
- switch (input_format) {
- 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: {
- request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
- request.set_json_payload(input);
- break;
- }
-
- default:
- GOOGLE_LOG(FATAL) << "Unspecified input format";
- }
-
- request.set_requested_output_format(requested_output);
-
RunTest(test_name, request, &response);
- Message *test_message = newTestMessage();
+ Message* test_message = setting.GetTestMessage();
+
+ WireFormat requested_output = request.requested_output_format();
switch (response.result_case()) {
case ConformanceResponse::RESULT_NOT_SET:
@@ -426,344 +315,38 @@ void ConformanceTestSuite::RunValidBinaryInputTest(
differences.c_str());
}
}
-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
- // we let it send its response as this. We must not leave it unspecified.
- request.set_requested_output_format(conformance::PROTOBUF);
-
- RunTest(effective_test_name, request, &response);
- if (response.result_case() == ConformanceResponse::kParseError) {
- ReportSuccess(effective_test_name);
- } else if (response.result_case() == ConformanceResponse::kSkipped) {
- ReportSkip(effective_test_name, request, response);
- } else {
- ReportFailure(effective_test_name, level, request, response,
- "Should have failed to parse, but didn't.");
- }
-}
-
-// 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.
-//
-// TODO(haberman): implement the second of these.
-void ConformanceTestSuite::ExpectHardParseFailureForProto(
- const string& proto, const string& test_name, ConformanceLevel level) {
- return ExpectParseFailureForProto(proto, test_name, level);
-}
-
-void ConformanceTestSuite::RunValidJsonTest(
- const string& test_name, ConformanceLevel level, const string& input_json,
- const string& equivalent_text_format) {
- RunValidInputTest(
- ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
- ".ProtobufOutput", level, input_json, conformance::JSON,
- equivalent_text_format, conformance::PROTOBUF, true);
- RunValidInputTest(
- ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
- ".JsonOutput", level, input_json, conformance::JSON,
- equivalent_text_format, conformance::JSON, true);
-}
-
-void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
- const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
- const string& equivalent_text_format) {
- RunValidInputTest(
- ConformanceLevelToString(level) + ".Proto3" + ".ProtobufInput." + test_name +
- ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
- equivalent_text_format, conformance::JSON, true);
-}
-
-void ConformanceTestSuite::RunValidProtobufTest(
- const string& test_name, ConformanceLevel level,
- const string& input_protobuf, const string& equivalent_text_format,
- bool isProto3) {
- string rname = ".Proto3";
- if (!isProto3) {
- rname = ".Proto2";
- }
- RunValidInputTest(
- ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
- ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
- 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 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
-// rules than parsers (e.g., a serializer must serialize int32 values as JSON
-// numbers while the parser is allowed to accept them as JSON strings). This
-// method allows strict checking on a proto3 JSON serializer by inspecting
-// the JSON output directly.
-void ConformanceTestSuite::RunValidJsonTestWithValidator(
- const string& test_name, ConformanceLevel level, const string& input_json,
- const Validator& validator) {
- ConformanceRequest request;
- 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) +
- ".Proto3.JsonInput." + test_name + ".Validator";
-
- RunTest(effective_test_name, request, &response);
-
- if (response.result_case() == ConformanceResponse::kSkipped) {
- ReportSkip(effective_test_name, request, response);
- return;
- }
-
- if (response.result_case() != ConformanceResponse::kJsonPayload) {
- ReportFailure(effective_test_name, level, request, response,
- "Expected JSON payload but got type %d.",
- response.result_case());
- return;
- }
- Json::Reader reader;
- Json::Value value;
- if (!reader.parse(response.json_payload(), value)) {
- ReportFailure(effective_test_name, level, request, response,
- "JSON payload cannot be parsed as valid JSON: %s",
- reader.getFormattedErrorMessages().c_str());
- return;
- }
- if (!validator(value)) {
- ReportFailure(effective_test_name, level, request, response,
- "JSON payload validation failed.");
- return;
- }
- ReportSuccess(effective_test_name);
-}
-
-void ConformanceTestSuite::ExpectParseFailureForJson(
- const string& test_name, ConformanceLevel level, const string& input_json) {
- 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) + ".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.
- request.set_requested_output_format(conformance::JSON);
-
- RunTest(effective_test_name, request, &response);
- if (response.result_case() == ConformanceResponse::kParseError) {
- ReportSuccess(effective_test_name);
- } else if (response.result_case() == ConformanceResponse::kSkipped) {
- ReportSkip(effective_test_name, request, response);
- } else {
- ReportFailure(effective_test_name, level, request, response,
- "Should have failed to parse, but didn't.");
- }
-}
-void ConformanceTestSuite::ExpectSerializeFailureForJson(
- const string& test_name, ConformanceLevel level, const string& text_format) {
- TestAllTypesProto3 payload_message;
- GOOGLE_CHECK(
- TextFormat::ParseFromString(text_format, &payload_message))
- << "Failed to parse: " << text_format;
-
- 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);
-
- RunTest(effective_test_name, request, &response);
- if (response.result_case() == ConformanceResponse::kSerializeError) {
- ReportSuccess(effective_test_name);
- } else if (response.result_case() == ConformanceResponse::kSkipped) {
- ReportSkip(effective_test_name, request, response);
- } else {
- ReportFailure(effective_test_name, level, request, response,
- "Should have failed to serialize, but didn't.");
+void ConformanceTestSuite::RunTest(const string& test_name,
+ const ConformanceRequest& request,
+ ConformanceResponse* response) {
+ if (test_names_.insert(test_name).second == false) {
+ GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
}
-}
-
-//TODO: proto2?
-void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
- // Incomplete values for each wire type.
- static const string incompletes[6] = {
- string("\x80"), // VARINT
- string("abcdefg"), // 64BIT
- string("\x80"), // DELIMITED (partial length)
- string(), // START_GROUP (no value required)
- string(), // END_GROUP (no value required)
- string("abc") // 32BIT
- };
-
- 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];
- const string type_name =
- UpperCase(string(".") + FieldDescriptor::TypeName(type));
-
- ExpectParseFailureForProto(
- tag(field->number(), wire_type),
- "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
-
- ExpectParseFailureForProto(
- tag(rep_field->number(), wire_type),
- "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
-
- ExpectParseFailureForProto(
- tag(UNKNOWN_FIELD, wire_type),
- "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
-
- ExpectParseFailureForProto(
- cat( tag(field->number(), wire_type), incomplete ),
- "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
- ExpectParseFailureForProto(
- cat( tag(rep_field->number(), wire_type), incomplete ),
- "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
-
- ExpectParseFailureForProto(
- cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
- "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
-
- if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
- ExpectParseFailureForProto(
- cat( tag(field->number(), wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
- REQUIRED);
-
- ExpectParseFailureForProto(
- cat( tag(rep_field->number(), wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
- REQUIRED);
-
- // EOF in the middle of delimited data for unknown value.
- ExpectParseFailureForProto(
- cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
-
- if (type == FieldDescriptor::TYPE_MESSAGE) {
- // Submessage ends in the middle of a value.
- string incomplete_submsg =
- cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
- incompletes[WireFormatLite::WIRETYPE_VARINT] );
- ExpectHardParseFailureForProto(
- cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
- varint(incomplete_submsg.size()),
- incomplete_submsg ),
- "PrematureEofInSubmessageValue" + type_name, REQUIRED);
- }
- } else if (type != FieldDescriptor::TYPE_GROUP) {
- // Non-delimited, non-group: eligible for packing.
+ string serialized_request;
+ string serialized_response;
+ request.SerializeToString(&serialized_request);
- // Packed region ends in the middle of a value.
- ExpectHardParseFailureForProto(
- cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
- varint(incomplete.size()), incomplete),
- "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
+ runner_->RunTest(test_name, serialized_request, &serialized_response);
- // EOF in the middle of packed region.
- ExpectParseFailureForProto(
- cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
- varint(1)),
- "PrematureEofInPackedField" + type_name, REQUIRED);
+ if (!response->ParseFromString(serialized_response)) {
+ response->Clear();
+ response->set_runtime_error("response proto could not be parsed.");
}
-}
-
-void ConformanceTestSuite::TestValidDataForType(
- FieldDescriptor::Type type,
- std::vector<std::pair<std::string, std::string>> values) {
- 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();
-
- 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);
+ if (verbose_) {
+ StringAppendF(&output_,
+ "conformance test: name=%s, request=%s, response=%s\n",
+ test_name.c_str(),
+ request.ShortDebugString().c_str(),
+ response->ShortDebugString().c_str());
}
}
-void ConformanceTestSuite::SetFailureList(const string& filename,
- const std::vector<string>& failure_list) {
- failure_list_filename_ = filename;
- expected_to_fail_.clear();
- std::copy(failure_list.begin(), failure_list.end(),
- std::inserter(expected_to_fail_, expected_to_fail_.end()));
-}
-
-bool ConformanceTestSuite::CheckSetEmpty(const std::set<string>& set_to_check,
- const std::string& write_to_file,
- const std::string& msg) {
+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()) {
return true;
} else {
@@ -792,70 +375,8 @@ bool ConformanceTestSuite::CheckSetEmpty(const std::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) {
+bool ConformanceTestSuite::RunSuite(
+ ConformanceTestRunner* runner, std::string* output) {
runner_ = runner;
successes_ = 0;
expected_failures_ = 0;
@@ -863,1677 +384,10 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
test_names_.clear();
unexpected_failing_tests_.clear();
unexpected_succeeding_tests_.clear();
- type_resolver_.reset(NewTypeResolverForDescriptorPool(
- kTypeUrlPrefix, DescriptorPool::generated_pool()));
- type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
- for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
- if (i == FieldDescriptor::TYPE_GROUP) continue;
- TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
- }
-
- TestIllegalTags();
-
- int64 kInt64Min = -9223372036854775808ULL;
- int64 kInt64Max = 9223372036854775807ULL;
- uint64 kUint64Max = 18446744073709551615ULL;
- int32 kInt32Max = 2147483647;
- int32 kInt32Min = -2147483648;
- uint32 kUint32Max = 4294967295UL;
-
- TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
- {dbl(0.1), "0.1"},
- {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
- {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
- });
- 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"}
- });
- TestValidDataForType(FieldDescriptor::TYPE_INT64, {
- {varint(12345), "12345"},
- {varint(kInt64Max), std::to_string(kInt64Max)},
- {varint(kInt64Min), std::to_string(kInt64Min)}
- });
- TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
- {varint(12345), "12345"},
- {varint(kUint64Max), std::to_string(kUint64Max)},
- {varint(0), "0"}
- });
- 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(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"},
- {u64(kUint64Max), std::to_string(kUint64Max)},
- {u64(0), "0"}
- });
- TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
- {u32(12345), "12345"},
- {u32(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX
- {u32(0), "0"}
- });
- TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
- {u64(12345), "12345"},
- {u64(kInt64Max), std::to_string(kInt64Max)},
- {u64(kInt64Min), std::to_string(kInt64Min)}
- });
- TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
- {u32(12345), "12345"},
- {u32(kInt32Max), std::to_string(kInt32Max)},
- {u32(kInt32Min), std::to_string(kInt32Min)}
- });
- TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
- {varint(1), "true"},
- {varint(0), "false"},
- {varint(12345678), "true"}
- });
- TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
- {zz32(12345), "12345"},
- {zz32(kInt32Max), std::to_string(kInt32Max)},
- {zz32(kInt32Min), std::to_string(kInt32Min)}
- });
- TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
- {zz64(12345), "12345"},
- {zz64(kInt64Max), std::to_string(kInt64Max)},
- {zz64(kInt64Min), std::to_string(kInt64Min)}
- });
-
- // TODO(haberman):
- // TestValidDataForType(FieldDescriptor::TYPE_STRING
- // TestValidDataForType(FieldDescriptor::TYPE_GROUP
- // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE
- // TestValidDataForType(FieldDescriptor::TYPE_BYTES
- // TestValidDataForType(FieldDescriptor::TYPE_ENUM
-
- RunValidJsonTest("HelloWorld", REQUIRED,
- "{\"optionalString\":\"Hello, World!\"}",
- "optional_string: 'Hello, World!'");
-
- // NOTE: The spec for JSON support is still being sorted out, these may not
- // all be correct.
- // Test field name conventions.
- RunValidJsonTest(
- "FieldNameInSnakeCase", REQUIRED,
- R"({
- "fieldname1": 1,
- "fieldName2": 2,
- "FieldName3": 3,
- "fieldName4": 4
- })",
- R"(
- fieldname1: 1
- field_name2: 2
- _field_name3: 3
- field__name4_: 4
- )");
- RunValidJsonTest(
- "FieldNameWithNumbers", REQUIRED,
- R"({
- "field0name5": 5,
- "field0Name6": 6
- })",
- R"(
- field0name5: 5
- field_0_name6: 6
- )");
- RunValidJsonTest(
- "FieldNameWithMixedCases", REQUIRED,
- R"({
- "fieldName7": 7,
- "FieldName8": 8,
- "fieldName9": 9,
- "FieldName10": 10,
- "FIELDNAME11": 11,
- "FIELDName12": 12
- })",
- R"(
- fieldName7: 7
- FieldName8: 8
- field_Name9: 9
- Field_Name10: 10
- FIELD_NAME11: 11
- FIELD_name12: 12
- )");
- RunValidJsonTest(
- "FieldNameWithDoubleUnderscores", RECOMMENDED,
- R"({
- "FieldName13": 13,
- "FieldName14": 14,
- "fieldName15": 15,
- "fieldName16": 16,
- "fieldName17": 17,
- "FieldName18": 18
- })",
- R"(
- __field_name13: 13
- __Field_name14: 14
- field__name15: 15
- field__Name16: 16
- field_name17__: 17
- Field_name18__: 18
- )");
- // Using the original proto field name in JSON is also allowed.
- RunValidJsonTest(
- "OriginalProtoFieldName", REQUIRED,
- R"({
- "fieldname1": 1,
- "field_name2": 2,
- "_field_name3": 3,
- "field__name4_": 4,
- "field0name5": 5,
- "field_0_name6": 6,
- "fieldName7": 7,
- "FieldName8": 8,
- "field_Name9": 9,
- "Field_Name10": 10,
- "FIELD_NAME11": 11,
- "FIELD_name12": 12,
- "__field_name13": 13,
- "__Field_name14": 14,
- "field__name15": 15,
- "field__Name16": 16,
- "field_name17__": 17,
- "Field_name18__": 18
- })",
- R"(
- fieldname1: 1
- field_name2: 2
- _field_name3: 3
- field__name4_: 4
- field0name5: 5
- field_0_name6: 6
- fieldName7: 7
- FieldName8: 8
- field_Name9: 9
- Field_Name10: 10
- FIELD_NAME11: 11
- FIELD_name12: 12
- __field_name13: 13
- __Field_name14: 14
- field__name15: 15
- field__Name16: 16
- field_name17__: 17
- Field_name18__: 18
- )");
- // Field names can be escaped.
- RunValidJsonTest(
- "FieldNameEscaped", REQUIRED,
- R"({"fieldn\u0061me1": 1})",
- "fieldname1: 1");
- // String ends with escape character.
- ExpectParseFailureForJson(
- "StringEndsWithEscapeChar", RECOMMENDED,
- "{\"optionalString\": \"abc\\");
- // Field names must be quoted (or it's not valid JSON).
- ExpectParseFailureForJson(
- "FieldNameNotQuoted", RECOMMENDED,
- "{fieldname1: 1}");
- // Trailing comma is not allowed (not valid JSON).
- ExpectParseFailureForJson(
- "TrailingCommaInAnObject", RECOMMENDED,
- R"({"fieldname1":1,})");
- ExpectParseFailureForJson(
- "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
- R"({"fieldname1":1 ,})");
- ExpectParseFailureForJson(
- "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
- R"({"fieldname1":1 , })");
- ExpectParseFailureForJson(
- "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
- R"({
- "fieldname1":1,
- })");
- // JSON doesn't support comments.
- ExpectParseFailureForJson(
- "JsonWithComments", RECOMMENDED,
- R"({
- // This is a comment.
- "fieldname1": 1
- })");
- // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
- RunValidJsonTest(
- "OneLineNoSpaces", RECOMMENDED,
- "{\"optionalInt32\":1,\"optionalInt64\":2}",
- R"(
- optional_int32: 1
- optional_int64: 2
- )");
- RunValidJsonTest(
- "OneLineWithSpaces", RECOMMENDED,
- "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
- R"(
- optional_int32: 1
- optional_int64: 2
- )");
- RunValidJsonTest(
- "MultilineNoSpaces", RECOMMENDED,
- "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
- R"(
- optional_int32: 1
- optional_int64: 2
- )");
- RunValidJsonTest(
- "MultilineWithSpaces", RECOMMENDED,
- "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
- R"(
- optional_int32: 1
- optional_int64: 2
- )");
- // Missing comma between key/value pairs.
- ExpectParseFailureForJson(
- "MissingCommaOneLine", RECOMMENDED,
- "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
- ExpectParseFailureForJson(
- "MissingCommaMultiline", RECOMMENDED,
- "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
- // Duplicated field names are not allowed.
- ExpectParseFailureForJson(
- "FieldNameDuplicate", RECOMMENDED,
- R"({
- "optionalNestedMessage": {a: 1},
- "optionalNestedMessage": {}
- })");
- ExpectParseFailureForJson(
- "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
- R"({
- "optional_nested_message": {a: 1},
- "optionalNestedMessage": {}
- })");
- ExpectParseFailureForJson(
- "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
- R"({
- "optionalNestedMessage": {a: 1},
- "optional_nested_message": {}
- })");
- // Serializers should use lowerCamelCase by default.
- RunValidJsonTestWithValidator(
- "FieldNameInLowerCamelCase", REQUIRED,
- R"({
- "fieldname1": 1,
- "fieldName2": 2,
- "FieldName3": 3,
- "fieldName4": 4
- })",
- [](const Json::Value& value) {
- return value.isMember("fieldname1") &&
- value.isMember("fieldName2") &&
- value.isMember("FieldName3") &&
- value.isMember("fieldName4");
- });
- RunValidJsonTestWithValidator(
- "FieldNameWithNumbers", REQUIRED,
- R"({
- "field0name5": 5,
- "field0Name6": 6
- })",
- [](const Json::Value& value) {
- return value.isMember("field0name5") &&
- value.isMember("field0Name6");
- });
- RunValidJsonTestWithValidator(
- "FieldNameWithMixedCases", REQUIRED,
- R"({
- "fieldName7": 7,
- "FieldName8": 8,
- "fieldName9": 9,
- "FieldName10": 10,
- "FIELDNAME11": 11,
- "FIELDName12": 12
- })",
- [](const Json::Value& value) {
- return value.isMember("fieldName7") &&
- value.isMember("FieldName8") &&
- value.isMember("fieldName9") &&
- value.isMember("FieldName10") &&
- value.isMember("FIELDNAME11") &&
- value.isMember("FIELDName12");
- });
- RunValidJsonTestWithValidator(
- "FieldNameWithDoubleUnderscores", RECOMMENDED,
- R"({
- "FieldName13": 13,
- "FieldName14": 14,
- "fieldName15": 15,
- "fieldName16": 16,
- "fieldName17": 17,
- "FieldName18": 18
- })",
- [](const Json::Value& value) {
- return value.isMember("FieldName13") &&
- value.isMember("FieldName14") &&
- value.isMember("fieldName15") &&
- value.isMember("fieldName16") &&
- value.isMember("fieldName17") &&
- value.isMember("FieldName18");
- });
-
- // Integer fields.
- RunValidJsonTest(
- "Int32FieldMaxValue", REQUIRED,
- R"({"optionalInt32": 2147483647})",
- "optional_int32: 2147483647");
- RunValidJsonTest(
- "Int32FieldMinValue", REQUIRED,
- R"({"optionalInt32": -2147483648})",
- "optional_int32: -2147483648");
- RunValidJsonTest(
- "Uint32FieldMaxValue", REQUIRED,
- R"({"optionalUint32": 4294967295})",
- "optional_uint32: 4294967295");
- RunValidJsonTest(
- "Int64FieldMaxValue", REQUIRED,
- R"({"optionalInt64": "9223372036854775807"})",
- "optional_int64: 9223372036854775807");
- RunValidJsonTest(
- "Int64FieldMinValue", REQUIRED,
- R"({"optionalInt64": "-9223372036854775808"})",
- "optional_int64: -9223372036854775808");
- RunValidJsonTest(
- "Uint64FieldMaxValue", REQUIRED,
- R"({"optionalUint64": "18446744073709551615"})",
- "optional_uint64: 18446744073709551615");
- // While not the largest Int64, this is the largest
- // Int64 which can be exactly represented within an
- // IEEE-754 64-bit float, which is the expected level
- // of interoperability guarantee. Larger values may
- // work in some implementations, but should not be
- // relied upon.
- RunValidJsonTest(
- "Int64FieldMaxValueNotQuoted", REQUIRED,
- R"({"optionalInt64": 9223372036854774784})",
- "optional_int64: 9223372036854774784");
- RunValidJsonTest(
- "Int64FieldMinValueNotQuoted", REQUIRED,
- R"({"optionalInt64": -9223372036854775808})",
- "optional_int64: -9223372036854775808");
- // Largest interoperable Uint64; see comment above
- // for Int64FieldMaxValueNotQuoted.
- RunValidJsonTest(
- "Uint64FieldMaxValueNotQuoted", REQUIRED,
- R"({"optionalUint64": 18446744073709549568})",
- "optional_uint64: 18446744073709549568");
- // Values can be represented as JSON strings.
- RunValidJsonTest(
- "Int32FieldStringValue", REQUIRED,
- R"({"optionalInt32": "2147483647"})",
- "optional_int32: 2147483647");
- RunValidJsonTest(
- "Int32FieldStringValueEscaped", REQUIRED,
- R"({"optionalInt32": "2\u003147483647"})",
- "optional_int32: 2147483647");
-
- // Parsers reject out-of-bound integer values.
- ExpectParseFailureForJson(
- "Int32FieldTooLarge", REQUIRED,
- R"({"optionalInt32": 2147483648})");
- ExpectParseFailureForJson(
- "Int32FieldTooSmall", REQUIRED,
- R"({"optionalInt32": -2147483649})");
- ExpectParseFailureForJson(
- "Uint32FieldTooLarge", REQUIRED,
- R"({"optionalUint32": 4294967296})");
- ExpectParseFailureForJson(
- "Int64FieldTooLarge", REQUIRED,
- R"({"optionalInt64": "9223372036854775808"})");
- ExpectParseFailureForJson(
- "Int64FieldTooSmall", REQUIRED,
- R"({"optionalInt64": "-9223372036854775809"})");
- ExpectParseFailureForJson(
- "Uint64FieldTooLarge", REQUIRED,
- R"({"optionalUint64": "18446744073709551616"})");
- // Parser reject non-integer numeric values as well.
- ExpectParseFailureForJson(
- "Int32FieldNotInteger", REQUIRED,
- R"({"optionalInt32": 0.5})");
- ExpectParseFailureForJson(
- "Uint32FieldNotInteger", REQUIRED,
- R"({"optionalUint32": 0.5})");
- ExpectParseFailureForJson(
- "Int64FieldNotInteger", REQUIRED,
- R"({"optionalInt64": "0.5"})");
- ExpectParseFailureForJson(
- "Uint64FieldNotInteger", REQUIRED,
- R"({"optionalUint64": "0.5"})");
-
- // Integers but represented as float values are accepted.
- RunValidJsonTest(
- "Int32FieldFloatTrailingZero", REQUIRED,
- R"({"optionalInt32": 100000.000})",
- "optional_int32: 100000");
- RunValidJsonTest(
- "Int32FieldExponentialFormat", REQUIRED,
- R"({"optionalInt32": 1e5})",
- "optional_int32: 100000");
- RunValidJsonTest(
- "Int32FieldMaxFloatValue", REQUIRED,
- R"({"optionalInt32": 2.147483647e9})",
- "optional_int32: 2147483647");
- RunValidJsonTest(
- "Int32FieldMinFloatValue", REQUIRED,
- R"({"optionalInt32": -2.147483648e9})",
- "optional_int32: -2147483648");
- RunValidJsonTest(
- "Uint32FieldMaxFloatValue", REQUIRED,
- R"({"optionalUint32": 4.294967295e9})",
- "optional_uint32: 4294967295");
-
- // Parser reject non-numeric values.
- ExpectParseFailureForJson(
- "Int32FieldNotNumber", REQUIRED,
- R"({"optionalInt32": "3x3"})");
- ExpectParseFailureForJson(
- "Uint32FieldNotNumber", REQUIRED,
- R"({"optionalUint32": "3x3"})");
- ExpectParseFailureForJson(
- "Int64FieldNotNumber", REQUIRED,
- R"({"optionalInt64": "3x3"})");
- ExpectParseFailureForJson(
- "Uint64FieldNotNumber", REQUIRED,
- R"({"optionalUint64": "3x3"})");
- // JSON does not allow "+" on numric values.
- ExpectParseFailureForJson(
- "Int32FieldPlusSign", REQUIRED,
- R"({"optionalInt32": +1})");
- // JSON doesn't allow leading 0s.
- ExpectParseFailureForJson(
- "Int32FieldLeadingZero", REQUIRED,
- R"({"optionalInt32": 01})");
- ExpectParseFailureForJson(
- "Int32FieldNegativeWithLeadingZero", REQUIRED,
- R"({"optionalInt32": -01})");
- // String values must follow the same syntax rule. Specifically leading
- // or trailing spaces are not allowed.
- ExpectParseFailureForJson(
- "Int32FieldLeadingSpace", REQUIRED,
- R"({"optionalInt32": " 1"})");
- ExpectParseFailureForJson(
- "Int32FieldTrailingSpace", REQUIRED,
- R"({"optionalInt32": "1 "})");
-
- // 64-bit values are serialized as strings.
- RunValidJsonTestWithValidator(
- "Int64FieldBeString", RECOMMENDED,
- R"({"optionalInt64": 1})",
- [](const Json::Value& value) {
- return value["optionalInt64"].type() == Json::stringValue &&
- value["optionalInt64"].asString() == "1";
- });
- RunValidJsonTestWithValidator(
- "Uint64FieldBeString", RECOMMENDED,
- R"({"optionalUint64": 1})",
- [](const Json::Value& value) {
- return value["optionalUint64"].type() == Json::stringValue &&
- value["optionalUint64"].asString() == "1";
- });
-
- // Bool fields.
- RunValidJsonTest(
- "BoolFieldTrue", REQUIRED,
- R"({"optionalBool":true})",
- "optional_bool: true");
- RunValidJsonTest(
- "BoolFieldFalse", REQUIRED,
- R"({"optionalBool":false})",
- "optional_bool: false");
-
- // Other forms are not allowed.
- ExpectParseFailureForJson(
- "BoolFieldIntegerZero", RECOMMENDED,
- R"({"optionalBool":0})");
- ExpectParseFailureForJson(
- "BoolFieldIntegerOne", RECOMMENDED,
- R"({"optionalBool":1})");
- ExpectParseFailureForJson(
- "BoolFieldCamelCaseTrue", RECOMMENDED,
- R"({"optionalBool":True})");
- ExpectParseFailureForJson(
- "BoolFieldCamelCaseFalse", RECOMMENDED,
- R"({"optionalBool":False})");
- ExpectParseFailureForJson(
- "BoolFieldAllCapitalTrue", RECOMMENDED,
- R"({"optionalBool":TRUE})");
- ExpectParseFailureForJson(
- "BoolFieldAllCapitalFalse", RECOMMENDED,
- R"({"optionalBool":FALSE})");
- ExpectParseFailureForJson(
- "BoolFieldDoubleQuotedTrue", RECOMMENDED,
- R"({"optionalBool":"true"})");
- ExpectParseFailureForJson(
- "BoolFieldDoubleQuotedFalse", RECOMMENDED,
- R"({"optionalBool":"false"})");
-
- // Float fields.
- RunValidJsonTest(
- "FloatFieldMinPositiveValue", REQUIRED,
- R"({"optionalFloat": 1.175494e-38})",
- "optional_float: 1.175494e-38");
- RunValidJsonTest(
- "FloatFieldMaxNegativeValue", REQUIRED,
- R"({"optionalFloat": -1.175494e-38})",
- "optional_float: -1.175494e-38");
- RunValidJsonTest(
- "FloatFieldMaxPositiveValue", REQUIRED,
- R"({"optionalFloat": 3.402823e+38})",
- "optional_float: 3.402823e+38");
- RunValidJsonTest(
- "FloatFieldMinNegativeValue", REQUIRED,
- R"({"optionalFloat": 3.402823e+38})",
- "optional_float: 3.402823e+38");
- // Values can be quoted.
- RunValidJsonTest(
- "FloatFieldQuotedValue", REQUIRED,
- R"({"optionalFloat": "1"})",
- "optional_float: 1");
- // Special values.
- RunValidJsonTest(
- "FloatFieldNan", REQUIRED,
- R"({"optionalFloat": "NaN"})",
- "optional_float: nan");
- RunValidJsonTest(
- "FloatFieldInfinity", REQUIRED,
- R"({"optionalFloat": "Infinity"})",
- "optional_float: inf");
- RunValidJsonTest(
- "FloatFieldNegativeInfinity", REQUIRED,
- R"({"optionalFloat": "-Infinity"})",
- "optional_float: -inf");
- // Non-cannonical Nan will be correctly normalized.
- {
- TestAllTypesProto3 message;
- // IEEE floating-point standard 32-bit quiet NaN:
- // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
- message.set_optional_float(
- WireFormatLite::DecodeFloat(0x7FA12345));
- RunValidJsonTestWithProtobufInput(
- "FloatFieldNormalizeQuietNan", REQUIRED, message,
- "optional_float: nan");
- // IEEE floating-point standard 64-bit signaling NaN:
- // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
- message.set_optional_float(
- WireFormatLite::DecodeFloat(0xFFB54321));
- RunValidJsonTestWithProtobufInput(
- "FloatFieldNormalizeSignalingNan", REQUIRED, message,
- "optional_float: nan");
- }
-
- // Special values must be quoted.
- ExpectParseFailureForJson(
- "FloatFieldNanNotQuoted", RECOMMENDED,
- R"({"optionalFloat": NaN})");
- ExpectParseFailureForJson(
- "FloatFieldInfinityNotQuoted", RECOMMENDED,
- R"({"optionalFloat": Infinity})");
- ExpectParseFailureForJson(
- "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
- R"({"optionalFloat": -Infinity})");
- // Parsers should reject out-of-bound values.
- ExpectParseFailureForJson(
- "FloatFieldTooSmall", REQUIRED,
- R"({"optionalFloat": -3.502823e+38})");
- ExpectParseFailureForJson(
- "FloatFieldTooLarge", REQUIRED,
- R"({"optionalFloat": 3.502823e+38})");
-
- // Double fields.
- RunValidJsonTest(
- "DoubleFieldMinPositiveValue", REQUIRED,
- R"({"optionalDouble": 2.22507e-308})",
- "optional_double: 2.22507e-308");
- RunValidJsonTest(
- "DoubleFieldMaxNegativeValue", REQUIRED,
- R"({"optionalDouble": -2.22507e-308})",
- "optional_double: -2.22507e-308");
- RunValidJsonTest(
- "DoubleFieldMaxPositiveValue", REQUIRED,
- R"({"optionalDouble": 1.79769e+308})",
- "optional_double: 1.79769e+308");
- RunValidJsonTest(
- "DoubleFieldMinNegativeValue", REQUIRED,
- R"({"optionalDouble": -1.79769e+308})",
- "optional_double: -1.79769e+308");
- // Values can be quoted.
- RunValidJsonTest(
- "DoubleFieldQuotedValue", REQUIRED,
- R"({"optionalDouble": "1"})",
- "optional_double: 1");
- // Speical values.
- RunValidJsonTest(
- "DoubleFieldNan", REQUIRED,
- R"({"optionalDouble": "NaN"})",
- "optional_double: nan");
- RunValidJsonTest(
- "DoubleFieldInfinity", REQUIRED,
- R"({"optionalDouble": "Infinity"})",
- "optional_double: inf");
- RunValidJsonTest(
- "DoubleFieldNegativeInfinity", REQUIRED,
- R"({"optionalDouble": "-Infinity"})",
- "optional_double: -inf");
- // Non-cannonical Nan will be correctly normalized.
- {
- TestAllTypesProto3 message;
- message.set_optional_double(
- WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
- RunValidJsonTestWithProtobufInput(
- "DoubleFieldNormalizeQuietNan", REQUIRED, message,
- "optional_double: nan");
- message.set_optional_double(
- WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
- RunValidJsonTestWithProtobufInput(
- "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
- "optional_double: nan");
- }
-
- // Special values must be quoted.
- ExpectParseFailureForJson(
- "DoubleFieldNanNotQuoted", RECOMMENDED,
- R"({"optionalDouble": NaN})");
- ExpectParseFailureForJson(
- "DoubleFieldInfinityNotQuoted", RECOMMENDED,
- R"({"optionalDouble": Infinity})");
- ExpectParseFailureForJson(
- "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
- R"({"optionalDouble": -Infinity})");
-
- // Parsers should reject out-of-bound values.
- ExpectParseFailureForJson(
- "DoubleFieldTooSmall", REQUIRED,
- R"({"optionalDouble": -1.89769e+308})");
- ExpectParseFailureForJson(
- "DoubleFieldTooLarge", REQUIRED,
- R"({"optionalDouble": +1.89769e+308})");
-
- // Enum fields.
- RunValidJsonTest(
- "EnumField", REQUIRED,
- R"({"optionalNestedEnum": "FOO"})",
- "optional_nested_enum: FOO");
- // Enum values must be represented as strings.
- ExpectParseFailureForJson(
- "EnumFieldNotQuoted", REQUIRED,
- R"({"optionalNestedEnum": FOO})");
- // Numeric values are allowed.
- RunValidJsonTest(
- "EnumFieldNumericValueZero", REQUIRED,
- R"({"optionalNestedEnum": 0})",
- "optional_nested_enum: FOO");
- RunValidJsonTest(
- "EnumFieldNumericValueNonZero", REQUIRED,
- R"({"optionalNestedEnum": 1})",
- "optional_nested_enum: BAR");
- // Unknown enum values are represented as numeric values.
- RunValidJsonTestWithValidator(
- "EnumFieldUnknownValue", REQUIRED,
- R"({"optionalNestedEnum": 123})",
- [](const Json::Value& value) {
- return value["optionalNestedEnum"].type() == Json::intValue &&
- value["optionalNestedEnum"].asInt() == 123;
- });
-
- // String fields.
- RunValidJsonTest(
- "StringField", REQUIRED,
- R"({"optionalString": "Hello world!"})",
- "optional_string: \"Hello world!\"");
- RunValidJsonTest(
- "StringFieldUnicode", REQUIRED,
- // Google in Chinese.
- R"({"optionalString": "谷歌"})",
- R"(optional_string: "谷歌")");
- RunValidJsonTest(
- "StringFieldEscape", REQUIRED,
- R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
- R"(optional_string: "\"\\/\b\f\n\r\t")");
- RunValidJsonTest(
- "StringFieldUnicodeEscape", REQUIRED,
- R"({"optionalString": "\u8C37\u6B4C"})",
- R"(optional_string: "谷歌")");
- RunValidJsonTest(
- "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
- R"({"optionalString": "\u8c37\u6b4c"})",
- R"(optional_string: "谷歌")");
- RunValidJsonTest(
- "StringFieldSurrogatePair", REQUIRED,
- // The character is an emoji: grinning face with smiling eyes. 😁
- R"({"optionalString": "\uD83D\uDE01"})",
- R"(optional_string: "\xF0\x9F\x98\x81")");
-
- // Unicode escapes must start with "\u" (lowercase u).
- ExpectParseFailureForJson(
- "StringFieldUppercaseEscapeLetter", RECOMMENDED,
- R"({"optionalString": "\U8C37\U6b4C"})");
- ExpectParseFailureForJson(
- "StringFieldInvalidEscape", RECOMMENDED,
- R"({"optionalString": "\uXXXX\u6B4C"})");
- ExpectParseFailureForJson(
- "StringFieldUnterminatedEscape", RECOMMENDED,
- R"({"optionalString": "\u8C3"})");
- ExpectParseFailureForJson(
- "StringFieldUnpairedHighSurrogate", RECOMMENDED,
- R"({"optionalString": "\uD800"})");
- ExpectParseFailureForJson(
- "StringFieldUnpairedLowSurrogate", RECOMMENDED,
- R"({"optionalString": "\uDC00"})");
- ExpectParseFailureForJson(
- "StringFieldSurrogateInWrongOrder", RECOMMENDED,
- R"({"optionalString": "\uDE01\uD83D"})");
- ExpectParseFailureForJson(
- "StringFieldNotAString", REQUIRED,
- R"({"optionalString": 12345})");
-
- // Bytes fields.
- RunValidJsonTest(
- "BytesField", REQUIRED,
- R"({"optionalBytes": "AQI="})",
- R"(optional_bytes: "\x01\x02")");
- RunValidJsonTest(
- "BytesFieldBase64Url", RECOMMENDED,
- R"({"optionalBytes": "-_"})",
- R"(optional_bytes: "\xfb")");
-
- // Message fields.
- RunValidJsonTest(
- "MessageField", REQUIRED,
- R"({"optionalNestedMessage": {"a": 1234}})",
- "optional_nested_message: {a: 1234}");
-
- // Oneof fields.
- ExpectParseFailureForJson(
- "OneofFieldDuplicate", REQUIRED,
- R"({"oneofUint32": 1, "oneofString": "test"})");
- // Ensure zero values for oneof make it out/backs.
- TestAllTypesProto3 messageProto3;
- TestAllTypesProto2 messageProto2;
- TestOneofMessage(messageProto3, true);
- TestOneofMessage(messageProto2, false);
- RunValidJsonTest(
- "OneofZeroUint32", RECOMMENDED,
- R"({"oneofUint32": 0})", "oneof_uint32: 0");
- RunValidJsonTest(
- "OneofZeroMessage", RECOMMENDED,
- R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
- RunValidJsonTest(
- "OneofZeroString", RECOMMENDED,
- R"({"oneofString": ""})", "oneof_string: \"\"");
- RunValidJsonTest(
- "OneofZeroBytes", RECOMMENDED,
- R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
- RunValidJsonTest(
- "OneofZeroBool", RECOMMENDED,
- R"({"oneofBool": false})", "oneof_bool: false");
- RunValidJsonTest(
- "OneofZeroUint64", RECOMMENDED,
- R"({"oneofUint64": 0})", "oneof_uint64: 0");
- RunValidJsonTest(
- "OneofZeroFloat", RECOMMENDED,
- R"({"oneofFloat": 0.0})", "oneof_float: 0");
- RunValidJsonTest(
- "OneofZeroDouble", RECOMMENDED,
- R"({"oneofDouble": 0.0})", "oneof_double: 0");
- RunValidJsonTest(
- "OneofZeroEnum", RECOMMENDED,
- R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
-
- // Repeated fields.
- RunValidJsonTest(
- "PrimitiveRepeatedField", REQUIRED,
- R"({"repeatedInt32": [1, 2, 3, 4]})",
- "repeated_int32: [1, 2, 3, 4]");
- RunValidJsonTest(
- "EnumRepeatedField", REQUIRED,
- R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
- "repeated_nested_enum: [FOO, BAR, BAZ]");
- RunValidJsonTest(
- "StringRepeatedField", REQUIRED,
- R"({"repeatedString": ["Hello", "world"]})",
- R"(repeated_string: ["Hello", "world"])");
- RunValidJsonTest(
- "BytesRepeatedField", REQUIRED,
- R"({"repeatedBytes": ["AAEC", "AQI="]})",
- R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
- RunValidJsonTest(
- "MessageRepeatedField", REQUIRED,
- R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
- "repeated_nested_message: {a: 1234}"
- "repeated_nested_message: {a: 5678}");
-
- // Repeated field elements are of incorrect type.
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
- R"({"repeatedInt32": [1, false, 3, 4]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
- R"({"repeatedInt32": [1, 2, "name", 4]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
- R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
- R"({"repeatedString": ["1", 2, "3", "4"]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
- R"({"repeatedString": ["1", "2", false, "4"]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
- R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
- R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
- R"({"repeatedNestedMessage": [{"a": 1}, false]})");
- ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
- R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
- // Trailing comma in the repeated field is not allowed.
- ExpectParseFailureForJson(
- "RepeatedFieldTrailingComma", RECOMMENDED,
- R"({"repeatedInt32": [1, 2, 3, 4,]})");
- ExpectParseFailureForJson(
- "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
- "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
- ExpectParseFailureForJson(
- "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
- "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
- ExpectParseFailureForJson(
- "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
- "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
-
- // Map fields.
- RunValidJsonTest(
- "Int32MapField", REQUIRED,
- R"({"mapInt32Int32": {"1": 2, "3": 4}})",
- "map_int32_int32: {key: 1 value: 2}"
- "map_int32_int32: {key: 3 value: 4}");
- ExpectParseFailureForJson(
- "Int32MapFieldKeyNotQuoted", RECOMMENDED,
- R"({"mapInt32Int32": {1: 2, 3: 4}})");
- RunValidJsonTest(
- "Uint32MapField", REQUIRED,
- R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
- "map_uint32_uint32: {key: 1 value: 2}"
- "map_uint32_uint32: {key: 3 value: 4}");
- ExpectParseFailureForJson(
- "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
- R"({"mapUint32Uint32": {1: 2, 3: 4}})");
- RunValidJsonTest(
- "Int64MapField", REQUIRED,
- R"({"mapInt64Int64": {"1": 2, "3": 4}})",
- "map_int64_int64: {key: 1 value: 2}"
- "map_int64_int64: {key: 3 value: 4}");
- ExpectParseFailureForJson(
- "Int64MapFieldKeyNotQuoted", RECOMMENDED,
- R"({"mapInt64Int64": {1: 2, 3: 4}})");
- RunValidJsonTest(
- "Uint64MapField", REQUIRED,
- R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
- "map_uint64_uint64: {key: 1 value: 2}"
- "map_uint64_uint64: {key: 3 value: 4}");
- ExpectParseFailureForJson(
- "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
- R"({"mapUint64Uint64": {1: 2, 3: 4}})");
- RunValidJsonTest(
- "BoolMapField", REQUIRED,
- R"({"mapBoolBool": {"true": true, "false": false}})",
- "map_bool_bool: {key: true value: true}"
- "map_bool_bool: {key: false value: false}");
- ExpectParseFailureForJson(
- "BoolMapFieldKeyNotQuoted", RECOMMENDED,
- R"({"mapBoolBool": {true: true, false: false}})");
- RunValidJsonTest(
- "MessageMapField", REQUIRED,
- R"({
- "mapStringNestedMessage": {
- "hello": {"a": 1234},
- "world": {"a": 5678}
- }
- })",
- R"(
- map_string_nested_message: {
- key: "hello"
- value: {a: 1234}
- }
- map_string_nested_message: {
- key: "world"
- value: {a: 5678}
- }
- )");
- // Since Map keys are represented as JSON strings, escaping should be allowed.
- RunValidJsonTest(
- "Int32MapEscapedKey", REQUIRED,
- R"({"mapInt32Int32": {"\u0031": 2}})",
- "map_int32_int32: {key: 1 value: 2}");
- RunValidJsonTest(
- "Int64MapEscapedKey", REQUIRED,
- R"({"mapInt64Int64": {"\u0031": 2}})",
- "map_int64_int64: {key: 1 value: 2}");
- RunValidJsonTest(
- "BoolMapEscapedKey", REQUIRED,
- R"({"mapBoolBool": {"tr\u0075e": true}})",
- "map_bool_bool: {key: true value: true}");
-
- // "null" is accepted for all fields types.
- RunValidJsonTest(
- "AllFieldAcceptNull", REQUIRED,
- R"({
- "optionalInt32": null,
- "optionalInt64": null,
- "optionalUint32": null,
- "optionalUint64": null,
- "optionalSint32": null,
- "optionalSint64": null,
- "optionalFixed32": null,
- "optionalFixed64": null,
- "optionalSfixed32": null,
- "optionalSfixed64": null,
- "optionalFloat": null,
- "optionalDouble": null,
- "optionalBool": null,
- "optionalString": null,
- "optionalBytes": null,
- "optionalNestedEnum": null,
- "optionalNestedMessage": null,
- "repeatedInt32": null,
- "repeatedInt64": null,
- "repeatedUint32": null,
- "repeatedUint64": null,
- "repeatedSint32": null,
- "repeatedSint64": null,
- "repeatedFixed32": null,
- "repeatedFixed64": null,
- "repeatedSfixed32": null,
- "repeatedSfixed64": null,
- "repeatedFloat": null,
- "repeatedDouble": null,
- "repeatedBool": null,
- "repeatedString": null,
- "repeatedBytes": null,
- "repeatedNestedEnum": null,
- "repeatedNestedMessage": null,
- "mapInt32Int32": null,
- "mapBoolBool": null,
- "mapStringNestedMessage": null
- })",
- "");
-
- // Repeated field elements cannot be null.
- ExpectParseFailureForJson(
- "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
- R"({"repeatedInt32": [1, null, 2]})");
- ExpectParseFailureForJson(
- "RepeatedFieldMessageElementIsNull", RECOMMENDED,
- R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
- // Map field keys cannot be null.
- ExpectParseFailureForJson(
- "MapFieldKeyIsNull", RECOMMENDED,
- R"({"mapInt32Int32": {null: 1}})");
- // Map field values cannot be null.
- ExpectParseFailureForJson(
- "MapFieldValueIsNull", RECOMMENDED,
- R"({"mapInt32Int32": {"0": null}})");
-
- // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
- // quotes.
- ExpectParseFailureForJson(
- "StringFieldSingleQuoteKey", RECOMMENDED,
- R"({'optionalString': "Hello world!"})");
- ExpectParseFailureForJson(
- "StringFieldSingleQuoteValue", RECOMMENDED,
- R"({"optionalString": 'Hello world!'})");
- ExpectParseFailureForJson(
- "StringFieldSingleQuoteBoth", RECOMMENDED,
- R"({'optionalString': 'Hello world!'})");
-
- // Unknown fields.
- {
- TestAllTypesProto3 messageProto3;
- TestAllTypesProto2 messageProto2;
- //TODO(yilunchong): update this behavior when unknown field's behavior
- // changed in open source. Also delete
- // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
- // from failure list of python_cpp python java
- TestUnknownMessage(messageProto3, true);
- TestUnknownMessage(messageProto2, false);
- }
-
- // Wrapper types.
- RunValidJsonTest(
- "OptionalBoolWrapper", REQUIRED,
- R"({"optionalBoolWrapper": false})",
- "optional_bool_wrapper: {value: false}");
- RunValidJsonTest(
- "OptionalInt32Wrapper", REQUIRED,
- R"({"optionalInt32Wrapper": 0})",
- "optional_int32_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalUint32Wrapper", REQUIRED,
- R"({"optionalUint32Wrapper": 0})",
- "optional_uint32_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalInt64Wrapper", REQUIRED,
- R"({"optionalInt64Wrapper": 0})",
- "optional_int64_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalUint64Wrapper", REQUIRED,
- R"({"optionalUint64Wrapper": 0})",
- "optional_uint64_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalFloatWrapper", REQUIRED,
- R"({"optionalFloatWrapper": 0})",
- "optional_float_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalDoubleWrapper", REQUIRED,
- R"({"optionalDoubleWrapper": 0})",
- "optional_double_wrapper: {value: 0}");
- RunValidJsonTest(
- "OptionalStringWrapper", REQUIRED,
- R"({"optionalStringWrapper": ""})",
- R"(optional_string_wrapper: {value: ""})");
- RunValidJsonTest(
- "OptionalBytesWrapper", REQUIRED,
- R"({"optionalBytesWrapper": ""})",
- R"(optional_bytes_wrapper: {value: ""})");
- RunValidJsonTest(
- "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
- R"({
- "optionalBoolWrapper": true,
- "optionalInt32Wrapper": 1,
- "optionalUint32Wrapper": 1,
- "optionalInt64Wrapper": "1",
- "optionalUint64Wrapper": "1",
- "optionalFloatWrapper": 1,
- "optionalDoubleWrapper": 1,
- "optionalStringWrapper": "1",
- "optionalBytesWrapper": "AQI="
- })",
- R"(
- optional_bool_wrapper: {value: true}
- optional_int32_wrapper: {value: 1}
- optional_uint32_wrapper: {value: 1}
- optional_int64_wrapper: {value: 1}
- optional_uint64_wrapper: {value: 1}
- optional_float_wrapper: {value: 1}
- optional_double_wrapper: {value: 1}
- optional_string_wrapper: {value: "1"}
- optional_bytes_wrapper: {value: "\x01\x02"}
- )");
- RunValidJsonTest(
- "RepeatedBoolWrapper", REQUIRED,
- R"({"repeatedBoolWrapper": [true, false]})",
- "repeated_bool_wrapper: {value: true}"
- "repeated_bool_wrapper: {value: false}");
- RunValidJsonTest(
- "RepeatedInt32Wrapper", REQUIRED,
- R"({"repeatedInt32Wrapper": [0, 1]})",
- "repeated_int32_wrapper: {value: 0}"
- "repeated_int32_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedUint32Wrapper", REQUIRED,
- R"({"repeatedUint32Wrapper": [0, 1]})",
- "repeated_uint32_wrapper: {value: 0}"
- "repeated_uint32_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedInt64Wrapper", REQUIRED,
- R"({"repeatedInt64Wrapper": [0, 1]})",
- "repeated_int64_wrapper: {value: 0}"
- "repeated_int64_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedUint64Wrapper", REQUIRED,
- R"({"repeatedUint64Wrapper": [0, 1]})",
- "repeated_uint64_wrapper: {value: 0}"
- "repeated_uint64_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedFloatWrapper", REQUIRED,
- R"({"repeatedFloatWrapper": [0, 1]})",
- "repeated_float_wrapper: {value: 0}"
- "repeated_float_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedDoubleWrapper", REQUIRED,
- R"({"repeatedDoubleWrapper": [0, 1]})",
- "repeated_double_wrapper: {value: 0}"
- "repeated_double_wrapper: {value: 1}");
- RunValidJsonTest(
- "RepeatedStringWrapper", REQUIRED,
- R"({"repeatedStringWrapper": ["", "AQI="]})",
- R"(
- repeated_string_wrapper: {value: ""}
- repeated_string_wrapper: {value: "AQI="}
- )");
- RunValidJsonTest(
- "RepeatedBytesWrapper", REQUIRED,
- R"({"repeatedBytesWrapper": ["", "AQI="]})",
- R"(
- repeated_bytes_wrapper: {value: ""}
- repeated_bytes_wrapper: {value: "\x01\x02"}
- )");
- RunValidJsonTest(
- "WrapperTypesWithNullValue", REQUIRED,
- R"({
- "optionalBoolWrapper": null,
- "optionalInt32Wrapper": null,
- "optionalUint32Wrapper": null,
- "optionalInt64Wrapper": null,
- "optionalUint64Wrapper": null,
- "optionalFloatWrapper": null,
- "optionalDoubleWrapper": null,
- "optionalStringWrapper": null,
- "optionalBytesWrapper": null,
- "repeatedBoolWrapper": null,
- "repeatedInt32Wrapper": null,
- "repeatedUint32Wrapper": null,
- "repeatedInt64Wrapper": null,
- "repeatedUint64Wrapper": null,
- "repeatedFloatWrapper": null,
- "repeatedDoubleWrapper": null,
- "repeatedStringWrapper": null,
- "repeatedBytesWrapper": null
- })",
- "");
-
- // Duration
- RunValidJsonTest(
- "DurationMinValue", REQUIRED,
- R"({"optionalDuration": "-315576000000.999999999s"})",
- "optional_duration: {seconds: -315576000000 nanos: -999999999}");
- RunValidJsonTest(
- "DurationMaxValue", REQUIRED,
- R"({"optionalDuration": "315576000000.999999999s"})",
- "optional_duration: {seconds: 315576000000 nanos: 999999999}");
- RunValidJsonTest(
- "DurationRepeatedValue", REQUIRED,
- 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,
- R"({"optionalDuration": "1"})");
- ExpectParseFailureForJson(
- "DurationJsonInputTooSmall", REQUIRED,
- R"({"optionalDuration": "-315576000001.000000000s"})");
- ExpectParseFailureForJson(
- "DurationJsonInputTooLarge", REQUIRED,
- R"({"optionalDuration": "315576000001.000000000s"})");
- ExpectSerializeFailureForJson(
- "DurationProtoInputTooSmall", REQUIRED,
- "optional_duration: {seconds: -315576000001 nanos: 0}");
- ExpectSerializeFailureForJson(
- "DurationProtoInputTooLarge", REQUIRED,
- "optional_duration: {seconds: 315576000001 nanos: 0}");
-
- RunValidJsonTestWithValidator(
- "DurationHasZeroFractionalDigit", RECOMMENDED,
- R"({"optionalDuration": "1.000000000s"})",
- [](const Json::Value& value) {
- return value["optionalDuration"].asString() == "1s";
- });
- RunValidJsonTestWithValidator(
- "DurationHas3FractionalDigits", RECOMMENDED,
- R"({"optionalDuration": "1.010000000s"})",
- [](const Json::Value& value) {
- return value["optionalDuration"].asString() == "1.010s";
- });
- RunValidJsonTestWithValidator(
- "DurationHas6FractionalDigits", RECOMMENDED,
- R"({"optionalDuration": "1.000010000s"})",
- [](const Json::Value& value) {
- return value["optionalDuration"].asString() == "1.000010s";
- });
- RunValidJsonTestWithValidator(
- "DurationHas9FractionalDigits", RECOMMENDED,
- R"({"optionalDuration": "1.000000010s"})",
- [](const Json::Value& value) {
- return value["optionalDuration"].asString() == "1.000000010s";
- });
-
- // Timestamp
- RunValidJsonTest(
- "TimestampMinValue", REQUIRED,
- R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
- "optional_timestamp: {seconds: -62135596800}");
- RunValidJsonTest(
- "TimestampMaxValue", REQUIRED,
- R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
- "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
- RunValidJsonTest(
- "TimestampRepeatedValue", REQUIRED,
- R"({
- "repeatedTimestamp": [
- "0001-01-01T00:00:00Z",
- "9999-12-31T23:59:59.999999999Z"
- ]
- })",
- "repeated_timestamp: {seconds: -62135596800}"
- "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
- RunValidJsonTest(
- "TimestampWithPositiveOffset", REQUIRED,
- R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
- "optional_timestamp: {seconds: 0}");
- RunValidJsonTest(
- "TimestampWithNegativeOffset", REQUIRED,
- R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
- "optional_timestamp: {seconds: 0}");
- RunValidJsonTest(
- "TimestampNull", REQUIRED,
- R"({"optionalTimestamp": null})",
- "");
-
- ExpectParseFailureForJson(
- "TimestampJsonInputTooSmall", REQUIRED,
- R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
- ExpectParseFailureForJson(
- "TimestampJsonInputTooLarge", REQUIRED,
- R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
- ExpectParseFailureForJson(
- "TimestampJsonInputMissingZ", REQUIRED,
- R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
- ExpectParseFailureForJson(
- "TimestampJsonInputMissingT", REQUIRED,
- R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
- ExpectParseFailureForJson(
- "TimestampJsonInputLowercaseZ", REQUIRED,
- R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
- ExpectParseFailureForJson(
- "TimestampJsonInputLowercaseT", REQUIRED,
- R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
- ExpectSerializeFailureForJson(
- "TimestampProtoInputTooSmall", REQUIRED,
- "optional_timestamp: {seconds: -62135596801}");
- ExpectSerializeFailureForJson(
- "TimestampProtoInputTooLarge", REQUIRED,
- "optional_timestamp: {seconds: 253402300800}");
- RunValidJsonTestWithValidator(
- "TimestampZeroNormalized", RECOMMENDED,
- R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
- [](const Json::Value& value) {
- return value["optionalTimestamp"].asString() ==
- "1970-01-01T00:00:00Z";
- });
- RunValidJsonTestWithValidator(
- "TimestampHasZeroFractionalDigit", RECOMMENDED,
- R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
- [](const Json::Value& value) {
- return value["optionalTimestamp"].asString() ==
- "1970-01-01T00:00:00Z";
- });
- RunValidJsonTestWithValidator(
- "TimestampHas3FractionalDigits", RECOMMENDED,
- R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
- [](const Json::Value& value) {
- return value["optionalTimestamp"].asString() ==
- "1970-01-01T00:00:00.010Z";
- });
- RunValidJsonTestWithValidator(
- "TimestampHas6FractionalDigits", RECOMMENDED,
- R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
- [](const Json::Value& value) {
- return value["optionalTimestamp"].asString() ==
- "1970-01-01T00:00:00.000010Z";
- });
- RunValidJsonTestWithValidator(
- "TimestampHas9FractionalDigits", RECOMMENDED,
- R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
- [](const Json::Value& value) {
- return value["optionalTimestamp"].asString() ==
- "1970-01-01T00:00:00.000000010Z";
- });
-
- // FieldMask
- RunValidJsonTest(
- "FieldMask", REQUIRED,
- R"({"optionalFieldMask": "foo,barBaz"})",
- R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
- ExpectParseFailureForJson(
- "FieldMaskInvalidCharacter", RECOMMENDED,
- R"({"optionalFieldMask": "foo,bar_bar"})");
- ExpectSerializeFailureForJson(
- "FieldMaskPathsDontRoundTrip", RECOMMENDED,
- R"(optional_field_mask: {paths: "fooBar"})");
- ExpectSerializeFailureForJson(
- "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
- R"(optional_field_mask: {paths: "foo_3_bar"})");
- ExpectSerializeFailureForJson(
- "FieldMaskTooManyUnderscore", RECOMMENDED,
- R"(optional_field_mask: {paths: "foo__bar"})");
-
- // Struct
- RunValidJsonTest(
- "Struct", REQUIRED,
- R"({
- "optionalStruct": {
- "nullValue": null,
- "intValue": 1234,
- "boolValue": true,
- "doubleValue": 1234.5678,
- "stringValue": "Hello world!",
- "listValue": [1234, "5678"],
- "objectValue": {
- "value": 0
- }
- }
- })",
- R"(
- optional_struct: {
- fields: {
- key: "nullValue"
- value: {null_value: NULL_VALUE}
- }
- fields: {
- key: "intValue"
- value: {number_value: 1234}
- }
- fields: {
- key: "boolValue"
- value: {bool_value: true}
- }
- fields: {
- key: "doubleValue"
- value: {number_value: 1234.5678}
- }
- fields: {
- key: "stringValue"
- value: {string_value: "Hello world!"}
- }
- fields: {
- key: "listValue"
- value: {
- list_value: {
- values: {
- number_value: 1234
- }
- values: {
- string_value: "5678"
- }
- }
- }
- }
- fields: {
- key: "objectValue"
- value: {
- struct_value: {
- fields: {
- key: "value"
- value: {
- number_value: 0
- }
- }
- }
- }
- }
- }
- )");
- // Value
- RunValidJsonTest(
- "ValueAcceptInteger", REQUIRED,
- R"({"optionalValue": 1})",
- "optional_value: { number_value: 1}");
- RunValidJsonTest(
- "ValueAcceptFloat", REQUIRED,
- R"({"optionalValue": 1.5})",
- "optional_value: { number_value: 1.5}");
- RunValidJsonTest(
- "ValueAcceptBool", REQUIRED,
- R"({"optionalValue": false})",
- "optional_value: { bool_value: false}");
- RunValidJsonTest(
- "ValueAcceptNull", REQUIRED,
- R"({"optionalValue": null})",
- "optional_value: { null_value: NULL_VALUE}");
- RunValidJsonTest(
- "ValueAcceptString", REQUIRED,
- R"({"optionalValue": "hello"})",
- R"(optional_value: { string_value: "hello"})");
- RunValidJsonTest(
- "ValueAcceptList", REQUIRED,
- R"({"optionalValue": [0, "hello"]})",
- R"(
- optional_value: {
- list_value: {
- values: {
- number_value: 0
- }
- values: {
- string_value: "hello"
- }
- }
- }
- )");
- RunValidJsonTest(
- "ValueAcceptListWithNull", REQUIRED,
- R"({"optionalValue": ["x", null, "y"]})",
- R"(
- optional_value: {
- list_value: {
- values: {
- string_value: "x"
- }
- values: {
- null_value: NULL_VALUE
- }
- values: {
- string_value: "y"
- }
- }
- }
- )");
- RunValidJsonTest(
- "ValueAcceptObject", REQUIRED,
- R"({"optionalValue": {"value": 1}})",
- R"(
- optional_value: {
- struct_value: {
- fields: {
- key: "value"
- value: {
- number_value: 1
- }
- }
- }
- }
- )");
-
- // Any
- RunValidJsonTest(
- "Any", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
- "optionalInt32": 12345
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
- optional_int32: 12345
- }
- }
- )");
- RunValidJsonTest(
- "AnyNested", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Any",
- "value": {
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
- "optionalInt32": 12345
- }
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Any] {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
- optional_int32: 12345
- }
- }
- }
- )");
- // The special "@type" tag is not required to appear first.
- RunValidJsonTest(
- "AnyUnorderedTypeTag", REQUIRED,
- R"({
- "optionalAny": {
- "optionalInt32": 12345,
- "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
- optional_int32: 12345
- }
- }
- )");
- // Well-known types in Any.
- RunValidJsonTest(
- "AnyWithInt32ValueWrapper", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Int32Value",
- "value": 12345
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Int32Value] {
- value: 12345
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithDuration", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Duration",
- "value": "1.5s"
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Duration] {
- seconds: 1
- nanos: 500000000
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithTimestamp", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Timestamp",
- "value": "1970-01-01T00:00:00Z"
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Timestamp] {
- seconds: 0
- nanos: 0
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithFieldMask", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.FieldMask",
- "value": "foo,barBaz"
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.FieldMask] {
- paths: ["foo", "bar_baz"]
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithStruct", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Struct",
- "value": {
- "foo": 1
- }
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Struct] {
- fields: {
- key: "foo"
- value: {
- number_value: 1
- }
- }
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithValueForJsonObject", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Value",
- "value": {
- "foo": 1
- }
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Value] {
- struct_value: {
- fields: {
- key: "foo"
- value: {
- number_value: 1
- }
- }
- }
- }
- }
- )");
- RunValidJsonTest(
- "AnyWithValueForInteger", REQUIRED,
- R"({
- "optionalAny": {
- "@type": "type.googleapis.com/google.protobuf.Value",
- "value": 1
- }
- })",
- R"(
- optional_any: {
- [type.googleapis.com/google.protobuf.Value] {
- number_value: 1
- }
- }
- )");
+ RunSuiteImpl();
bool ok = true;
if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h
index 2649f8b2..d5c2f3d4 100644
--- a/conformance/conformance_test.h
+++ b/conformance/conformance_test.h
@@ -40,11 +40,13 @@
#include <functional>
#include <string>
+
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/wire_format_lite.h>
-#include "third_party/jsoncpp/json.h"
+#include "conformance.pb.h"
namespace conformance {
class ConformanceRequest;
@@ -60,6 +62,8 @@ class TestAllTypesProto3;
namespace google {
namespace protobuf {
+class ConformanceTestSuite;
+
class ConformanceTestRunner {
public:
virtual ~ConformanceTestRunner() {}
@@ -76,27 +80,85 @@ class ConformanceTestRunner {
std::string* output) = 0;
};
+// Test runner that spawns the process being tested and communicates with it
+// over a pipe.
+class ForkPipeRunner : public ConformanceTestRunner {
+ public:
+ static int Run(int argc, char *argv[],
+ ConformanceTestSuite* suite);
+
+ private:
+ ForkPipeRunner(const std::string &executable)
+ : child_pid_(-1), executable_(executable) {}
+
+ virtual ~ForkPipeRunner() {}
+
+ void RunTest(const std::string& test_name,
+ const std::string& request,
+ std::string* response);
+
+ // TODO(haberman): make this work on Windows, instead of using these
+ // UNIX-specific APIs.
+ //
+ // There is a platform-agnostic API in
+ // src/google/protobuf/compiler/subprocess.h
+ //
+ // However that API only supports sending a single message to the subprocess.
+ // We really want to be able to send messages and receive responses one at a
+ // time:
+ //
+ // 1. Spawning a new process for each test would take way too long for thousands
+ // of tests and subprocesses like java that can take 100ms or more to start
+ // up.
+ //
+ // 2. Sending all the tests in one big message and receiving all results in one
+ // big message would take away our visibility about which test(s) caused a
+ // crash or other fatal error. It would also give us only a single failure
+ // instead of all of them.
+ void SpawnTestProgram();
+
+ void CheckedWrite(int fd, const void *buf, size_t len);
+ bool TryRead(int fd, void *buf, size_t len);
+ void CheckedRead(int fd, void *buf, size_t len);
+
+ int write_fd_;
+ int read_fd_;
+ pid_t child_pid_;
+ std::string executable_;
+ std::string current_test_name_;
+};
+
// Class representing the test suite itself. To run it, implement your own
-// class derived from ConformanceTestRunner and then write code like:
+// class derived from ConformanceTestRunner, class derived from
+// ConformanceTestSuite and then write code like:
+//
+// class MyConformanceTestSuite : public ConformanceTestSuite {
+// public:
+// void RunSuiteImpl() {
+// // INSERT ACTURAL TESTS.
+// }
+// };
//
// class MyConformanceTestRunner : public ConformanceTestRunner {
// public:
+// static int Run(int argc, char *argv[],
+// ConformanceTestSuite* suite);
+//
+// private:
// virtual void RunTest(...) {
// // INSERT YOUR FRAMEWORK-SPECIFIC CODE HERE.
// }
// };
//
// int main() {
-// MyConformanceTestRunner runner;
-// google::protobuf::ConformanceTestSuite suite;
-//
-// std::string output;
-// suite.RunSuite(&runner, &output);
+// MyConformanceTestSuite suite;
+// MyConformanceTestRunner::Run(argc, argv, &suite);
// }
//
class ConformanceTestSuite {
public:
ConformanceTestSuite() : verbose_(false), enforce_recommended_(false) {}
+ virtual ~ConformanceTestSuite() {}
void SetVerbose(bool verbose) { verbose_ = verbose; }
@@ -129,7 +191,7 @@ class ConformanceTestSuite {
// tests passed.
bool RunSuite(ConformanceTestRunner* runner, std::string* output);
- private:
+ protected:
// Test cases are classified into a few categories:
// REQUIRED: the test case must be passed for an implementation to be
// interoperable with other implementations. For example, a
@@ -146,7 +208,47 @@ class ConformanceTestSuite {
REQUIRED = 0,
RECOMMENDED = 1,
};
- string ConformanceLevelToString(ConformanceLevel level);
+
+ class ConformanceRequestSetting {
+ public:
+ ConformanceRequestSetting(
+ ConformanceLevel level,
+ conformance::WireFormat input_format,
+ conformance::WireFormat output_format,
+ conformance::TestCategory test_category,
+ const Message& prototype_message,
+ const string& test_name, const string& input);
+ virtual ~ConformanceRequestSetting() {}
+
+ Message* GetTestMessage() const;
+
+ string GetTestName() const;
+
+ const conformance::ConformanceRequest& GetRequest() const {
+ return request_;
+ }
+
+ const ConformanceLevel GetLevel() const {
+ return level_;
+ }
+
+ string ConformanceLevelToString(ConformanceLevel level) const;
+
+ protected:
+ virtual string InputFormatString(conformance::WireFormat format) const;
+ virtual string OutputFormatString(conformance::WireFormat format) const;
+
+ private:
+ ConformanceLevel level_;
+ ::conformance::WireFormat input_format_;
+ ::conformance::WireFormat output_format_;
+ const Message& prototype_message_;
+ string test_name_;
+ conformance::ConformanceRequest request_;
+ };
+
+ bool CheckSetEmpty(const std::set<string>& set_to_check,
+ const std::string& write_to_file, const std::string& msg);
void ReportSuccess(const std::string& test_name);
void ReportFailure(const string& test_name,
@@ -157,80 +259,18 @@ class ConformanceTestSuite {
void ReportSkip(const string& test_name,
const conformance::ConformanceRequest& request,
const conformance::ConformanceResponse& response);
+
+ void RunValidInputTest(const ConformanceRequestSetting& setting,
+ const string& equivalent_text_format);
+ void RunValidBinaryInputTest(const ConformanceRequestSetting& setting,
+ const string& equivalent_wire_format);
+
void RunTest(const std::string& test_name,
const conformance::ConformanceRequest& request,
conformance::ConformanceResponse* response);
- void RunValidInputTest(const string& test_name,
- ConformanceLevel level,
- const string& input,
- conformance::WireFormat input_format,
- const string& equivalent_text_format,
- 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,
- const string& equivalent_text_format);
- void RunValidJsonTestWithProtobufInput(
- const string& test_name,
- ConformanceLevel level,
- 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,
- 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 Message *input,
- const string& equivalent_text_format,
- bool isProto3);
-
- typedef std::function<bool(const Json::Value&)> Validator;
- void RunValidJsonTestWithValidator(const string& test_name,
- ConformanceLevel level,
- const string& input_json,
- const Validator& validator);
- void ExpectParseFailureForJson(const string& test_name,
- ConformanceLevel level,
- const string& input_json);
- 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);
- void ExpectHardParseFailureForProto(const std::string& proto,
- 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 std::set<string>& set_to_check,
- const std::string& write_to_file, const std::string& msg);
+
+ virtual void RunSuiteImpl() = 0;
+
ConformanceTestRunner* runner_;
int successes_;
int expected_failures_;
@@ -256,7 +296,8 @@ class ConformanceTestSuite {
// The set of tests that the testee opted out of;
std::set<std::string> skipped_;
- std::unique_ptr<google::protobuf::util::TypeResolver> type_resolver_;
+ std::unique_ptr<google::protobuf::util::TypeResolver>
+ type_resolver_;
std::string type_url_;
};
diff --git a/conformance/conformance_test_impl.cc b/conformance/conformance_test_impl.cc
new file mode 100644
index 00000000..a884deaa
--- /dev/null
+++ b/conformance/conformance_test_impl.cc
@@ -0,0 +1,2367 @@
+// 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 "conformance_test.h"
+#include "third_party/jsoncpp/json.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/strutil.h>
+#include <google/protobuf/text_format.h>
+#include <google/protobuf/util/type_resolver_util.h>
+#include <google/protobuf/wire_format_lite.h>
+
+using conformance::ConformanceRequest;
+using conformance::ConformanceResponse;
+using google::protobuf::Descriptor;
+using google::protobuf::FieldDescriptor;
+using google::protobuf::Message;
+using google::protobuf::internal::WireFormatLite;
+using google::protobuf::TextFormat;
+using google::protobuf::util::NewTypeResolverForDescriptorPool;
+using protobuf_test_messages::proto3::TestAllTypesProto3;
+using protobuf_test_messages::proto2::TestAllTypesProto2;
+using std::string;
+
+namespace {
+
+static const char kTypeUrlPrefix[] = "type.googleapis.com";
+
+static string GetTypeUrl(const Descriptor* message) {
+ return string(kTypeUrlPrefix) + "/" + message->full_name();
+}
+
+/* Routines for building arbitrary protos *************************************/
+
+// We would use CodedOutputStream except that we want more freedom to build
+// arbitrary protos (even invalid ones).
+
+const string empty;
+
+string cat(const string& a, const string& b,
+ const string& c = empty,
+ const string& d = empty,
+ const string& e = empty,
+ const string& f = empty,
+ const string& g = empty,
+ const string& h = empty,
+ const string& i = empty,
+ const string& j = empty,
+ const string& k = empty,
+ const string& l = empty) {
+ string ret;
+ ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
+ g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
+ ret.append(a);
+ ret.append(b);
+ ret.append(c);
+ ret.append(d);
+ ret.append(e);
+ ret.append(f);
+ ret.append(g);
+ ret.append(h);
+ ret.append(i);
+ ret.append(j);
+ ret.append(k);
+ ret.append(l);
+ return ret;
+}
+
+// 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, 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 || 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;
+}
+
+string varint(uint64_t x) {
+ char buf[VARINT_MAX_LEN];
+ 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);
+}
+
+// TODO: proper byte-swapping for big-endian machines.
+string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
+string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
+
+string delim(const string& buf) { return cat(varint(buf.size()), buf); }
+string u32(uint32_t u32) { return fixed32(&u32); }
+string u64(uint64_t u64) { return fixed64(&u64); }
+string flt(float f) { return fixed32(&f); }
+string dbl(double d) { return fixed64(&d); }
+string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
+string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
+
+string tag(uint32_t fieldnum, char wire_type) {
+ return varint((fieldnum << 3) | wire_type);
+}
+
+string submsg(uint32_t fn, const string& buf) {
+ return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
+}
+
+#define UNKNOWN_FIELD 666
+
+const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
+ bool repeated, bool is_proto3) {
+
+ const Descriptor* d = is_proto3 ?
+ 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) {
+ return f;
+ }
+ }
+ GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
+ return nullptr;
+}
+
+string UpperCase(string str) {
+ for (int i = 0; i < str.size(); i++) {
+ str[i] = toupper(str[i]);
+ }
+ return str;
+}
+
+std::unique_ptr<Message> NewTestMessage(bool is_proto3) {
+ std::unique_ptr<Message> prototype;
+ if (is_proto3) {
+ prototype.reset(new TestAllTypesProto3());
+ } else {
+ prototype.reset(new TestAllTypesProto2());
+ }
+ return prototype;
+}
+
+} // anonymous namespace
+
+namespace google {
+namespace protobuf {
+
+class ConformanceTestSuiteImpl : public ConformanceTestSuite {
+ public:
+ ConformanceTestSuiteImpl() {}
+
+ private:
+ void RunSuiteImpl();
+ void RunValidJsonTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input_json,
+ const string& equivalent_text_format);
+ void RunValidJsonTestWithProtobufInput(
+ const string& test_name,
+ ConformanceLevel level,
+ const protobuf_test_messages::proto3::TestAllTypesProto3& input,
+ const string& equivalent_text_format);
+ void RunValidJsonIgnoreUnknownTest(
+ const string& test_name, ConformanceLevel level, const string& input_json,
+ const string& equivalent_text_format);
+ void RunValidProtobufTest(const string& test_name, ConformanceLevel level,
+ const string& input_protobuf,
+ const string& equivalent_text_format,
+ bool is_proto3);
+ void RunValidBinaryProtobufTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input_protobuf,
+ bool is_proto3);
+ void RunValidProtobufTestWithMessage(
+ const string& test_name, ConformanceLevel level,
+ const Message *input,
+ const string& equivalent_text_format,
+ bool is_proto3);
+
+ typedef std::function<bool(const Json::Value&)> Validator;
+ void RunValidJsonTestWithValidator(const string& test_name,
+ ConformanceLevel level,
+ const string& input_json,
+ const Validator& validator);
+ void ExpectParseFailureForJson(const string& test_name,
+ ConformanceLevel level,
+ const string& input_json);
+ void ExpectSerializeFailureForJson(const string& test_name,
+ ConformanceLevel level,
+ const string& text_format);
+ void ExpectParseFailureForProtoWithProtoVersion (const string& proto,
+ const string& test_name,
+ ConformanceLevel level,
+ bool is_proto3);
+ void ExpectParseFailureForProto(const std::string& proto,
+ const std::string& test_name,
+ ConformanceLevel level);
+ void ExpectHardParseFailureForProto(const std::string& proto,
+ const std::string& test_name,
+ ConformanceLevel level);
+ void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type);
+ void TestIllegalTags();
+ template <class MessageType>
+ void TestOneofMessage (MessageType &message,
+ bool is_proto3);
+ template <class MessageType>
+ void TestUnknownMessage (MessageType &message,
+ bool is_proto3);
+ void TestValidDataForType(
+ google::protobuf::FieldDescriptor::Type,
+ std::vector<std::pair<std::string, std::string>> values);
+};
+
+void ConformanceTestSuiteImpl::ExpectParseFailureForProtoWithProtoVersion (
+ const string& proto, const string& test_name, ConformanceLevel level,
+ bool is_proto3) {
+ std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
+ // 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.
+ ConformanceRequestSetting setting(
+ level, conformance::PROTOBUF, conformance::PROTOBUF,
+ conformance::BINARY_TEST,
+ *prototype, test_name, proto);
+
+ const ConformanceRequest& request = setting.GetRequest();
+ ConformanceResponse response;
+ string effective_test_name =
+ StrCat(setting.ConformanceLevelToString(level),
+ (is_proto3 ? ".Proto3" : ".Proto2"),
+ ".ProtobufInput.", test_name);
+
+ RunTest(effective_test_name, request, &response);
+ if (response.result_case() == ConformanceResponse::kParseError) {
+ ReportSuccess(effective_test_name);
+ } else if (response.result_case() == ConformanceResponse::kSkipped) {
+ ReportSkip(effective_test_name, request, response);
+ } else {
+ ReportFailure(effective_test_name, level, request, response,
+ "Should have failed to parse, but didn't.");
+ }
+}
+
+// Expect that this precise protobuf will cause a parse error.
+void ConformanceTestSuiteImpl::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.
+//
+// TODO(haberman): implement the second of these.
+void ConformanceTestSuiteImpl::ExpectHardParseFailureForProto(
+ const string& proto, const string& test_name, ConformanceLevel level) {
+ return ExpectParseFailureForProto(proto, test_name, level);
+}
+
+void ConformanceTestSuiteImpl::RunValidJsonTest(
+ const string& test_name, ConformanceLevel level, const string& input_json,
+ const string& equivalent_text_format) {
+ TestAllTypesProto3 prototype;
+ ConformanceRequestSetting setting1(
+ level, conformance::JSON, conformance::PROTOBUF,
+ conformance::JSON_TEST,
+ prototype, test_name, input_json);
+ RunValidInputTest(setting1, equivalent_text_format);
+ ConformanceRequestSetting setting2(
+ level, conformance::JSON, conformance::JSON,
+ conformance::JSON_TEST,
+ prototype, test_name, input_json);
+ RunValidInputTest(setting2, equivalent_text_format);
+}
+
+void ConformanceTestSuiteImpl::RunValidJsonTestWithProtobufInput(
+ const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
+ const string& equivalent_text_format) {
+ ConformanceRequestSetting setting(
+ level, conformance::PROTOBUF, conformance::JSON,
+ conformance::JSON_TEST,
+ input, test_name, input.SerializeAsString());
+ RunValidInputTest(setting, equivalent_text_format);
+}
+
+void ConformanceTestSuiteImpl::RunValidJsonIgnoreUnknownTest(
+ const string& test_name, ConformanceLevel level, const string& input_json,
+ const string& equivalent_text_format) {
+ TestAllTypesProto3 prototype;
+ ConformanceRequestSetting setting(
+ level, conformance::JSON, conformance::PROTOBUF,
+ conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST,
+ prototype, test_name, input_json);
+ RunValidInputTest(setting, equivalent_text_format);
+}
+
+void ConformanceTestSuiteImpl::RunValidProtobufTest(
+ const string& test_name, ConformanceLevel level,
+ const string& input_protobuf, const string& equivalent_text_format,
+ bool is_proto3) {
+ std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
+
+ ConformanceRequestSetting setting1(
+ level, conformance::PROTOBUF, conformance::PROTOBUF,
+ conformance::BINARY_TEST,
+ *prototype, test_name, input_protobuf);
+ RunValidInputTest(setting1, equivalent_text_format);
+
+ if (is_proto3) {
+ ConformanceRequestSetting setting2(
+ level, conformance::PROTOBUF, conformance::JSON,
+ conformance::BINARY_TEST,
+ *prototype, test_name, input_protobuf);
+ RunValidInputTest(setting2, equivalent_text_format);
+ }
+}
+
+void ConformanceTestSuiteImpl::RunValidBinaryProtobufTest(
+ const string& test_name, ConformanceLevel level,
+ const string& input_protobuf, bool is_proto3) {
+ std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
+ ConformanceRequestSetting setting(
+ level, conformance::PROTOBUF, conformance::PROTOBUF,
+ conformance::BINARY_TEST,
+ *prototype, test_name, input_protobuf);
+ RunValidBinaryInputTest(setting, input_protobuf);
+}
+
+void ConformanceTestSuiteImpl::RunValidProtobufTestWithMessage(
+ const string& test_name, ConformanceLevel level, const Message *input,
+ const string& equivalent_text_format, bool is_proto3) {
+ RunValidProtobufTest(test_name, level, input->SerializeAsString(),
+ equivalent_text_format, is_proto3);
+}
+
+// According to proto3 JSON specification, JSON serializers follow more strict
+// rules than parsers (e.g., a serializer must serialize int32 values as JSON
+// numbers while the parser is allowed to accept them as JSON strings). This
+// method allows strict checking on a proto3 JSON serializer by inspecting
+// the JSON output directly.
+void ConformanceTestSuiteImpl::RunValidJsonTestWithValidator(
+ const string& test_name, ConformanceLevel level, const string& input_json,
+ const Validator& validator) {
+ TestAllTypesProto3 prototype;
+ ConformanceRequestSetting setting(
+ level, conformance::JSON, conformance::JSON,
+ conformance::JSON_TEST,
+ prototype, test_name, input_json);
+ const ConformanceRequest& request = setting.GetRequest();
+ ConformanceResponse response;
+ string effective_test_name =
+ StrCat(setting.ConformanceLevelToString(level),
+ ".Proto3.JsonInput.",
+ test_name, ".Validator");
+
+ RunTest(effective_test_name, request, &response);
+
+ if (response.result_case() == ConformanceResponse::kSkipped) {
+ ReportSkip(effective_test_name, request, response);
+ return;
+ }
+
+ if (response.result_case() != ConformanceResponse::kJsonPayload) {
+ ReportFailure(effective_test_name, level, request, response,
+ "Expected JSON payload but got type %d.",
+ response.result_case());
+ return;
+ }
+ Json::Reader reader;
+ Json::Value value;
+ if (!reader.parse(response.json_payload(), value)) {
+ ReportFailure(effective_test_name, level, request, response,
+ "JSON payload cannot be parsed as valid JSON: %s",
+ reader.getFormattedErrorMessages().c_str());
+ return;
+ }
+ if (!validator(value)) {
+ ReportFailure(effective_test_name, level, request, response,
+ "JSON payload validation failed.");
+ return;
+ }
+ ReportSuccess(effective_test_name);
+}
+
+void ConformanceTestSuiteImpl::ExpectParseFailureForJson(
+ const string& test_name, ConformanceLevel level, const string& input_json) {
+ TestAllTypesProto3 prototype;
+ // 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.
+ ConformanceRequestSetting setting(
+ level, conformance::JSON, conformance::JSON,
+ conformance::JSON_TEST,
+ prototype, test_name, input_json);
+ const ConformanceRequest& request = setting.GetRequest();
+ ConformanceResponse response;
+ string effective_test_name =
+ StrCat(setting.ConformanceLevelToString(level),
+ ".Proto3.JsonInput.", test_name);
+
+ RunTest(effective_test_name, request, &response);
+ if (response.result_case() == ConformanceResponse::kParseError) {
+ ReportSuccess(effective_test_name);
+ } else if (response.result_case() == ConformanceResponse::kSkipped) {
+ ReportSkip(effective_test_name, request, response);
+ } else {
+ ReportFailure(effective_test_name, level, request, response,
+ "Should have failed to parse, but didn't.");
+ }
+}
+
+void ConformanceTestSuiteImpl::ExpectSerializeFailureForJson(
+ const string& test_name, ConformanceLevel level, const string& text_format) {
+ TestAllTypesProto3 payload_message;
+ GOOGLE_CHECK(
+ TextFormat::ParseFromString(text_format, &payload_message))
+ << "Failed to parse: " << text_format;
+
+ TestAllTypesProto3 prototype;
+ ConformanceRequestSetting setting(
+ level, conformance::PROTOBUF, conformance::JSON,
+ conformance::JSON_TEST,
+ prototype, test_name, payload_message.SerializeAsString());
+ const ConformanceRequest& request = setting.GetRequest();
+ ConformanceResponse response;
+ string effective_test_name =
+ StrCat(setting.ConformanceLevelToString(level),
+ ".", test_name, ".JsonOutput");
+
+ RunTest(effective_test_name, request, &response);
+ if (response.result_case() == ConformanceResponse::kSerializeError) {
+ ReportSuccess(effective_test_name);
+ } else if (response.result_case() == ConformanceResponse::kSkipped) {
+ ReportSkip(effective_test_name, request, response);
+ } else {
+ ReportFailure(effective_test_name, level, request, response,
+ "Should have failed to serialize, but didn't.");
+ }
+}
+
+//TODO: proto2?
+void ConformanceTestSuiteImpl::TestPrematureEOFForType(
+ FieldDescriptor::Type type) {
+ // Incomplete values for each wire type.
+ static const string incompletes[6] = {
+ string("\x80"), // VARINT
+ string("abcdefg"), // 64BIT
+ string("\x80"), // DELIMITED (partial length)
+ string(), // START_GROUP (no value required)
+ string(), // END_GROUP (no value required)
+ string("abc") // 32BIT
+ };
+
+ 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];
+ const string type_name =
+ UpperCase(string(".") + FieldDescriptor::TypeName(type));
+
+ ExpectParseFailureForProto(
+ tag(field->number(), wire_type),
+ "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
+
+ ExpectParseFailureForProto(
+ tag(rep_field->number(), wire_type),
+ "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
+
+ ExpectParseFailureForProto(
+ tag(UNKNOWN_FIELD, wire_type),
+ "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
+
+ ExpectParseFailureForProto(
+ cat( tag(field->number(), wire_type), incomplete ),
+ "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
+
+ ExpectParseFailureForProto(
+ cat( tag(rep_field->number(), wire_type), incomplete ),
+ "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
+
+ ExpectParseFailureForProto(
+ cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
+ "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
+
+ if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
+ ExpectParseFailureForProto(
+ cat( tag(field->number(), wire_type), varint(1) ),
+ "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
+ REQUIRED);
+
+ ExpectParseFailureForProto(
+ cat( tag(rep_field->number(), wire_type), varint(1) ),
+ "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
+ REQUIRED);
+
+ // EOF in the middle of delimited data for unknown value.
+ ExpectParseFailureForProto(
+ cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
+ "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
+
+ if (type == FieldDescriptor::TYPE_MESSAGE) {
+ // Submessage ends in the middle of a value.
+ string incomplete_submsg =
+ cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
+ incompletes[WireFormatLite::WIRETYPE_VARINT] );
+ ExpectHardParseFailureForProto(
+ cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
+ varint(incomplete_submsg.size()),
+ incomplete_submsg ),
+ "PrematureEofInSubmessageValue" + type_name, REQUIRED);
+ }
+ } else if (type != FieldDescriptor::TYPE_GROUP) {
+ // Non-delimited, non-group: eligible for packing.
+
+ // Packed region ends in the middle of a value.
+ ExpectHardParseFailureForProto(
+ cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
+ varint(incomplete.size()), incomplete),
+ "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
+
+ // EOF in the middle of packed region.
+ ExpectParseFailureForProto(
+ cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
+ varint(1)),
+ "PrematureEofInPackedField" + type_name, REQUIRED);
+ }
+}
+
+void ConformanceTestSuiteImpl::TestValidDataForType(
+ FieldDescriptor::Type type,
+ std::vector<std::pair<std::string, std::string>> values) {
+ for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
+ 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, is_proto3);
+ const FieldDescriptor* rep_field = GetFieldForType(type, true, is_proto3);
+
+ RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED,
+ cat(tag(field->number(), wire_type), values[0].first),
+ field->name() + ": " + values[0].second, is_proto3);
+
+ 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, is_proto3);
+
+ 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 + " ";
+ }
+ RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED,
+ proto, text, is_proto3);
+ }
+}
+
+// TODO: proto2?
+void ConformanceTestSuiteImpl::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 ConformanceTestSuiteImpl::TestOneofMessage (
+ MessageType &message, bool is_proto3) {
+ message.set_oneof_uint32(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3);
+ message.mutable_oneof_nested_message()->set_a(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroMessage", RECOMMENDED, &message,
+ is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
+ is_proto3);
+ message.mutable_oneof_nested_message()->set_a(1);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroMessageSetTwice", RECOMMENDED, &message,
+ "oneof_nested_message: {a: 1}",
+ is_proto3);
+ message.set_oneof_string("");
+ RunValidProtobufTestWithMessage(
+ "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3);
+ message.set_oneof_bytes("");
+ RunValidProtobufTestWithMessage(
+ "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3);
+ message.set_oneof_bool(false);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3);
+ message.set_oneof_uint64(0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3);
+ message.set_oneof_float(0.0f);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3);
+ message.set_oneof_double(0.0);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3);
+ message.set_oneof_enum(MessageType::FOO);
+ RunValidProtobufTestWithMessage(
+ "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3);
+}
+
+template <class MessageType>
+void ConformanceTestSuiteImpl::TestUnknownMessage(
+ MessageType& message, bool is_proto3) {
+ message.ParseFromString("\xA8\x1F\x01");
+ RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
+ message.SerializeAsString(), is_proto3);
+}
+
+void ConformanceTestSuiteImpl::RunSuiteImpl() {
+ type_resolver_.reset(NewTypeResolverForDescriptorPool(
+ kTypeUrlPrefix, DescriptorPool::generated_pool()));
+ type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
+
+ for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
+ if (i == FieldDescriptor::TYPE_GROUP) continue;
+ TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
+ }
+
+ TestIllegalTags();
+
+ int64 kInt64Min = -9223372036854775808ULL;
+ int64 kInt64Max = 9223372036854775807ULL;
+ uint64 kUint64Max = 18446744073709551615ULL;
+ int32 kInt32Max = 2147483647;
+ int32 kInt32Min = -2147483648;
+ uint32 kUint32Max = 4294967295UL;
+
+ TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
+ {dbl(0.1), "0.1"},
+ {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
+ {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
+ });
+ 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"}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_INT64, {
+ {varint(12345), "12345"},
+ {varint(kInt64Max), std::to_string(kInt64Max)},
+ {varint(kInt64Min), std::to_string(kInt64Min)}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
+ {varint(12345), "12345"},
+ {varint(kUint64Max), std::to_string(kUint64Max)},
+ {varint(0), "0"}
+ });
+ 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(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"},
+ {u64(kUint64Max), std::to_string(kUint64Max)},
+ {u64(0), "0"}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
+ {u32(12345), "12345"},
+ {u32(kUint32Max), std::to_string(kUint32Max)}, // UINT32_MAX
+ {u32(0), "0"}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
+ {u64(12345), "12345"},
+ {u64(kInt64Max), std::to_string(kInt64Max)},
+ {u64(kInt64Min), std::to_string(kInt64Min)}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
+ {u32(12345), "12345"},
+ {u32(kInt32Max), std::to_string(kInt32Max)},
+ {u32(kInt32Min), std::to_string(kInt32Min)}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
+ {varint(1), "true"},
+ {varint(0), "false"},
+ {varint(12345678), "true"}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
+ {zz32(12345), "12345"},
+ {zz32(kInt32Max), std::to_string(kInt32Max)},
+ {zz32(kInt32Min), std::to_string(kInt32Min)}
+ });
+ TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
+ {zz64(12345), "12345"},
+ {zz64(kInt64Max), std::to_string(kInt64Max)},
+ {zz64(kInt64Min), std::to_string(kInt64Min)}
+ });
+
+ // TODO(haberman):
+ // TestValidDataForType(FieldDescriptor::TYPE_STRING
+ // TestValidDataForType(FieldDescriptor::TYPE_GROUP
+ // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE
+ // TestValidDataForType(FieldDescriptor::TYPE_BYTES
+ // TestValidDataForType(FieldDescriptor::TYPE_ENUM
+
+ RunValidJsonTest("HelloWorld", REQUIRED,
+ "{\"optionalString\":\"Hello, World!\"}",
+ "optional_string: 'Hello, World!'");
+
+ // NOTE: The spec for JSON support is still being sorted out, these may not
+ // all be correct.
+ // Test field name conventions.
+ RunValidJsonTest(
+ "FieldNameInSnakeCase", REQUIRED,
+ R"({
+ "fieldname1": 1,
+ "fieldName2": 2,
+ "FieldName3": 3,
+ "fieldName4": 4
+ })",
+ R"(
+ fieldname1: 1
+ field_name2: 2
+ _field_name3: 3
+ field__name4_: 4
+ )");
+ RunValidJsonTest(
+ "FieldNameWithNumbers", REQUIRED,
+ R"({
+ "field0name5": 5,
+ "field0Name6": 6
+ })",
+ R"(
+ field0name5: 5
+ field_0_name6: 6
+ )");
+ RunValidJsonTest(
+ "FieldNameWithMixedCases", REQUIRED,
+ R"({
+ "fieldName7": 7,
+ "FieldName8": 8,
+ "fieldName9": 9,
+ "FieldName10": 10,
+ "FIELDNAME11": 11,
+ "FIELDName12": 12
+ })",
+ R"(
+ fieldName7: 7
+ FieldName8: 8
+ field_Name9: 9
+ Field_Name10: 10
+ FIELD_NAME11: 11
+ FIELD_name12: 12
+ )");
+ RunValidJsonTest(
+ "FieldNameWithDoubleUnderscores", RECOMMENDED,
+ R"({
+ "FieldName13": 13,
+ "FieldName14": 14,
+ "fieldName15": 15,
+ "fieldName16": 16,
+ "fieldName17": 17,
+ "FieldName18": 18
+ })",
+ R"(
+ __field_name13: 13
+ __Field_name14: 14
+ field__name15: 15
+ field__Name16: 16
+ field_name17__: 17
+ Field_name18__: 18
+ )");
+ // Using the original proto field name in JSON is also allowed.
+ RunValidJsonTest(
+ "OriginalProtoFieldName", REQUIRED,
+ R"({
+ "fieldname1": 1,
+ "field_name2": 2,
+ "_field_name3": 3,
+ "field__name4_": 4,
+ "field0name5": 5,
+ "field_0_name6": 6,
+ "fieldName7": 7,
+ "FieldName8": 8,
+ "field_Name9": 9,
+ "Field_Name10": 10,
+ "FIELD_NAME11": 11,
+ "FIELD_name12": 12,
+ "__field_name13": 13,
+ "__Field_name14": 14,
+ "field__name15": 15,
+ "field__Name16": 16,
+ "field_name17__": 17,
+ "Field_name18__": 18
+ })",
+ R"(
+ fieldname1: 1
+ field_name2: 2
+ _field_name3: 3
+ field__name4_: 4
+ field0name5: 5
+ field_0_name6: 6
+ fieldName7: 7
+ FieldName8: 8
+ field_Name9: 9
+ Field_Name10: 10
+ FIELD_NAME11: 11
+ FIELD_name12: 12
+ __field_name13: 13
+ __Field_name14: 14
+ field__name15: 15
+ field__Name16: 16
+ field_name17__: 17
+ Field_name18__: 18
+ )");
+ // Field names can be escaped.
+ RunValidJsonTest(
+ "FieldNameEscaped", REQUIRED,
+ R"({"fieldn\u0061me1": 1})",
+ "fieldname1: 1");
+ // String ends with escape character.
+ ExpectParseFailureForJson(
+ "StringEndsWithEscapeChar", RECOMMENDED,
+ "{\"optionalString\": \"abc\\");
+ // Field names must be quoted (or it's not valid JSON).
+ ExpectParseFailureForJson(
+ "FieldNameNotQuoted", RECOMMENDED,
+ "{fieldname1: 1}");
+ // Trailing comma is not allowed (not valid JSON).
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObject", RECOMMENDED,
+ R"({"fieldname1":1,})");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
+ R"({"fieldname1":1 ,})");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
+ R"({"fieldname1":1 , })");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
+ R"({
+ "fieldname1":1,
+ })");
+ // JSON doesn't support comments.
+ ExpectParseFailureForJson(
+ "JsonWithComments", RECOMMENDED,
+ R"({
+ // This is a comment.
+ "fieldname1": 1
+ })");
+ // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
+ RunValidJsonTest(
+ "OneLineNoSpaces", RECOMMENDED,
+ "{\"optionalInt32\":1,\"optionalInt64\":2}",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "OneLineWithSpaces", RECOMMENDED,
+ "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "MultilineNoSpaces", RECOMMENDED,
+ "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "MultilineWithSpaces", RECOMMENDED,
+ "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ // Missing comma between key/value pairs.
+ ExpectParseFailureForJson(
+ "MissingCommaOneLine", RECOMMENDED,
+ "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
+ ExpectParseFailureForJson(
+ "MissingCommaMultiline", RECOMMENDED,
+ "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
+ // Duplicated field names are not allowed.
+ ExpectParseFailureForJson(
+ "FieldNameDuplicate", RECOMMENDED,
+ R"({
+ "optionalNestedMessage": {a: 1},
+ "optionalNestedMessage": {}
+ })");
+ ExpectParseFailureForJson(
+ "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
+ R"({
+ "optional_nested_message": {a: 1},
+ "optionalNestedMessage": {}
+ })");
+ ExpectParseFailureForJson(
+ "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
+ R"({
+ "optionalNestedMessage": {a: 1},
+ "optional_nested_message": {}
+ })");
+ // Serializers should use lowerCamelCase by default.
+ RunValidJsonTestWithValidator(
+ "FieldNameInLowerCamelCase", REQUIRED,
+ R"({
+ "fieldname1": 1,
+ "fieldName2": 2,
+ "FieldName3": 3,
+ "fieldName4": 4
+ })",
+ [](const Json::Value& value) {
+ return value.isMember("fieldname1") &&
+ value.isMember("fieldName2") &&
+ value.isMember("FieldName3") &&
+ value.isMember("fieldName4");
+ });
+ RunValidJsonTestWithValidator(
+ "FieldNameWithNumbers", REQUIRED,
+ R"({
+ "field0name5": 5,
+ "field0Name6": 6
+ })",
+ [](const Json::Value& value) {
+ return value.isMember("field0name5") &&
+ value.isMember("field0Name6");
+ });
+ RunValidJsonTestWithValidator(
+ "FieldNameWithMixedCases", REQUIRED,
+ R"({
+ "fieldName7": 7,
+ "FieldName8": 8,
+ "fieldName9": 9,
+ "FieldName10": 10,
+ "FIELDNAME11": 11,
+ "FIELDName12": 12
+ })",
+ [](const Json::Value& value) {
+ return value.isMember("fieldName7") &&
+ value.isMember("FieldName8") &&
+ value.isMember("fieldName9") &&
+ value.isMember("FieldName10") &&
+ value.isMember("FIELDNAME11") &&
+ value.isMember("FIELDName12");
+ });
+ RunValidJsonTestWithValidator(
+ "FieldNameWithDoubleUnderscores", RECOMMENDED,
+ R"({
+ "FieldName13": 13,
+ "FieldName14": 14,
+ "fieldName15": 15,
+ "fieldName16": 16,
+ "fieldName17": 17,
+ "FieldName18": 18
+ })",
+ [](const Json::Value& value) {
+ return value.isMember("FieldName13") &&
+ value.isMember("FieldName14") &&
+ value.isMember("fieldName15") &&
+ value.isMember("fieldName16") &&
+ value.isMember("fieldName17") &&
+ value.isMember("FieldName18");
+ });
+
+ // Integer fields.
+ RunValidJsonTest(
+ "Int32FieldMaxValue", REQUIRED,
+ R"({"optionalInt32": 2147483647})",
+ "optional_int32: 2147483647");
+ RunValidJsonTest(
+ "Int32FieldMinValue", REQUIRED,
+ R"({"optionalInt32": -2147483648})",
+ "optional_int32: -2147483648");
+ RunValidJsonTest(
+ "Uint32FieldMaxValue", REQUIRED,
+ R"({"optionalUint32": 4294967295})",
+ "optional_uint32: 4294967295");
+ RunValidJsonTest(
+ "Int64FieldMaxValue", REQUIRED,
+ R"({"optionalInt64": "9223372036854775807"})",
+ "optional_int64: 9223372036854775807");
+ RunValidJsonTest(
+ "Int64FieldMinValue", REQUIRED,
+ R"({"optionalInt64": "-9223372036854775808"})",
+ "optional_int64: -9223372036854775808");
+ RunValidJsonTest(
+ "Uint64FieldMaxValue", REQUIRED,
+ R"({"optionalUint64": "18446744073709551615"})",
+ "optional_uint64: 18446744073709551615");
+ // While not the largest Int64, this is the largest
+ // Int64 which can be exactly represented within an
+ // IEEE-754 64-bit float, which is the expected level
+ // of interoperability guarantee. Larger values may
+ // work in some implementations, but should not be
+ // relied upon.
+ RunValidJsonTest(
+ "Int64FieldMaxValueNotQuoted", REQUIRED,
+ R"({"optionalInt64": 9223372036854774784})",
+ "optional_int64: 9223372036854774784");
+ RunValidJsonTest(
+ "Int64FieldMinValueNotQuoted", REQUIRED,
+ R"({"optionalInt64": -9223372036854775808})",
+ "optional_int64: -9223372036854775808");
+ // Largest interoperable Uint64; see comment above
+ // for Int64FieldMaxValueNotQuoted.
+ RunValidJsonTest(
+ "Uint64FieldMaxValueNotQuoted", REQUIRED,
+ R"({"optionalUint64": 18446744073709549568})",
+ "optional_uint64: 18446744073709549568");
+ // Values can be represented as JSON strings.
+ RunValidJsonTest(
+ "Int32FieldStringValue", REQUIRED,
+ R"({"optionalInt32": "2147483647"})",
+ "optional_int32: 2147483647");
+ RunValidJsonTest(
+ "Int32FieldStringValueEscaped", REQUIRED,
+ R"({"optionalInt32": "2\u003147483647"})",
+ "optional_int32: 2147483647");
+
+ // Parsers reject out-of-bound integer values.
+ ExpectParseFailureForJson(
+ "Int32FieldTooLarge", REQUIRED,
+ R"({"optionalInt32": 2147483648})");
+ ExpectParseFailureForJson(
+ "Int32FieldTooSmall", REQUIRED,
+ R"({"optionalInt32": -2147483649})");
+ ExpectParseFailureForJson(
+ "Uint32FieldTooLarge", REQUIRED,
+ R"({"optionalUint32": 4294967296})");
+ ExpectParseFailureForJson(
+ "Int64FieldTooLarge", REQUIRED,
+ R"({"optionalInt64": "9223372036854775808"})");
+ ExpectParseFailureForJson(
+ "Int64FieldTooSmall", REQUIRED,
+ R"({"optionalInt64": "-9223372036854775809"})");
+ ExpectParseFailureForJson(
+ "Uint64FieldTooLarge", REQUIRED,
+ R"({"optionalUint64": "18446744073709551616"})");
+ // Parser reject non-integer numeric values as well.
+ ExpectParseFailureForJson(
+ "Int32FieldNotInteger", REQUIRED,
+ R"({"optionalInt32": 0.5})");
+ ExpectParseFailureForJson(
+ "Uint32FieldNotInteger", REQUIRED,
+ R"({"optionalUint32": 0.5})");
+ ExpectParseFailureForJson(
+ "Int64FieldNotInteger", REQUIRED,
+ R"({"optionalInt64": "0.5"})");
+ ExpectParseFailureForJson(
+ "Uint64FieldNotInteger", REQUIRED,
+ R"({"optionalUint64": "0.5"})");
+
+ // Integers but represented as float values are accepted.
+ RunValidJsonTest(
+ "Int32FieldFloatTrailingZero", REQUIRED,
+ R"({"optionalInt32": 100000.000})",
+ "optional_int32: 100000");
+ RunValidJsonTest(
+ "Int32FieldExponentialFormat", REQUIRED,
+ R"({"optionalInt32": 1e5})",
+ "optional_int32: 100000");
+ RunValidJsonTest(
+ "Int32FieldMaxFloatValue", REQUIRED,
+ R"({"optionalInt32": 2.147483647e9})",
+ "optional_int32: 2147483647");
+ RunValidJsonTest(
+ "Int32FieldMinFloatValue", REQUIRED,
+ R"({"optionalInt32": -2.147483648e9})",
+ "optional_int32: -2147483648");
+ RunValidJsonTest(
+ "Uint32FieldMaxFloatValue", REQUIRED,
+ R"({"optionalUint32": 4.294967295e9})",
+ "optional_uint32: 4294967295");
+
+ // Parser reject non-numeric values.
+ ExpectParseFailureForJson(
+ "Int32FieldNotNumber", REQUIRED,
+ R"({"optionalInt32": "3x3"})");
+ ExpectParseFailureForJson(
+ "Uint32FieldNotNumber", REQUIRED,
+ R"({"optionalUint32": "3x3"})");
+ ExpectParseFailureForJson(
+ "Int64FieldNotNumber", REQUIRED,
+ R"({"optionalInt64": "3x3"})");
+ ExpectParseFailureForJson(
+ "Uint64FieldNotNumber", REQUIRED,
+ R"({"optionalUint64": "3x3"})");
+ // JSON does not allow "+" on numric values.
+ ExpectParseFailureForJson(
+ "Int32FieldPlusSign", REQUIRED,
+ R"({"optionalInt32": +1})");
+ // JSON doesn't allow leading 0s.
+ ExpectParseFailureForJson(
+ "Int32FieldLeadingZero", REQUIRED,
+ R"({"optionalInt32": 01})");
+ ExpectParseFailureForJson(
+ "Int32FieldNegativeWithLeadingZero", REQUIRED,
+ R"({"optionalInt32": -01})");
+ // String values must follow the same syntax rule. Specifically leading
+ // or trailing spaces are not allowed.
+ ExpectParseFailureForJson(
+ "Int32FieldLeadingSpace", REQUIRED,
+ R"({"optionalInt32": " 1"})");
+ ExpectParseFailureForJson(
+ "Int32FieldTrailingSpace", REQUIRED,
+ R"({"optionalInt32": "1 "})");
+
+ // 64-bit values are serialized as strings.
+ RunValidJsonTestWithValidator(
+ "Int64FieldBeString", RECOMMENDED,
+ R"({"optionalInt64": 1})",
+ [](const Json::Value& value) {
+ return value["optionalInt64"].type() == Json::stringValue &&
+ value["optionalInt64"].asString() == "1";
+ });
+ RunValidJsonTestWithValidator(
+ "Uint64FieldBeString", RECOMMENDED,
+ R"({"optionalUint64": 1})",
+ [](const Json::Value& value) {
+ return value["optionalUint64"].type() == Json::stringValue &&
+ value["optionalUint64"].asString() == "1";
+ });
+
+ // Bool fields.
+ RunValidJsonTest(
+ "BoolFieldTrue", REQUIRED,
+ R"({"optionalBool":true})",
+ "optional_bool: true");
+ RunValidJsonTest(
+ "BoolFieldFalse", REQUIRED,
+ R"({"optionalBool":false})",
+ "optional_bool: false");
+
+ // Other forms are not allowed.
+ ExpectParseFailureForJson(
+ "BoolFieldIntegerZero", RECOMMENDED,
+ R"({"optionalBool":0})");
+ ExpectParseFailureForJson(
+ "BoolFieldIntegerOne", RECOMMENDED,
+ R"({"optionalBool":1})");
+ ExpectParseFailureForJson(
+ "BoolFieldCamelCaseTrue", RECOMMENDED,
+ R"({"optionalBool":True})");
+ ExpectParseFailureForJson(
+ "BoolFieldCamelCaseFalse", RECOMMENDED,
+ R"({"optionalBool":False})");
+ ExpectParseFailureForJson(
+ "BoolFieldAllCapitalTrue", RECOMMENDED,
+ R"({"optionalBool":TRUE})");
+ ExpectParseFailureForJson(
+ "BoolFieldAllCapitalFalse", RECOMMENDED,
+ R"({"optionalBool":FALSE})");
+ ExpectParseFailureForJson(
+ "BoolFieldDoubleQuotedTrue", RECOMMENDED,
+ R"({"optionalBool":"true"})");
+ ExpectParseFailureForJson(
+ "BoolFieldDoubleQuotedFalse", RECOMMENDED,
+ R"({"optionalBool":"false"})");
+
+ // Float fields.
+ RunValidJsonTest(
+ "FloatFieldMinPositiveValue", REQUIRED,
+ R"({"optionalFloat": 1.175494e-38})",
+ "optional_float: 1.175494e-38");
+ RunValidJsonTest(
+ "FloatFieldMaxNegativeValue", REQUIRED,
+ R"({"optionalFloat": -1.175494e-38})",
+ "optional_float: -1.175494e-38");
+ RunValidJsonTest(
+ "FloatFieldMaxPositiveValue", REQUIRED,
+ R"({"optionalFloat": 3.402823e+38})",
+ "optional_float: 3.402823e+38");
+ RunValidJsonTest(
+ "FloatFieldMinNegativeValue", REQUIRED,
+ R"({"optionalFloat": 3.402823e+38})",
+ "optional_float: 3.402823e+38");
+ // Values can be quoted.
+ RunValidJsonTest(
+ "FloatFieldQuotedValue", REQUIRED,
+ R"({"optionalFloat": "1"})",
+ "optional_float: 1");
+ // Special values.
+ RunValidJsonTest(
+ "FloatFieldNan", REQUIRED,
+ R"({"optionalFloat": "NaN"})",
+ "optional_float: nan");
+ RunValidJsonTest(
+ "FloatFieldInfinity", REQUIRED,
+ R"({"optionalFloat": "Infinity"})",
+ "optional_float: inf");
+ RunValidJsonTest(
+ "FloatFieldNegativeInfinity", REQUIRED,
+ R"({"optionalFloat": "-Infinity"})",
+ "optional_float: -inf");
+ // Non-cannonical Nan will be correctly normalized.
+ {
+ TestAllTypesProto3 message;
+ // IEEE floating-point standard 32-bit quiet NaN:
+ // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
+ message.set_optional_float(
+ WireFormatLite::DecodeFloat(0x7FA12345));
+ RunValidJsonTestWithProtobufInput(
+ "FloatFieldNormalizeQuietNan", REQUIRED, message,
+ "optional_float: nan");
+ // IEEE floating-point standard 64-bit signaling NaN:
+ // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
+ message.set_optional_float(
+ WireFormatLite::DecodeFloat(0xFFB54321));
+ RunValidJsonTestWithProtobufInput(
+ "FloatFieldNormalizeSignalingNan", REQUIRED, message,
+ "optional_float: nan");
+ }
+
+ // Special values must be quoted.
+ ExpectParseFailureForJson(
+ "FloatFieldNanNotQuoted", RECOMMENDED,
+ R"({"optionalFloat": NaN})");
+ ExpectParseFailureForJson(
+ "FloatFieldInfinityNotQuoted", RECOMMENDED,
+ R"({"optionalFloat": Infinity})");
+ ExpectParseFailureForJson(
+ "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
+ R"({"optionalFloat": -Infinity})");
+ // Parsers should reject out-of-bound values.
+ ExpectParseFailureForJson(
+ "FloatFieldTooSmall", REQUIRED,
+ R"({"optionalFloat": -3.502823e+38})");
+ ExpectParseFailureForJson(
+ "FloatFieldTooLarge", REQUIRED,
+ R"({"optionalFloat": 3.502823e+38})");
+
+ // Double fields.
+ RunValidJsonTest(
+ "DoubleFieldMinPositiveValue", REQUIRED,
+ R"({"optionalDouble": 2.22507e-308})",
+ "optional_double: 2.22507e-308");
+ RunValidJsonTest(
+ "DoubleFieldMaxNegativeValue", REQUIRED,
+ R"({"optionalDouble": -2.22507e-308})",
+ "optional_double: -2.22507e-308");
+ RunValidJsonTest(
+ "DoubleFieldMaxPositiveValue", REQUIRED,
+ R"({"optionalDouble": 1.79769e+308})",
+ "optional_double: 1.79769e+308");
+ RunValidJsonTest(
+ "DoubleFieldMinNegativeValue", REQUIRED,
+ R"({"optionalDouble": -1.79769e+308})",
+ "optional_double: -1.79769e+308");
+ // Values can be quoted.
+ RunValidJsonTest(
+ "DoubleFieldQuotedValue", REQUIRED,
+ R"({"optionalDouble": "1"})",
+ "optional_double: 1");
+ // Speical values.
+ RunValidJsonTest(
+ "DoubleFieldNan", REQUIRED,
+ R"({"optionalDouble": "NaN"})",
+ "optional_double: nan");
+ RunValidJsonTest(
+ "DoubleFieldInfinity", REQUIRED,
+ R"({"optionalDouble": "Infinity"})",
+ "optional_double: inf");
+ RunValidJsonTest(
+ "DoubleFieldNegativeInfinity", REQUIRED,
+ R"({"optionalDouble": "-Infinity"})",
+ "optional_double: -inf");
+ // Non-cannonical Nan will be correctly normalized.
+ {
+ TestAllTypesProto3 message;
+ message.set_optional_double(
+ WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
+ RunValidJsonTestWithProtobufInput(
+ "DoubleFieldNormalizeQuietNan", REQUIRED, message,
+ "optional_double: nan");
+ message.set_optional_double(
+ WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
+ RunValidJsonTestWithProtobufInput(
+ "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
+ "optional_double: nan");
+ }
+
+ // Special values must be quoted.
+ ExpectParseFailureForJson(
+ "DoubleFieldNanNotQuoted", RECOMMENDED,
+ R"({"optionalDouble": NaN})");
+ ExpectParseFailureForJson(
+ "DoubleFieldInfinityNotQuoted", RECOMMENDED,
+ R"({"optionalDouble": Infinity})");
+ ExpectParseFailureForJson(
+ "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
+ R"({"optionalDouble": -Infinity})");
+
+ // Parsers should reject out-of-bound values.
+ ExpectParseFailureForJson(
+ "DoubleFieldTooSmall", REQUIRED,
+ R"({"optionalDouble": -1.89769e+308})");
+ ExpectParseFailureForJson(
+ "DoubleFieldTooLarge", REQUIRED,
+ R"({"optionalDouble": +1.89769e+308})");
+
+ // Enum fields.
+ RunValidJsonTest(
+ "EnumField", REQUIRED,
+ R"({"optionalNestedEnum": "FOO"})",
+ "optional_nested_enum: FOO");
+ // Enum values must be represented as strings.
+ ExpectParseFailureForJson(
+ "EnumFieldNotQuoted", REQUIRED,
+ R"({"optionalNestedEnum": FOO})");
+ // Numeric values are allowed.
+ RunValidJsonTest(
+ "EnumFieldNumericValueZero", REQUIRED,
+ R"({"optionalNestedEnum": 0})",
+ "optional_nested_enum: FOO");
+ RunValidJsonTest(
+ "EnumFieldNumericValueNonZero", REQUIRED,
+ R"({"optionalNestedEnum": 1})",
+ "optional_nested_enum: BAR");
+ // Unknown enum values are represented as numeric values.
+ RunValidJsonTestWithValidator(
+ "EnumFieldUnknownValue", REQUIRED,
+ R"({"optionalNestedEnum": 123})",
+ [](const Json::Value& value) {
+ return value["optionalNestedEnum"].type() == Json::intValue &&
+ value["optionalNestedEnum"].asInt() == 123;
+ });
+
+ // String fields.
+ RunValidJsonTest(
+ "StringField", REQUIRED,
+ R"({"optionalString": "Hello world!"})",
+ "optional_string: \"Hello world!\"");
+ RunValidJsonTest(
+ "StringFieldUnicode", REQUIRED,
+ // Google in Chinese.
+ R"({"optionalString": "谷歌"})",
+ R"(optional_string: "谷歌")");
+ RunValidJsonTest(
+ "StringFieldEscape", REQUIRED,
+ R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
+ R"(optional_string: "\"\\/\b\f\n\r\t")");
+ RunValidJsonTest(
+ "StringFieldUnicodeEscape", REQUIRED,
+ R"({"optionalString": "\u8C37\u6B4C"})",
+ R"(optional_string: "谷歌")");
+ RunValidJsonTest(
+ "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
+ R"({"optionalString": "\u8c37\u6b4c"})",
+ R"(optional_string: "谷歌")");
+ RunValidJsonTest(
+ "StringFieldSurrogatePair", REQUIRED,
+ // The character is an emoji: grinning face with smiling eyes. 😁
+ R"({"optionalString": "\uD83D\uDE01"})",
+ R"(optional_string: "\xF0\x9F\x98\x81")");
+
+ // Unicode escapes must start with "\u" (lowercase u).
+ ExpectParseFailureForJson(
+ "StringFieldUppercaseEscapeLetter", RECOMMENDED,
+ R"({"optionalString": "\U8C37\U6b4C"})");
+ ExpectParseFailureForJson(
+ "StringFieldInvalidEscape", RECOMMENDED,
+ R"({"optionalString": "\uXXXX\u6B4C"})");
+ ExpectParseFailureForJson(
+ "StringFieldUnterminatedEscape", RECOMMENDED,
+ R"({"optionalString": "\u8C3"})");
+ ExpectParseFailureForJson(
+ "StringFieldUnpairedHighSurrogate", RECOMMENDED,
+ R"({"optionalString": "\uD800"})");
+ ExpectParseFailureForJson(
+ "StringFieldUnpairedLowSurrogate", RECOMMENDED,
+ R"({"optionalString": "\uDC00"})");
+ ExpectParseFailureForJson(
+ "StringFieldSurrogateInWrongOrder", RECOMMENDED,
+ R"({"optionalString": "\uDE01\uD83D"})");
+ ExpectParseFailureForJson(
+ "StringFieldNotAString", REQUIRED,
+ R"({"optionalString": 12345})");
+
+ // Bytes fields.
+ RunValidJsonTest(
+ "BytesField", REQUIRED,
+ R"({"optionalBytes": "AQI="})",
+ R"(optional_bytes: "\x01\x02")");
+ RunValidJsonTest(
+ "BytesFieldBase64Url", RECOMMENDED,
+ R"({"optionalBytes": "-_"})",
+ R"(optional_bytes: "\xfb")");
+
+ // Message fields.
+ RunValidJsonTest(
+ "MessageField", REQUIRED,
+ R"({"optionalNestedMessage": {"a": 1234}})",
+ "optional_nested_message: {a: 1234}");
+
+ // Oneof fields.
+ ExpectParseFailureForJson(
+ "OneofFieldDuplicate", REQUIRED,
+ R"({"oneofUint32": 1, "oneofString": "test"})");
+ // Ensure zero values for oneof make it out/backs.
+ TestAllTypesProto3 messageProto3;
+ TestAllTypesProto2 messageProto2;
+ TestOneofMessage(messageProto3, true);
+ TestOneofMessage(messageProto2, false);
+ RunValidJsonTest(
+ "OneofZeroUint32", RECOMMENDED,
+ R"({"oneofUint32": 0})", "oneof_uint32: 0");
+ RunValidJsonTest(
+ "OneofZeroMessage", RECOMMENDED,
+ R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
+ RunValidJsonTest(
+ "OneofZeroString", RECOMMENDED,
+ R"({"oneofString": ""})", "oneof_string: \"\"");
+ RunValidJsonTest(
+ "OneofZeroBytes", RECOMMENDED,
+ R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
+ RunValidJsonTest(
+ "OneofZeroBool", RECOMMENDED,
+ R"({"oneofBool": false})", "oneof_bool: false");
+ RunValidJsonTest(
+ "OneofZeroUint64", RECOMMENDED,
+ R"({"oneofUint64": 0})", "oneof_uint64: 0");
+ RunValidJsonTest(
+ "OneofZeroFloat", RECOMMENDED,
+ R"({"oneofFloat": 0.0})", "oneof_float: 0");
+ RunValidJsonTest(
+ "OneofZeroDouble", RECOMMENDED,
+ R"({"oneofDouble": 0.0})", "oneof_double: 0");
+ RunValidJsonTest(
+ "OneofZeroEnum", RECOMMENDED,
+ R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
+
+ // Repeated fields.
+ RunValidJsonTest(
+ "PrimitiveRepeatedField", REQUIRED,
+ R"({"repeatedInt32": [1, 2, 3, 4]})",
+ "repeated_int32: [1, 2, 3, 4]");
+ RunValidJsonTest(
+ "EnumRepeatedField", REQUIRED,
+ R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
+ "repeated_nested_enum: [FOO, BAR, BAZ]");
+ RunValidJsonTest(
+ "StringRepeatedField", REQUIRED,
+ R"({"repeatedString": ["Hello", "world"]})",
+ R"(repeated_string: ["Hello", "world"])");
+ RunValidJsonTest(
+ "BytesRepeatedField", REQUIRED,
+ R"({"repeatedBytes": ["AAEC", "AQI="]})",
+ R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
+ RunValidJsonTest(
+ "MessageRepeatedField", REQUIRED,
+ R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
+ "repeated_nested_message: {a: 1234}"
+ "repeated_nested_message: {a: 5678}");
+
+ // Repeated field elements are of incorrect type.
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
+ R"({"repeatedInt32": [1, false, 3, 4]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
+ R"({"repeatedInt32": [1, 2, "name", 4]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
+ R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
+ R"({"repeatedString": ["1", 2, "3", "4"]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
+ R"({"repeatedString": ["1", "2", false, "4"]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
+ R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
+ R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
+ R"({"repeatedNestedMessage": [{"a": 1}, false]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
+ R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
+ // Trailing comma in the repeated field is not allowed.
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingComma", RECOMMENDED,
+ R"({"repeatedInt32": [1, 2, 3, 4,]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
+ "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
+ "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
+ "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
+
+ // Map fields.
+ RunValidJsonTest(
+ "Int32MapField", REQUIRED,
+ R"({"mapInt32Int32": {"1": 2, "3": 4}})",
+ "map_int32_int32: {key: 1 value: 2}"
+ "map_int32_int32: {key: 3 value: 4}");
+ ExpectParseFailureForJson(
+ "Int32MapFieldKeyNotQuoted", RECOMMENDED,
+ R"({"mapInt32Int32": {1: 2, 3: 4}})");
+ RunValidJsonTest(
+ "Uint32MapField", REQUIRED,
+ R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
+ "map_uint32_uint32: {key: 1 value: 2}"
+ "map_uint32_uint32: {key: 3 value: 4}");
+ ExpectParseFailureForJson(
+ "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
+ R"({"mapUint32Uint32": {1: 2, 3: 4}})");
+ RunValidJsonTest(
+ "Int64MapField", REQUIRED,
+ R"({"mapInt64Int64": {"1": 2, "3": 4}})",
+ "map_int64_int64: {key: 1 value: 2}"
+ "map_int64_int64: {key: 3 value: 4}");
+ ExpectParseFailureForJson(
+ "Int64MapFieldKeyNotQuoted", RECOMMENDED,
+ R"({"mapInt64Int64": {1: 2, 3: 4}})");
+ RunValidJsonTest(
+ "Uint64MapField", REQUIRED,
+ R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
+ "map_uint64_uint64: {key: 1 value: 2}"
+ "map_uint64_uint64: {key: 3 value: 4}");
+ ExpectParseFailureForJson(
+ "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
+ R"({"mapUint64Uint64": {1: 2, 3: 4}})");
+ RunValidJsonTest(
+ "BoolMapField", REQUIRED,
+ R"({"mapBoolBool": {"true": true, "false": false}})",
+ "map_bool_bool: {key: true value: true}"
+ "map_bool_bool: {key: false value: false}");
+ ExpectParseFailureForJson(
+ "BoolMapFieldKeyNotQuoted", RECOMMENDED,
+ R"({"mapBoolBool": {true: true, false: false}})");
+ RunValidJsonTest(
+ "MessageMapField", REQUIRED,
+ R"({
+ "mapStringNestedMessage": {
+ "hello": {"a": 1234},
+ "world": {"a": 5678}
+ }
+ })",
+ R"(
+ map_string_nested_message: {
+ key: "hello"
+ value: {a: 1234}
+ }
+ map_string_nested_message: {
+ key: "world"
+ value: {a: 5678}
+ }
+ )");
+ // Since Map keys are represented as JSON strings, escaping should be allowed.
+ RunValidJsonTest(
+ "Int32MapEscapedKey", REQUIRED,
+ R"({"mapInt32Int32": {"\u0031": 2}})",
+ "map_int32_int32: {key: 1 value: 2}");
+ RunValidJsonTest(
+ "Int64MapEscapedKey", REQUIRED,
+ R"({"mapInt64Int64": {"\u0031": 2}})",
+ "map_int64_int64: {key: 1 value: 2}");
+ RunValidJsonTest(
+ "BoolMapEscapedKey", REQUIRED,
+ R"({"mapBoolBool": {"tr\u0075e": true}})",
+ "map_bool_bool: {key: true value: true}");
+
+ // "null" is accepted for all fields types.
+ RunValidJsonTest(
+ "AllFieldAcceptNull", REQUIRED,
+ R"({
+ "optionalInt32": null,
+ "optionalInt64": null,
+ "optionalUint32": null,
+ "optionalUint64": null,
+ "optionalSint32": null,
+ "optionalSint64": null,
+ "optionalFixed32": null,
+ "optionalFixed64": null,
+ "optionalSfixed32": null,
+ "optionalSfixed64": null,
+ "optionalFloat": null,
+ "optionalDouble": null,
+ "optionalBool": null,
+ "optionalString": null,
+ "optionalBytes": null,
+ "optionalNestedEnum": null,
+ "optionalNestedMessage": null,
+ "repeatedInt32": null,
+ "repeatedInt64": null,
+ "repeatedUint32": null,
+ "repeatedUint64": null,
+ "repeatedSint32": null,
+ "repeatedSint64": null,
+ "repeatedFixed32": null,
+ "repeatedFixed64": null,
+ "repeatedSfixed32": null,
+ "repeatedSfixed64": null,
+ "repeatedFloat": null,
+ "repeatedDouble": null,
+ "repeatedBool": null,
+ "repeatedString": null,
+ "repeatedBytes": null,
+ "repeatedNestedEnum": null,
+ "repeatedNestedMessage": null,
+ "mapInt32Int32": null,
+ "mapBoolBool": null,
+ "mapStringNestedMessage": null
+ })",
+ "");
+
+ // Repeated field elements cannot be null.
+ ExpectParseFailureForJson(
+ "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
+ R"({"repeatedInt32": [1, null, 2]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldMessageElementIsNull", RECOMMENDED,
+ R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
+ // Map field keys cannot be null.
+ ExpectParseFailureForJson(
+ "MapFieldKeyIsNull", RECOMMENDED,
+ R"({"mapInt32Int32": {null: 1}})");
+ // Map field values cannot be null.
+ ExpectParseFailureForJson(
+ "MapFieldValueIsNull", RECOMMENDED,
+ R"({"mapInt32Int32": {"0": null}})");
+
+ // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
+ // quotes.
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteKey", RECOMMENDED,
+ R"({'optionalString': "Hello world!"})");
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteValue", RECOMMENDED,
+ R"({"optionalString": 'Hello world!'})");
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteBoth", RECOMMENDED,
+ R"({'optionalString': 'Hello world!'})");
+
+ // Unknown fields.
+ {
+ TestAllTypesProto3 messageProto3;
+ TestAllTypesProto2 messageProto2;
+ //TODO(yilunchong): update this behavior when unknown field's behavior
+ // changed in open source. Also delete
+ // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
+ // from failure list of python_cpp python java
+ TestUnknownMessage(messageProto3, true);
+ TestUnknownMessage(messageProto2, false);
+ }
+
+ // Wrapper types.
+ RunValidJsonTest(
+ "OptionalBoolWrapper", REQUIRED,
+ R"({"optionalBoolWrapper": false})",
+ "optional_bool_wrapper: {value: false}");
+ RunValidJsonTest(
+ "OptionalInt32Wrapper", REQUIRED,
+ R"({"optionalInt32Wrapper": 0})",
+ "optional_int32_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalUint32Wrapper", REQUIRED,
+ R"({"optionalUint32Wrapper": 0})",
+ "optional_uint32_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalInt64Wrapper", REQUIRED,
+ R"({"optionalInt64Wrapper": 0})",
+ "optional_int64_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalUint64Wrapper", REQUIRED,
+ R"({"optionalUint64Wrapper": 0})",
+ "optional_uint64_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalFloatWrapper", REQUIRED,
+ R"({"optionalFloatWrapper": 0})",
+ "optional_float_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalDoubleWrapper", REQUIRED,
+ R"({"optionalDoubleWrapper": 0})",
+ "optional_double_wrapper: {value: 0}");
+ RunValidJsonTest(
+ "OptionalStringWrapper", REQUIRED,
+ R"({"optionalStringWrapper": ""})",
+ R"(optional_string_wrapper: {value: ""})");
+ RunValidJsonTest(
+ "OptionalBytesWrapper", REQUIRED,
+ R"({"optionalBytesWrapper": ""})",
+ R"(optional_bytes_wrapper: {value: ""})");
+ RunValidJsonTest(
+ "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
+ R"({
+ "optionalBoolWrapper": true,
+ "optionalInt32Wrapper": 1,
+ "optionalUint32Wrapper": 1,
+ "optionalInt64Wrapper": "1",
+ "optionalUint64Wrapper": "1",
+ "optionalFloatWrapper": 1,
+ "optionalDoubleWrapper": 1,
+ "optionalStringWrapper": "1",
+ "optionalBytesWrapper": "AQI="
+ })",
+ R"(
+ optional_bool_wrapper: {value: true}
+ optional_int32_wrapper: {value: 1}
+ optional_uint32_wrapper: {value: 1}
+ optional_int64_wrapper: {value: 1}
+ optional_uint64_wrapper: {value: 1}
+ optional_float_wrapper: {value: 1}
+ optional_double_wrapper: {value: 1}
+ optional_string_wrapper: {value: "1"}
+ optional_bytes_wrapper: {value: "\x01\x02"}
+ )");
+ RunValidJsonTest(
+ "RepeatedBoolWrapper", REQUIRED,
+ R"({"repeatedBoolWrapper": [true, false]})",
+ "repeated_bool_wrapper: {value: true}"
+ "repeated_bool_wrapper: {value: false}");
+ RunValidJsonTest(
+ "RepeatedInt32Wrapper", REQUIRED,
+ R"({"repeatedInt32Wrapper": [0, 1]})",
+ "repeated_int32_wrapper: {value: 0}"
+ "repeated_int32_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedUint32Wrapper", REQUIRED,
+ R"({"repeatedUint32Wrapper": [0, 1]})",
+ "repeated_uint32_wrapper: {value: 0}"
+ "repeated_uint32_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedInt64Wrapper", REQUIRED,
+ R"({"repeatedInt64Wrapper": [0, 1]})",
+ "repeated_int64_wrapper: {value: 0}"
+ "repeated_int64_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedUint64Wrapper", REQUIRED,
+ R"({"repeatedUint64Wrapper": [0, 1]})",
+ "repeated_uint64_wrapper: {value: 0}"
+ "repeated_uint64_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedFloatWrapper", REQUIRED,
+ R"({"repeatedFloatWrapper": [0, 1]})",
+ "repeated_float_wrapper: {value: 0}"
+ "repeated_float_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedDoubleWrapper", REQUIRED,
+ R"({"repeatedDoubleWrapper": [0, 1]})",
+ "repeated_double_wrapper: {value: 0}"
+ "repeated_double_wrapper: {value: 1}");
+ RunValidJsonTest(
+ "RepeatedStringWrapper", REQUIRED,
+ R"({"repeatedStringWrapper": ["", "AQI="]})",
+ R"(
+ repeated_string_wrapper: {value: ""}
+ repeated_string_wrapper: {value: "AQI="}
+ )");
+ RunValidJsonTest(
+ "RepeatedBytesWrapper", REQUIRED,
+ R"({"repeatedBytesWrapper": ["", "AQI="]})",
+ R"(
+ repeated_bytes_wrapper: {value: ""}
+ repeated_bytes_wrapper: {value: "\x01\x02"}
+ )");
+ RunValidJsonTest(
+ "WrapperTypesWithNullValue", REQUIRED,
+ R"({
+ "optionalBoolWrapper": null,
+ "optionalInt32Wrapper": null,
+ "optionalUint32Wrapper": null,
+ "optionalInt64Wrapper": null,
+ "optionalUint64Wrapper": null,
+ "optionalFloatWrapper": null,
+ "optionalDoubleWrapper": null,
+ "optionalStringWrapper": null,
+ "optionalBytesWrapper": null,
+ "repeatedBoolWrapper": null,
+ "repeatedInt32Wrapper": null,
+ "repeatedUint32Wrapper": null,
+ "repeatedInt64Wrapper": null,
+ "repeatedUint64Wrapper": null,
+ "repeatedFloatWrapper": null,
+ "repeatedDoubleWrapper": null,
+ "repeatedStringWrapper": null,
+ "repeatedBytesWrapper": null
+ })",
+ "");
+
+ // Duration
+ RunValidJsonTest(
+ "DurationMinValue", REQUIRED,
+ R"({"optionalDuration": "-315576000000.999999999s"})",
+ "optional_duration: {seconds: -315576000000 nanos: -999999999}");
+ RunValidJsonTest(
+ "DurationMaxValue", REQUIRED,
+ R"({"optionalDuration": "315576000000.999999999s"})",
+ "optional_duration: {seconds: 315576000000 nanos: 999999999}");
+ RunValidJsonTest(
+ "DurationRepeatedValue", REQUIRED,
+ 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,
+ R"({"optionalDuration": "1"})");
+ ExpectParseFailureForJson(
+ "DurationJsonInputTooSmall", REQUIRED,
+ R"({"optionalDuration": "-315576000001.000000000s"})");
+ ExpectParseFailureForJson(
+ "DurationJsonInputTooLarge", REQUIRED,
+ R"({"optionalDuration": "315576000001.000000000s"})");
+ ExpectSerializeFailureForJson(
+ "DurationProtoInputTooSmall", REQUIRED,
+ "optional_duration: {seconds: -315576000001 nanos: 0}");
+ ExpectSerializeFailureForJson(
+ "DurationProtoInputTooLarge", REQUIRED,
+ "optional_duration: {seconds: 315576000001 nanos: 0}");
+
+ RunValidJsonTestWithValidator(
+ "DurationHasZeroFractionalDigit", RECOMMENDED,
+ R"({"optionalDuration": "1.000000000s"})",
+ [](const Json::Value& value) {
+ return value["optionalDuration"].asString() == "1s";
+ });
+ RunValidJsonTestWithValidator(
+ "DurationHas3FractionalDigits", RECOMMENDED,
+ R"({"optionalDuration": "1.010000000s"})",
+ [](const Json::Value& value) {
+ return value["optionalDuration"].asString() == "1.010s";
+ });
+ RunValidJsonTestWithValidator(
+ "DurationHas6FractionalDigits", RECOMMENDED,
+ R"({"optionalDuration": "1.000010000s"})",
+ [](const Json::Value& value) {
+ return value["optionalDuration"].asString() == "1.000010s";
+ });
+ RunValidJsonTestWithValidator(
+ "DurationHas9FractionalDigits", RECOMMENDED,
+ R"({"optionalDuration": "1.000000010s"})",
+ [](const Json::Value& value) {
+ return value["optionalDuration"].asString() == "1.000000010s";
+ });
+
+ // Timestamp
+ RunValidJsonTest(
+ "TimestampMinValue", REQUIRED,
+ R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
+ "optional_timestamp: {seconds: -62135596800}");
+ RunValidJsonTest(
+ "TimestampMaxValue", REQUIRED,
+ R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
+ "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
+ RunValidJsonTest(
+ "TimestampRepeatedValue", REQUIRED,
+ R"({
+ "repeatedTimestamp": [
+ "0001-01-01T00:00:00Z",
+ "9999-12-31T23:59:59.999999999Z"
+ ]
+ })",
+ "repeated_timestamp: {seconds: -62135596800}"
+ "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
+ RunValidJsonTest(
+ "TimestampWithPositiveOffset", REQUIRED,
+ R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
+ "optional_timestamp: {seconds: 0}");
+ RunValidJsonTest(
+ "TimestampWithNegativeOffset", REQUIRED,
+ R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
+ "optional_timestamp: {seconds: 0}");
+ RunValidJsonTest(
+ "TimestampNull", REQUIRED,
+ R"({"optionalTimestamp": null})",
+ "");
+
+ ExpectParseFailureForJson(
+ "TimestampJsonInputTooSmall", REQUIRED,
+ R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
+ ExpectParseFailureForJson(
+ "TimestampJsonInputTooLarge", REQUIRED,
+ R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
+ ExpectParseFailureForJson(
+ "TimestampJsonInputMissingZ", REQUIRED,
+ R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
+ ExpectParseFailureForJson(
+ "TimestampJsonInputMissingT", REQUIRED,
+ R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
+ ExpectParseFailureForJson(
+ "TimestampJsonInputLowercaseZ", REQUIRED,
+ R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
+ ExpectParseFailureForJson(
+ "TimestampJsonInputLowercaseT", REQUIRED,
+ R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
+ ExpectSerializeFailureForJson(
+ "TimestampProtoInputTooSmall", REQUIRED,
+ "optional_timestamp: {seconds: -62135596801}");
+ ExpectSerializeFailureForJson(
+ "TimestampProtoInputTooLarge", REQUIRED,
+ "optional_timestamp: {seconds: 253402300800}");
+ RunValidJsonTestWithValidator(
+ "TimestampZeroNormalized", RECOMMENDED,
+ R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
+ [](const Json::Value& value) {
+ return value["optionalTimestamp"].asString() ==
+ "1970-01-01T00:00:00Z";
+ });
+ RunValidJsonTestWithValidator(
+ "TimestampHasZeroFractionalDigit", RECOMMENDED,
+ R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
+ [](const Json::Value& value) {
+ return value["optionalTimestamp"].asString() ==
+ "1970-01-01T00:00:00Z";
+ });
+ RunValidJsonTestWithValidator(
+ "TimestampHas3FractionalDigits", RECOMMENDED,
+ R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
+ [](const Json::Value& value) {
+ return value["optionalTimestamp"].asString() ==
+ "1970-01-01T00:00:00.010Z";
+ });
+ RunValidJsonTestWithValidator(
+ "TimestampHas6FractionalDigits", RECOMMENDED,
+ R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
+ [](const Json::Value& value) {
+ return value["optionalTimestamp"].asString() ==
+ "1970-01-01T00:00:00.000010Z";
+ });
+ RunValidJsonTestWithValidator(
+ "TimestampHas9FractionalDigits", RECOMMENDED,
+ R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
+ [](const Json::Value& value) {
+ return value["optionalTimestamp"].asString() ==
+ "1970-01-01T00:00:00.000000010Z";
+ });
+
+ // FieldMask
+ RunValidJsonTest(
+ "FieldMask", REQUIRED,
+ R"({"optionalFieldMask": "foo,barBaz"})",
+ R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
+ ExpectParseFailureForJson(
+ "FieldMaskInvalidCharacter", RECOMMENDED,
+ R"({"optionalFieldMask": "foo,bar_bar"})");
+ ExpectSerializeFailureForJson(
+ "FieldMaskPathsDontRoundTrip", RECOMMENDED,
+ R"(optional_field_mask: {paths: "fooBar"})");
+ ExpectSerializeFailureForJson(
+ "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
+ R"(optional_field_mask: {paths: "foo_3_bar"})");
+ ExpectSerializeFailureForJson(
+ "FieldMaskTooManyUnderscore", RECOMMENDED,
+ R"(optional_field_mask: {paths: "foo__bar"})");
+
+ // Struct
+ RunValidJsonTest(
+ "Struct", REQUIRED,
+ R"({
+ "optionalStruct": {
+ "nullValue": null,
+ "intValue": 1234,
+ "boolValue": true,
+ "doubleValue": 1234.5678,
+ "stringValue": "Hello world!",
+ "listValue": [1234, "5678"],
+ "objectValue": {
+ "value": 0
+ }
+ }
+ })",
+ R"(
+ optional_struct: {
+ fields: {
+ key: "nullValue"
+ value: {null_value: NULL_VALUE}
+ }
+ fields: {
+ key: "intValue"
+ value: {number_value: 1234}
+ }
+ fields: {
+ key: "boolValue"
+ value: {bool_value: true}
+ }
+ fields: {
+ key: "doubleValue"
+ value: {number_value: 1234.5678}
+ }
+ fields: {
+ key: "stringValue"
+ value: {string_value: "Hello world!"}
+ }
+ fields: {
+ key: "listValue"
+ value: {
+ list_value: {
+ values: {
+ number_value: 1234
+ }
+ values: {
+ string_value: "5678"
+ }
+ }
+ }
+ }
+ fields: {
+ key: "objectValue"
+ value: {
+ struct_value: {
+ fields: {
+ key: "value"
+ value: {
+ number_value: 0
+ }
+ }
+ }
+ }
+ }
+ }
+ )");
+ // Value
+ RunValidJsonTest(
+ "ValueAcceptInteger", REQUIRED,
+ R"({"optionalValue": 1})",
+ "optional_value: { number_value: 1}");
+ RunValidJsonTest(
+ "ValueAcceptFloat", REQUIRED,
+ R"({"optionalValue": 1.5})",
+ "optional_value: { number_value: 1.5}");
+ RunValidJsonTest(
+ "ValueAcceptBool", REQUIRED,
+ R"({"optionalValue": false})",
+ "optional_value: { bool_value: false}");
+ RunValidJsonTest(
+ "ValueAcceptNull", REQUIRED,
+ R"({"optionalValue": null})",
+ "optional_value: { null_value: NULL_VALUE}");
+ RunValidJsonTest(
+ "ValueAcceptString", REQUIRED,
+ R"({"optionalValue": "hello"})",
+ R"(optional_value: { string_value: "hello"})");
+ RunValidJsonTest(
+ "ValueAcceptList", REQUIRED,
+ R"({"optionalValue": [0, "hello"]})",
+ R"(
+ optional_value: {
+ list_value: {
+ values: {
+ number_value: 0
+ }
+ values: {
+ string_value: "hello"
+ }
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "ValueAcceptObject", REQUIRED,
+ R"({"optionalValue": {"value": 1}})",
+ R"(
+ optional_value: {
+ struct_value: {
+ fields: {
+ key: "value"
+ value: {
+ number_value: 1
+ }
+ }
+ }
+ }
+ )");
+
+ // Any
+ RunValidJsonTest(
+ "Any", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
+ "optionalInt32": 12345
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
+ optional_int32: 12345
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyNested", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Any",
+ "value": {
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
+ "optionalInt32": 12345
+ }
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Any] {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
+ optional_int32: 12345
+ }
+ }
+ }
+ )");
+ // The special "@type" tag is not required to appear first.
+ RunValidJsonTest(
+ "AnyUnorderedTypeTag", REQUIRED,
+ R"({
+ "optionalAny": {
+ "optionalInt32": 12345,
+ "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
+ optional_int32: 12345
+ }
+ }
+ )");
+ // Well-known types in Any.
+ RunValidJsonTest(
+ "AnyWithInt32ValueWrapper", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Int32Value",
+ "value": 12345
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Int32Value] {
+ value: 12345
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithDuration", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Duration",
+ "value": "1.5s"
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Duration] {
+ seconds: 1
+ nanos: 500000000
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithTimestamp", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Timestamp",
+ "value": "1970-01-01T00:00:00Z"
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Timestamp] {
+ seconds: 0
+ nanos: 0
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithFieldMask", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.FieldMask",
+ "value": "foo,barBaz"
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.FieldMask] {
+ paths: ["foo", "bar_baz"]
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithStruct", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Struct",
+ "value": {
+ "foo": 1
+ }
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Struct] {
+ fields: {
+ key: "foo"
+ value: {
+ number_value: 1
+ }
+ }
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithValueForJsonObject", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Value",
+ "value": {
+ "foo": 1
+ }
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Value] {
+ struct_value: {
+ fields: {
+ key: "foo"
+ value: {
+ number_value: 1
+ }
+ }
+ }
+ }
+ }
+ )");
+ RunValidJsonTest(
+ "AnyWithValueForInteger", REQUIRED,
+ R"({
+ "optionalAny": {
+ "@type": "type.googleapis.com/google.protobuf.Value",
+ "value": 1
+ }
+ })",
+ R"(
+ optional_any: {
+ [type.googleapis.com/google.protobuf.Value] {
+ number_value: 1
+ }
+ }
+ )");
+
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonNumber", REQUIRED,
+ R"({
+ "unknown": 1
+ })",
+ "");
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonString", REQUIRED,
+ R"({
+ "unknown": "a"
+ })",
+ "");
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonTrue", REQUIRED,
+ R"({
+ "unknown": true
+ })",
+ "");
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonFalse", REQUIRED,
+ R"({
+ "unknown": false
+ })",
+ "");
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonNull", REQUIRED,
+ R"({
+ "unknown": null
+ })",
+ "");
+ RunValidJsonIgnoreUnknownTest(
+ "IgnoreUnknownJsonObject", REQUIRED,
+ R"({
+ "unknown": {"a": 1}
+ })",
+ "");
+}
+
+} // namespace protobuf
+} // namespace google
+
+int main(int argc, char *argv[]) {
+ google::protobuf::ConformanceTestSuiteImpl suite;
+ return google::protobuf::ForkPipeRunner::Run(argc, argv, &suite);
+}
diff --git a/conformance/conformance_test_runner.cc b/conformance/conformance_test_runner.cc
index b0357b87..9c377124 100644
--- a/conformance/conformance_test_runner.cc
+++ b/conformance/conformance_test_runner.cc
@@ -66,9 +66,9 @@
#include "conformance.pb.h"
#include "conformance_test.h"
-using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
using google::protobuf::StringAppendF;
+using google::protobuf::ConformanceTestSuite;
using std::string;
using std::vector;
@@ -80,162 +80,31 @@ using std::vector;
exit(1); \
}
-// Test runner that spawns the process being tested and communicates with it
-// over a pipe.
-class ForkPipeRunner : public google::protobuf::ConformanceTestRunner {
- public:
- ForkPipeRunner(const std::string &executable)
- : child_pid_(-1), executable_(executable) {}
+namespace google {
+namespace protobuf {
- virtual ~ForkPipeRunner() {}
-
- void RunTest(const std::string& test_name,
- const std::string& request,
- std::string* response) {
- if (child_pid_ < 0) {
- SpawnTestProgram();
- }
-
- current_test_name_ = test_name;
-
- uint32_t len = request.size();
- CheckedWrite(write_fd_, &len, sizeof(uint32_t));
- CheckedWrite(write_fd_, request.c_str(), request.size());
-
- if (!TryRead(read_fd_, &len, sizeof(uint32_t))) {
- // We failed to read from the child, assume a crash and try to reap.
- GOOGLE_LOG(INFO) << "Trying to reap child, pid=" << child_pid_;
-
- int status;
- waitpid(child_pid_, &status, WEXITED);
-
- string error_msg;
- if (WIFEXITED(status)) {
- StringAppendF(&error_msg,
- "child exited, status=%d", WEXITSTATUS(status));
- } else if (WIFSIGNALED(status)) {
- StringAppendF(&error_msg,
- "child killed by signal %d", WTERMSIG(status));
- }
- GOOGLE_LOG(INFO) << error_msg;
- child_pid_ = -1;
-
- conformance::ConformanceResponse response_obj;
- response_obj.set_runtime_error(error_msg);
- response_obj.SerializeToString(response);
- return;
- }
-
- response->resize(len);
- CheckedRead(read_fd_, (void*)response->c_str(), len);
- }
-
- private:
- // TODO(haberman): make this work on Windows, instead of using these
- // UNIX-specific APIs.
- //
- // There is a platform-agnostic API in
- // src/google/protobuf/compiler/subprocess.h
- //
- // However that API only supports sending a single message to the subprocess.
- // We really want to be able to send messages and receive responses one at a
- // time:
- //
- // 1. Spawning a new process for each test would take way too long for thousands
- // of tests and subprocesses like java that can take 100ms or more to start
- // up.
- //
- // 2. Sending all the tests in one big message and receiving all results in one
- // big message would take away our visibility about which test(s) caused a
- // crash or other fatal error. It would also give us only a single failure
- // instead of all of them.
- void SpawnTestProgram() {
- int toproc_pipe_fd[2];
- int fromproc_pipe_fd[2];
- if (pipe(toproc_pipe_fd) < 0 || pipe(fromproc_pipe_fd) < 0) {
- perror("pipe");
- exit(1);
- }
-
- pid_t pid = fork();
- if (pid < 0) {
- perror("fork");
- exit(1);
- }
-
- if (pid) {
- // Parent.
- CHECK_SYSCALL(close(toproc_pipe_fd[0]));
- CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
- write_fd_ = toproc_pipe_fd[1];
- read_fd_ = fromproc_pipe_fd[0];
- child_pid_ = pid;
- } else {
- // Child.
- CHECK_SYSCALL(close(STDIN_FILENO));
- CHECK_SYSCALL(close(STDOUT_FILENO));
- CHECK_SYSCALL(dup2(toproc_pipe_fd[0], STDIN_FILENO));
- CHECK_SYSCALL(dup2(fromproc_pipe_fd[1], STDOUT_FILENO));
-
- CHECK_SYSCALL(close(toproc_pipe_fd[0]));
- CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
- CHECK_SYSCALL(close(toproc_pipe_fd[1]));
- CHECK_SYSCALL(close(fromproc_pipe_fd[0]));
-
- std::unique_ptr<char[]> executable(new char[executable_.size() + 1]);
- memcpy(executable.get(), executable_.c_str(), executable_.size());
- executable[executable_.size()] = '\0';
-
- char *const argv[] = {executable.get(), NULL};
- CHECK_SYSCALL(execv(executable.get(), argv)); // Never returns.
- }
- }
+void ParseFailureList(const char *filename,
+ std::vector<string>* failure_list) {
+ std::ifstream infile(filename);
- void CheckedWrite(int fd, const void *buf, size_t len) {
- if (write(fd, buf, len) != len) {
- GOOGLE_LOG(FATAL) << current_test_name_
- << ": error writing to test program: "
- << strerror(errno);
- }
+ if (!infile.is_open()) {
+ fprintf(stderr, "Couldn't open failure list file: %s\n", filename);
+ exit(1);
}
- bool TryRead(int fd, void *buf, size_t len) {
- size_t ofs = 0;
- while (len > 0) {
- ssize_t bytes_read = read(fd, (char*)buf + ofs, len);
-
- if (bytes_read == 0) {
- GOOGLE_LOG(ERROR) << current_test_name_
- << ": unexpected EOF from test program";
- return false;
- } else if (bytes_read < 0) {
- GOOGLE_LOG(ERROR) << current_test_name_
- << ": error reading from test program: "
- << strerror(errno);
- return false;
- }
-
- len -= bytes_read;
- ofs += bytes_read;
- }
+ for (string line; getline(infile, line);) {
+ // Remove whitespace.
+ line.erase(std::remove_if(line.begin(), line.end(), ::isspace),
+ line.end());
- return true;
- }
+ // Remove comments.
+ line = line.substr(0, line.find("#"));
- void CheckedRead(int fd, void *buf, size_t len) {
- if (!TryRead(fd, buf, len)) {
- GOOGLE_LOG(FATAL) << current_test_name_
- << ": error reading from test program: "
- << strerror(errno);
+ if (!line.empty()) {
+ failure_list->push_back(line);
}
}
-
- int write_fd_;
- int read_fd_;
- pid_t child_pid_;
- std::string executable_;
- std::string current_test_name_;
-};
+}
void UsageError() {
fprintf(stderr,
@@ -263,32 +132,51 @@ void UsageError() {
exit(1);
}
-void ParseFailureList(const char *filename, std::vector<string>* failure_list) {
- std::ifstream infile(filename);
-
- if (!infile.is_open()) {
- fprintf(stderr, "Couldn't open failure list file: %s\n", filename);
- exit(1);
+void ForkPipeRunner::RunTest(
+ const std::string& test_name,
+ const std::string& request,
+ std::string* response) {
+ if (child_pid_ < 0) {
+ SpawnTestProgram();
}
- for (string line; getline(infile, line);) {
- // Remove whitespace.
- line.erase(std::remove_if(line.begin(), line.end(), ::isspace),
- line.end());
+ current_test_name_ = test_name;
- // Remove comments.
- line = line.substr(0, line.find("#"));
+ uint32_t len = request.size();
+ CheckedWrite(write_fd_, &len, sizeof(uint32_t));
+ CheckedWrite(write_fd_, request.c_str(), request.size());
- if (!line.empty()) {
- failure_list->push_back(line);
+ if (!TryRead(read_fd_, &len, sizeof(uint32_t))) {
+ // We failed to read from the child, assume a crash and try to reap.
+ GOOGLE_LOG(INFO) << "Trying to reap child, pid=" << child_pid_;
+
+ int status;
+ waitpid(child_pid_, &status, WEXITED);
+
+ string error_msg;
+ if (WIFEXITED(status)) {
+ StringAppendF(&error_msg,
+ "child exited, status=%d", WEXITSTATUS(status));
+ } else if (WIFSIGNALED(status)) {
+ StringAppendF(&error_msg,
+ "child killed by signal %d", WTERMSIG(status));
}
+ GOOGLE_LOG(INFO) << error_msg;
+ child_pid_ = -1;
+
+ conformance::ConformanceResponse response_obj;
+ response_obj.set_runtime_error(error_msg);
+ response_obj.SerializeToString(response);
+ return;
}
+
+ response->resize(len);
+ CheckedRead(read_fd_, (void*)response->c_str(), len);
}
-int main(int argc, char *argv[]) {
+int ForkPipeRunner::Run(
+ int argc, char *argv[], ConformanceTestSuite* suite) {
char *program;
- google::protobuf::ConformanceTestSuite suite;
-
string failure_list_filename;
std::vector<string> failure_list;
@@ -298,9 +186,9 @@ int main(int argc, char *argv[]) {
failure_list_filename = argv[arg];
ParseFailureList(argv[arg], &failure_list);
} else if (strcmp(argv[arg], "--verbose") == 0) {
- suite.SetVerbose(true);
+ suite->SetVerbose(true);
} else if (strcmp(argv[arg], "--enforce_recommended") == 0) {
- suite.SetEnforceRecommended(true);
+ suite->SetEnforceRecommended(true);
} else if (argv[arg][0] == '-') {
fprintf(stderr, "Unknown option: %s\n", argv[arg]);
UsageError();
@@ -313,13 +201,97 @@ int main(int argc, char *argv[]) {
}
}
- suite.SetFailureList(failure_list_filename, failure_list);
+ suite->SetFailureList(failure_list_filename, failure_list);
ForkPipeRunner runner(program);
std::string output;
- bool ok = suite.RunSuite(&runner, &output);
+ bool ok = suite->RunSuite(&runner, &output);
fwrite(output.c_str(), 1, output.size(), stderr);
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
+
+void ForkPipeRunner::SpawnTestProgram() {
+ int toproc_pipe_fd[2];
+ int fromproc_pipe_fd[2];
+ if (pipe(toproc_pipe_fd) < 0 || pipe(fromproc_pipe_fd) < 0) {
+ perror("pipe");
+ exit(1);
+ }
+
+ pid_t pid = fork();
+ if (pid < 0) {
+ perror("fork");
+ exit(1);
+ }
+
+ if (pid) {
+ // Parent.
+ CHECK_SYSCALL(close(toproc_pipe_fd[0]));
+ CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
+ write_fd_ = toproc_pipe_fd[1];
+ read_fd_ = fromproc_pipe_fd[0];
+ child_pid_ = pid;
+ } else {
+ // Child.
+ CHECK_SYSCALL(close(STDIN_FILENO));
+ CHECK_SYSCALL(close(STDOUT_FILENO));
+ CHECK_SYSCALL(dup2(toproc_pipe_fd[0], STDIN_FILENO));
+ CHECK_SYSCALL(dup2(fromproc_pipe_fd[1], STDOUT_FILENO));
+
+ CHECK_SYSCALL(close(toproc_pipe_fd[0]));
+ CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
+ CHECK_SYSCALL(close(toproc_pipe_fd[1]));
+ CHECK_SYSCALL(close(fromproc_pipe_fd[0]));
+
+ std::unique_ptr<char[]> executable(new char[executable_.size() + 1]);
+ memcpy(executable.get(), executable_.c_str(), executable_.size());
+ executable[executable_.size()] = '\0';
+
+ char *const argv[] = {executable.get(), NULL};
+ CHECK_SYSCALL(execv(executable.get(), argv)); // Never returns.
+ }
+}
+
+void ForkPipeRunner::CheckedWrite(int fd, const void *buf, size_t len) {
+ if (write(fd, buf, len) != len) {
+ GOOGLE_LOG(FATAL) << current_test_name_
+ << ": error writing to test program: "
+ << strerror(errno);
+ }
+}
+
+bool ForkPipeRunner::TryRead(int fd, void *buf, size_t len) {
+ size_t ofs = 0;
+ while (len > 0) {
+ ssize_t bytes_read = read(fd, (char*)buf + ofs, len);
+
+ if (bytes_read == 0) {
+ GOOGLE_LOG(ERROR) << current_test_name_
+ << ": unexpected EOF from test program";
+ return false;
+ } else if (bytes_read < 0) {
+ GOOGLE_LOG(ERROR) << current_test_name_
+ << ": error reading from test program: "
+ << strerror(errno);
+ return false;
+ }
+
+ len -= bytes_read;
+ ofs += bytes_read;
+ }
+
+ return true;
+}
+
+void ForkPipeRunner::CheckedRead(int fd, void *buf, size_t len) {
+ if (!TryRead(fd, buf, len)) {
+ GOOGLE_LOG(FATAL) << current_test_name_
+ << ": error reading from test program: "
+ << strerror(errno);
+ }
+}
+
+} // namespace protobuf
+} // namespace google
diff --git a/conformance/failure_list_php_c.txt b/conformance/failure_list_php_c.txt
index 088708e9..17e0fda4 100644
--- a/conformance/failure_list_php_c.txt
+++ b/conformance/failure_list_php_c.txt
@@ -1,8 +1,8 @@
Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
Recommended.FieldMaskTooManyUnderscore.JsonOutput
-Recommended.Proto3.JsonInput.BoolFieldIntegerOne
-Recommended.Proto3.JsonInput.BoolFieldIntegerZero
+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
@@ -10,20 +10,19 @@ 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.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
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
@@ -47,106 +46,27 @@ 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.OneofFieldDuplicate
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
@@ -155,10 +75,16 @@ Required.Proto3.JsonInput.StringFieldUnicodeEscapeWithLowercaseHexLetters.JsonOu
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.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
diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt
index b2683372..53b49701 100644
--- a/conformance/failure_list_ruby.txt
+++ b/conformance/failure_list_ruby.txt
@@ -120,8 +120,6 @@ Required.Proto3.JsonInput.ValueAcceptInteger.JsonOutput
Required.Proto3.JsonInput.ValueAcceptInteger.ProtobufOutput
Required.Proto3.JsonInput.ValueAcceptList.JsonOutput
Required.Proto3.JsonInput.ValueAcceptList.ProtobufOutput
-Required.Proto3.JsonInput.ValueAcceptListWithNull.JsonOutput
-Required.Proto3.JsonInput.ValueAcceptListWithNull.ProtobufOutput
Required.Proto3.JsonInput.ValueAcceptNull.JsonOutput
Required.Proto3.JsonInput.ValueAcceptNull.ProtobufOutput
Required.Proto3.JsonInput.ValueAcceptObject.JsonOutput
@@ -135,3 +133,9 @@ Required.Proto3.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
Required.Proto3.ProtobufInput.ValidDataRepeated.FLOAT.JsonOutput
Required.TimestampProtoInputTooLarge.JsonOutput
Required.TimestampProtoInputTooSmall.JsonOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonFalse.ProtobufOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonNull.ProtobufOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonNumber.ProtobufOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonObject.ProtobufOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonString.ProtobufOutput
+Required.Proto3.JsonInput.IgnoreUnknownJsonTrue.ProtobufOutput
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec
index 8a0d61e1..05779d44 100644
--- a/csharp/Google.Protobuf.Tools.nuspec
+++ b/csharp/Google.Protobuf.Tools.nuspec
@@ -8,8 +8,8 @@
<version>3.6.1</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
- <licenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</licenseUrl>
- <projectUrl>https://github.com/google/protobuf</projectUrl>
+ <licenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</licenseUrl>
+ <projectUrl>https://github.com/protocolbuffers/protobuf</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<releaseNotes>Tools for Protocol Buffers</releaseNotes>
<copyright>Copyright 2015, Google Inc.</copyright>
@@ -33,5 +33,7 @@
<file src="..\src\google\protobuf\timestamp.proto" target="tools\google\protobuf" />
<file src="..\src\google\protobuf\type.proto" target="tools\google\protobuf" />
<file src="..\src\google\protobuf\wrappers.proto" target="tools\google\protobuf" />
+ <file src="Google.Protobuf.Tools.targets" target="buildCrossTargeting" />
+ <file src="Google.Protobuf.Tools.targets" target="build" />
</files>
</package>
diff --git a/csharp/Google.Protobuf.Tools.targets b/csharp/Google.Protobuf.Tools.targets
new file mode 100644
index 00000000..682e11b0
--- /dev/null
+++ b/csharp/Google.Protobuf.Tools.targets
@@ -0,0 +1,11 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <protoc_tools>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)/../tools/'))</protoc_tools>
+ <protoc_linux64>$([System.IO.Path]::GetFullPath('$(protoc_tools)/linux_x64/protoc'))</protoc_linux64>
+ <protoc_linux86>$([System.IO.Path]::GetFullPath('$(protoc_tools)/linux_x86/protoc'))</protoc_linux86>
+ <protoc_macosx64>$([System.IO.Path]::GetFullPath('$(protoc_tools)/macosx_x64/protoc'))</protoc_macosx64>
+ <protoc_macosx86>$([System.IO.Path]::GetFullPath('$(protoc_tools)/macosx_x86/protoc'))</protoc_macosx86>
+ <protoc_windows64>$([System.IO.Path]::GetFullPath('$(protoc_tools)/windows_x64/protoc.exe'))</protoc_windows64>
+ <protoc_windows86>$([System.IO.Path]::GetFullPath('$(protoc_tools)/windows_x86/protoc.exe'))</protoc_windows86>
+ </PropertyGroup>
+</Project>
diff --git a/csharp/README.md b/csharp/README.md
index 9d1225f1..aafef16a 100644
--- a/csharp/README.md
+++ b/csharp/README.md
@@ -77,7 +77,7 @@ History of C# protobufs
This subtree was originally imported from https://github.com/jskeet/protobuf-csharp-port
and represents the latest development version of C# protobufs, that will now be developed
and maintained by Google. All the development will be done in open, under this repository
-(https://github.com/google/protobuf).
+(https://github.com/protocolbuffers/protobuf).
The previous project differs from this project in a number of ways:
diff --git a/csharp/build_packages.bat b/csharp/build_packages.bat
index d7205659..8157bbab 100644
--- a/csharp/build_packages.bat
+++ b/csharp/build_packages.bat
@@ -1,7 +1,7 @@
@rem Builds Google.Protobuf NuGet packages
dotnet restore src/Google.Protobuf.sln
-dotnet pack -c Release src/Google.Protobuf.sln || goto :error
+dotnet pack -c Release src/Google.Protobuf.sln /p:SourceLinkCreate=true || goto :error
goto :EOF
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
index 6c9f7634..7bec1f80 100644
--- 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
@@ -19,7 +19,7 @@ message Issue307 {
}
// 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
+// New issue 309: https://github.com/protocolbuffers/protobuf/issues/309
// message A {
// optional int32 _A = 1;
@@ -35,7 +35,7 @@ message Issue307 {
// 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
+// See https://github.com/protocolbuffers/protobuf/issues/308
// message NumberField {
// optional int32 _01 = 1;
// }
diff --git a/csharp/protos/unittest_issues.proto b/csharp/protos/unittest_issues.proto
index 0d8793e1..1619f13d 100644
--- a/csharp/protos/unittest_issues.proto
+++ b/csharp/protos/unittest_issues.proto
@@ -18,7 +18,7 @@ message Issue307 {
}
// 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
+// New issue 309: https://github.com/protocolbuffers/protobuf/issues/309
// message A {
// optional int32 _A = 1;
@@ -34,7 +34,7 @@ message Issue307 {
// 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
+// See https://github.com/protocolbuffers/protobuf/issues/308
// message NumberField {
// optional int32 _01 = 1;
// }
diff --git a/csharp/src/Google.Protobuf.Conformance/Conformance.cs b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
index f6118ea2..46793ce1 100644
--- a/csharp/src/Google.Protobuf.Conformance/Conformance.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
@@ -24,21 +24,25 @@ namespace Conformance {
static ConformanceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
- "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UiowEKEkNvbmZvcm1h",
+ "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2Ui1QEKEkNvbmZvcm1h",
"bmNlUmVxdWVzdBIaChBwcm90b2J1Zl9wYXlsb2FkGAEgASgMSAASFgoManNv",
"bl9wYXlsb2FkGAIgASgJSAASOAoXcmVxdWVzdGVkX291dHB1dF9mb3JtYXQY",
"AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0EhQKDG1lc3NhZ2VfdHlw",
- "ZRgEIAEoCUIJCgdwYXlsb2FkIrEBChNDb25mb3JtYW5jZVJlc3BvbnNlEhUK",
- "C3BhcnNlX2Vycm9yGAEgASgJSAASGQoPc2VyaWFsaXplX2Vycm9yGAYgASgJ",
- "SAASFwoNcnVudGltZV9lcnJvchgCIAEoCUgAEhoKEHByb3RvYnVmX3BheWxv",
- "YWQYAyABKAxIABIWCgxqc29uX3BheWxvYWQYBCABKAlIABIRCgdza2lwcGVk",
- "GAUgASgJSABCCAoGcmVzdWx0KjUKCldpcmVGb3JtYXQSDwoLVU5TUEVDSUZJ",
- "RUQQABIMCghQUk9UT0JVRhABEggKBEpTT04QAkIhCh9jb20uZ29vZ2xlLnBy",
- "b3RvYnVmLmNvbmZvcm1hbmNlYgZwcm90bzM="));
+ "ZRgEIAEoCRIwCg10ZXN0X2NhdGVnb3J5GAUgASgOMhkuY29uZm9ybWFuY2Uu",
+ "VGVzdENhdGVnb3J5QgkKB3BheWxvYWQisQEKE0NvbmZvcm1hbmNlUmVzcG9u",
+ "c2USFQoLcGFyc2VfZXJyb3IYASABKAlIABIZCg9zZXJpYWxpemVfZXJyb3IY",
+ "BiABKAlIABIXCg1ydW50aW1lX2Vycm9yGAIgASgJSAASGgoQcHJvdG9idWZf",
+ "cGF5bG9hZBgDIAEoDEgAEhYKDGpzb25fcGF5bG9hZBgEIAEoCUgAEhEKB3Nr",
+ "aXBwZWQYBSABKAlIAEIICgZyZXN1bHQqNQoKV2lyZUZvcm1hdBIPCgtVTlNQ",
+ "RUNJRklFRBAAEgwKCFBST1RPQlVGEAESCAoESlNPThACKmoKDFRlc3RDYXRl",
+ "Z29yeRIUChBVTlNQRUNJRklFRF9URVNUEAASDwoLQklOQVJZX1RFU1QQARIN",
+ "CglKU09OX1RFU1QQAhIkCiBKU09OX0lHTk9SRV9VTktOT1dOX1BBUlNJTkdf",
+ "VEVTVBADQiEKH2NvbS5nb29nbGUucHJvdG9idWYuY29uZm9ybWFuY2ViBnBy",
+ "b3RvMw=="));
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", "MessageType" }, new[]{ "Payload" }, null, null),
+ new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Conformance.WireFormat), typeof(global::Conformance.TestCategory), }, new pbr::GeneratedClrTypeInfo[] {
+ new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat", "MessageType", "TestCategory" }, 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)
}));
}
@@ -52,6 +56,26 @@ namespace Conformance {
[pbr::OriginalName("JSON")] Json = 2,
}
+ public enum TestCategory {
+ [pbr::OriginalName("UNSPECIFIED_TEST")] UnspecifiedTest = 0,
+ /// <summary>
+ /// Test binary wire format.
+ /// </summary>
+ [pbr::OriginalName("BINARY_TEST")] BinaryTest = 1,
+ /// <summary>
+ /// Test json wire format.
+ /// </summary>
+ [pbr::OriginalName("JSON_TEST")] JsonTest = 2,
+ /// <summary>
+ /// Similar to JSON_TEST. However, during parsing json, testee should ignore
+ /// unknown fields. This feature is optional. Each implementation can descide
+ /// whether to support it. See
+ /// https://developers.google.com/protocol-buffers/docs/proto3#json_options
+ /// for more detail.
+ /// </summary>
+ [pbr::OriginalName("JSON_IGNORE_UNKNOWN_PARSING_TEST")] JsonIgnoreUnknownParsingTest = 3,
+ }
+
#endregion
#region Messages
@@ -89,6 +113,7 @@ namespace Conformance {
public ConformanceRequest(ConformanceRequest other) : this() {
requestedOutputFormat_ = other.requestedOutputFormat_;
messageType_ = other.messageType_;
+ testCategory_ = other.testCategory_;
switch (other.PayloadCase) {
case PayloadOneofCase.ProtobufPayload:
ProtobufPayload = other.ProtobufPayload;
@@ -158,6 +183,22 @@ namespace Conformance {
}
}
+ /// <summary>Field number for the "test_category" field.</summary>
+ public const int TestCategoryFieldNumber = 5;
+ private global::Conformance.TestCategory testCategory_ = 0;
+ /// <summary>
+ /// Each test is given a specific test category. Some category may need
+ /// spedific support in testee programs. Refer to the defintion of TestCategory
+ /// for more information.
+ /// </summary>
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::Conformance.TestCategory TestCategory {
+ get { return testCategory_; }
+ set {
+ testCategory_ = value;
+ }
+ }
+
private object payload_;
/// <summary>Enum of possible cases for the "payload" oneof.</summary>
public enum PayloadOneofCase {
@@ -194,6 +235,7 @@ namespace Conformance {
if (JsonPayload != other.JsonPayload) return false;
if (RequestedOutputFormat != other.RequestedOutputFormat) return false;
if (MessageType != other.MessageType) return false;
+ if (TestCategory != other.TestCategory) return false;
if (PayloadCase != other.PayloadCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
@@ -205,6 +247,7 @@ namespace Conformance {
if (payloadCase_ == PayloadOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode();
if (RequestedOutputFormat != 0) hash ^= RequestedOutputFormat.GetHashCode();
if (MessageType.Length != 0) hash ^= MessageType.GetHashCode();
+ if (TestCategory != 0) hash ^= TestCategory.GetHashCode();
hash ^= (int) payloadCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
@@ -235,6 +278,10 @@ namespace Conformance {
output.WriteRawTag(34);
output.WriteString(MessageType);
}
+ if (TestCategory != 0) {
+ output.WriteRawTag(40);
+ output.WriteEnum((int) TestCategory);
+ }
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
@@ -255,6 +302,9 @@ namespace Conformance {
if (MessageType.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MessageType);
}
+ if (TestCategory != 0) {
+ size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) TestCategory);
+ }
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
@@ -272,6 +322,9 @@ namespace Conformance {
if (other.MessageType.Length != 0) {
MessageType = other.MessageType;
}
+ if (other.TestCategory != 0) {
+ TestCategory = other.TestCategory;
+ }
switch (other.PayloadCase) {
case PayloadOneofCase.ProtobufPayload:
ProtobufPayload = other.ProtobufPayload;
@@ -308,6 +361,10 @@ namespace Conformance {
MessageType = input.ReadString();
break;
}
+ case 40: {
+ testCategory_ = (global::Conformance.TestCategory) input.ReadEnum();
+ break;
+ }
}
}
}
diff --git a/csharp/src/Google.Protobuf.Conformance/Program.cs b/csharp/src/Google.Protobuf.Conformance/Program.cs
index 96dc354e..1eac00be 100644
--- a/csharp/src/Google.Protobuf.Conformance/Program.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Program.cs
@@ -87,6 +87,9 @@ namespace Google.Protobuf.Conformance
switch (request.PayloadCase)
{
case ConformanceRequest.PayloadOneofCase.JsonPayload:
+ if (request.TestCategory == global::Conformance.TestCategory.JsonIgnoreUnknownParsingTest) {
+ return new ConformanceResponse { Skipped = "CSharp doesn't support skipping unknown fields in json parsing." };
+ }
var parser = new JsonParser(new JsonParser.Settings(20, typeRegistry));
message = parser.Parse<ProtobufTestMessages.Proto3.TestAllTypesProto3>(request.JsonPayload);
break;
diff --git a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
index afdd491f..84e6341e 100755..100644
--- a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
+++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
@@ -227,7 +227,7 @@ namespace Google.Protobuf
{
// We used to have an awful hash algorithm where only the last four
// bytes were relevant. This is a regression test for
- // https://github.com/google/protobuf/issues/2511
+ // https://github.com/protocolbuffers/protobuf/issues/2511
ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4);
ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4);
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
index 8795fa65..8795fa65 100755..100644
--- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
+++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs
index 48c0725f..48c0725f 100755..100644
--- a/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Compatibility/StreamExtensionsTest.cs
diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
index abbe3c95..abbe3c95 100755..100644
--- a/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs
diff --git a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
index 77641163..77641163 100755..100644
--- a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
+++ b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs
diff --git a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
index 29a376e0..9abee951 100644
--- a/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
+++ b/csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs
@@ -30,10 +30,11 @@
// 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;
+using System;
+using System.Collections.Generic;
+using System.Linq;
namespace Google.Protobuf.Reflection
{
@@ -44,9 +45,32 @@ namespace Google.Protobuf.Reflection
public class DescriptorsTest
{
[Test]
- public void FileDescriptor()
+ public void FileDescriptor_GeneratedCode()
+ {
+ TestFileDescriptor(
+ UnittestProto3Reflection.Descriptor,
+ UnittestImportProto3Reflection.Descriptor,
+ UnittestImportPublicProto3Reflection.Descriptor);
+ }
+
+ [Test]
+ public void FileDescriptor_BuildFromByteStrings()
+ {
+ // The descriptors have to be supplied in an order such that all the
+ // dependencies come before the descriptors depending on them.
+ var descriptorData = new List<ByteString>
+ {
+ UnittestImportPublicProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestImportProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestProto3Reflection.Descriptor.Proto.ToByteString()
+ };
+ var converted = FileDescriptor.BuildFromByteStrings(descriptorData);
+ Assert.AreEqual(3, converted.Count);
+ TestFileDescriptor(converted[2], converted[1], converted[0]);
+ }
+
+ private void TestFileDescriptor(FileDescriptor file, FileDescriptor importedFile, FileDescriptor importedPublicFile)
{
- FileDescriptor file = UnittestProto3Reflection.Descriptor;
Assert.AreEqual("unittest_proto3.proto", file.Name);
Assert.AreEqual("protobuf_unittest3", file.Package);
@@ -56,17 +80,12 @@ namespace Google.Protobuf.Reflection
// 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]);
+ Assert.AreEqual(1, importedFile.PublicDependencies.Count);
+ Assert.AreEqual(importedPublicFile, importedFile.PublicDependencies[0]);
Assert.AreEqual(1, file.Dependencies.Count);
- Assert.AreEqual(UnittestImportProto3Reflection.Descriptor, file.Dependencies[0]);
+ Assert.AreEqual(importedFile, 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_unittest3.TestAllTypes"));
for (int i = 0; i < file.MessageTypes.Count; i++)
@@ -77,8 +96,8 @@ 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_unittest3.ForeignEnum"));
- Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.EnumTypes.Count);
- Assert.AreEqual("ImportEnum", UnittestImportProto3Reflection.Descriptor.EnumTypes[0].Name);
+ Assert.AreEqual(1, importedFile.EnumTypes.Count);
+ Assert.AreEqual("ImportEnum", importedFile.EnumTypes[0].Name);
for (int i = 0; i < file.EnumTypes.Count; i++)
{
Assert.AreEqual(i, file.EnumTypes[i].Index);
@@ -98,6 +117,56 @@ namespace Google.Protobuf.Reflection
}
[Test]
+ public void FileDescriptor_BuildFromByteStrings_MissingDependency()
+ {
+ var descriptorData = new List<ByteString>
+ {
+ UnittestImportProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestProto3Reflection.Descriptor.Proto.ToByteString(),
+ };
+ // This will fail, because we're missing UnittestImportPublicProto3Reflection
+ Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
+ }
+
+ [Test]
+ public void FileDescriptor_BuildFromByteStrings_DuplicateNames()
+ {
+ var descriptorData = new List<ByteString>
+ {
+ UnittestImportPublicProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestImportPublicProto3Reflection.Descriptor.Proto.ToByteString(),
+ };
+ // This will fail due to the same name being used twice
+ Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
+ }
+
+ [Test]
+ public void FileDescriptor_BuildFromByteStrings_IncorrectOrder()
+ {
+ var descriptorData = new List<ByteString>
+ {
+ UnittestProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestImportPublicProto3Reflection.Descriptor.Proto.ToByteString(),
+ UnittestImportProto3Reflection.Descriptor.Proto.ToByteString()
+ };
+ // This will fail, because the dependencies should come first
+ Assert.Throws<ArgumentException>(() => FileDescriptor.BuildFromByteStrings(descriptorData));
+
+ }
+
+ [Test]
+ public void MessageDescriptorFromGeneratedCodeFileDescriptor()
+ {
+ var file = UnittestProto3Reflection.Descriptor;
+
+ 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"));
+ }
+
+ [Test]
public void MessageDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
@@ -163,7 +232,7 @@ namespace Google.Protobuf.Reflection
Assert.AreEqual("single_nested_enum", enumField.Name);
Assert.AreEqual(FieldType.Enum, enumField.FieldType);
- // Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType);
+ Assert.AreEqual(messageType.EnumTypes[0], enumField.EnumType);
Assert.AreEqual("single_foreign_message", messageField.Name);
Assert.AreEqual(FieldType.Message, messageField.FieldType);
diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs
index 9ecd24c6..b8c07ef5 100644
--- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs
+++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/TimestampTest.cs
@@ -111,5 +111,106 @@ namespace Google.Protobuf.WellKnownTypes
var duration = new Timestamp { Seconds = 1, Nanos = -1 };
Assert.AreEqual("{ \"@warning\": \"Invalid Timestamp\", \"seconds\": \"1\", \"nanos\": -1 }", duration.ToString());
}
+
+ [Test]
+ public void Comparability()
+ {
+ Timestamp
+ a = null,
+ b = new Timestamp { Seconds = 1, Nanos = 1 },
+ c = new Timestamp { Seconds = 1, Nanos = 10 },
+ d = new Timestamp { Seconds = 10, Nanos = 1 },
+ e = new Timestamp { Seconds = 10, Nanos = 10 };
+
+ Assert.IsTrue(b.CompareTo(a) > 0); // null is always first (according to default behavior of Array.Sort)
+ Assert.IsTrue(b.CompareTo(b) == 0);
+ Assert.IsTrue(b.CompareTo(b.Clone()) == 0);
+ Assert.IsTrue(b.CompareTo(c) < 0);
+ Assert.IsTrue(b.CompareTo(d) < 0);
+ Assert.IsTrue(b.CompareTo(e) < 0);
+
+ Assert.IsTrue(c.CompareTo(a) > 0);
+ Assert.IsTrue(c.CompareTo(b) > 0);
+ Assert.IsTrue(c.CompareTo(c) == 0);
+ Assert.IsTrue(c.CompareTo(c.Clone()) == 0);
+ Assert.IsTrue(c.CompareTo(d) < 0);
+ Assert.IsTrue(c.CompareTo(e) < 0);
+
+ Assert.IsTrue(d.CompareTo(a) > 0);
+ Assert.IsTrue(d.CompareTo(b) > 0);
+ Assert.IsTrue(d.CompareTo(c) > 0);
+ Assert.IsTrue(d.CompareTo(d) == 0);
+ Assert.IsTrue(d.CompareTo(d.Clone()) == 0);
+ Assert.IsTrue(d.CompareTo(e) < 0);
+
+ Assert.IsTrue(e.CompareTo(a) > 0);
+ Assert.IsTrue(e.CompareTo(b) > 0);
+ Assert.IsTrue(e.CompareTo(c) > 0);
+ Assert.IsTrue(e.CompareTo(d) > 0);
+ Assert.IsTrue(e.CompareTo(e) == 0);
+ Assert.IsTrue(e.CompareTo(e.Clone()) == 0);
+ }
+
+
+ [Test]
+ public void ComparabilityOperators()
+ {
+ Timestamp
+ a = null,
+ b = new Timestamp { Seconds = 1, Nanos = 1 },
+ c = new Timestamp { Seconds = 1, Nanos = 10 },
+ d = new Timestamp { Seconds = 10, Nanos = 1 },
+ e = new Timestamp { Seconds = 10, Nanos = 10 };
+
+#pragma warning disable CS1718 // Comparison made to same variable
+ Assert.IsTrue(b > a);
+ Assert.IsTrue(b == b);
+ Assert.IsTrue(b == b.Clone());
+ Assert.IsTrue(b < c);
+ Assert.IsTrue(b < d);
+ Assert.IsTrue(b < e);
+
+ Assert.IsTrue(c > a);
+ Assert.IsTrue(c > b);
+ Assert.IsTrue(c == c);
+ Assert.IsTrue(c == c.Clone());
+ Assert.IsTrue(c < d);
+ Assert.IsTrue(c < e);
+
+ Assert.IsTrue(d > a);
+ Assert.IsTrue(d > b);
+ Assert.IsTrue(d > c);
+ Assert.IsTrue(d == d);
+ Assert.IsTrue(d == d.Clone());
+ Assert.IsTrue(d < e);
+
+ Assert.IsTrue(e > a);
+ Assert.IsTrue(e > b);
+ Assert.IsTrue(e > c);
+ Assert.IsTrue(e > d);
+ Assert.IsTrue(e == e);
+ Assert.IsTrue(e == e.Clone());
+
+ Assert.IsTrue(b >= a);
+ Assert.IsTrue(b <= c);
+ Assert.IsTrue(b <= d);
+ Assert.IsTrue(b <= e);
+
+ Assert.IsTrue(c >= a);
+ Assert.IsTrue(c >= b);
+ Assert.IsTrue(c <= d);
+ Assert.IsTrue(c <= e);
+
+ Assert.IsTrue(d >= a);
+ Assert.IsTrue(d >= b);
+ Assert.IsTrue(d >= c);
+ Assert.IsTrue(d <= e);
+
+ Assert.IsTrue(e >= a);
+ Assert.IsTrue(e >= b);
+ Assert.IsTrue(e >= c);
+ Assert.IsTrue(e >= d);
+#pragma warning restore CS1718 // Comparison made to same variable
+ }
}
}
diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs
index 4abdb718..4abdb718 100755..100644
--- a/csharp/src/Google.Protobuf/ByteString.cs
+++ b/csharp/src/Google.Protobuf/ByteString.cs
diff --git a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
index c18b63e2..c18b63e2 100755..100644
--- a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
+++ b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
diff --git a/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
index 95a02c72..95a02c72 100755..100644
--- a/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/PropertyInfoExtensions.cs
diff --git a/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs
index bf4bf220..bf4bf220 100755..100644
--- a/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/StreamExtensions.cs
diff --git a/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs b/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
index 2f237138..2f237138 100755..100644
--- a/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
+++ b/csharp/src/Google.Protobuf/Compatibility/TypeExtensions.cs
diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
index 11bc03d1..8ea3818a 100644
--- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj
+++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj
@@ -13,12 +13,10 @@
<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>
+ <PackageProjectUrl>https://github.com/protocolbuffers/protobuf</PackageProjectUrl>
+ <PackageLicenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</PackageLicenseUrl>
<RepositoryType>git</RepositoryType>
- <RepositoryUrl>https://github.com/google/protobuf.git</RepositoryUrl>
- <IncludeSymbols>true</IncludeSymbols>
- <IncludeSource>true</IncludeSource>
+ <RepositoryUrl>https://github.com/protocolbuffers/protobuf.git</RepositoryUrl>
</PropertyGroup>
<!--
@@ -30,4 +28,8 @@
<TargetFrameworks>netstandard1.0</TargetFrameworks>
</PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="SourceLink.Create.CommandLine" Version="2.7.6" PrivateAssets="All" />
+ </ItemGroup>
+
</Project>
diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs
index 4ae10d8b..4ae10d8b 100755..100644
--- a/csharp/src/Google.Protobuf/JsonFormatter.cs
+++ b/csharp/src/Google.Protobuf/JsonFormatter.cs
diff --git a/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs
index 99ca4bf3..9c2160fe 100644
--- a/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs
+++ b/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs
@@ -53,13 +53,13 @@ namespace Google.Protobuf.Reflection
private readonly HashSet<FileDescriptor> dependencies;
- internal DescriptorPool(FileDescriptor[] dependencyFiles)
+ internal DescriptorPool(IEnumerable<FileDescriptor> dependencyFiles)
{
dependencies = new HashSet<FileDescriptor>();
- for (int i = 0; i < dependencyFiles.Length; i++)
+ foreach (var dependencyFile in dependencyFiles)
{
- dependencies.Add(dependencyFiles[i]);
- ImportPublicDependencies(dependencyFiles[i]);
+ dependencies.Add(dependencyFile);
+ ImportPublicDependencies(dependencyFile);
}
foreach (FileDescriptor dependency in dependencyFiles)
diff --git a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
index 2a3d5c7a..152467d8 100644
--- a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
@@ -116,13 +116,18 @@ namespace Google.Protobuf.Reflection
/// that is the responsibility of the accessor.
/// </para>
/// <para>
- /// The value returned by this property will be non-null for all regular fields. However,
- /// if a message containing a map field is introspected, the list of nested messages will include
+ /// In descriptors for generated code, the value returned by this property will be non-null for all
+ /// regular fields. However, if a message containing a map field is introspected, the list of nested messages will include
/// an auto-generated nested key/value pair message for the field. This is not represented in any
/// generated type, and the value of the map field itself is represented by a dictionary in the
/// reflection API. There are never instances of those "hidden" messages, so no accessor is provided
/// and this property will return null.
/// </para>
+ /// <para>
+ /// In dynamically loaded descriptors, the value returned by this property will current be null;
+ /// if and when dynamic messages are supported, it will return a suitable accessor to work with
+ /// them.
+ /// </para>
/// </remarks>
public IFieldAccessor Accessor => accessor;
@@ -330,7 +335,8 @@ namespace Google.Protobuf.Reflection
private IFieldAccessor CreateAccessor()
{
// If we're given no property name, that's because we really don't want an accessor.
- // (At the moment, that means it's a map entry message...)
+ // This could be because it's a map message, or it could be that we're loading a FileDescriptor dynamically.
+ // TODO: Support dynamic messages.
if (propertyName == null)
{
return null;
diff --git a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
index be94cb10..799f7291 100644
--- a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
@@ -34,6 +34,7 @@ using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Linq;
namespace Google.Protobuf.Reflection
{
@@ -54,12 +55,12 @@ namespace Google.Protobuf.Reflection
ForceReflectionInitialization<Value.KindOneofCase>();
}
- private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
+ private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
SerializedData = descriptorData;
DescriptorPool = pool;
Proto = proto;
- Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
+ Dependencies = new ReadOnlyCollection<FileDescriptor>(dependencies.ToList());
PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
@@ -67,11 +68,11 @@ namespace Google.Protobuf.Reflection
MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
(message, index) =>
- new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
+ new MessageDescriptor(message, this, null, index, generatedCodeInfo?.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(enumType, index) =>
- new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
+ new EnumDescriptor(enumType, this, null, index, generatedCodeInfo?.NestedEnums[index]));
Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) =>
@@ -98,13 +99,9 @@ namespace Google.Protobuf.Reflection
/// Extracts public dependencies from direct dependencies. This is a static method despite its
/// first parameter, as the value we're in the middle of constructing is only used for exceptions.
/// </summary>
- private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
+ private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, IEnumerable<FileDescriptor> dependencies, bool allowUnknownDependencies)
{
- var nameToFileMap = new Dictionary<string, FileDescriptor>();
- foreach (var file in dependencies)
- {
- nameToFileMap[file.Name] = file;
- }
+ var nameToFileMap = dependencies.ToDictionary(file => file.Name);
var publicDependencies = new List<FileDescriptor>();
for (int i = 0; i < proto.PublicDependency.Count; i++)
{
@@ -114,8 +111,7 @@ namespace Google.Protobuf.Reflection
throw new DescriptorValidationException(@this, "Invalid public dependency index.");
}
string name = proto.Dependency[index];
- FileDescriptor file = nameToFileMap[name];
- if (file == null)
+ if (!nameToFileMap.TryGetValue(name, out var file))
{
if (!allowUnknownDependencies)
{
@@ -316,6 +312,49 @@ namespace Google.Protobuf.Reflection
}
/// <summary>
+ /// Converts the given descriptor binary data into FileDescriptor objects.
+ /// Note: reflection using the returned FileDescriptors is not currently supported.
+ /// </summary>
+ /// <param name="descriptorData">The binary file descriptor proto data. Must not be null, and any
+ /// dependencies must come before the descriptor which depends on them. (If A depends on B, and B
+ /// depends on C, then the descriptors must be presented in the order C, B, A.) This is compatible
+ /// with the order in which protoc provides descriptors to plugins.</param>
+ /// <returns>The file descriptors corresponding to <paramref name="descriptorData"/>.</returns>
+ public static IReadOnlyList<FileDescriptor> BuildFromByteStrings(IEnumerable<ByteString> descriptorData)
+ {
+ ProtoPreconditions.CheckNotNull(descriptorData, nameof(descriptorData));
+
+ // TODO: See if we can build a single DescriptorPool instead of building lots of them.
+ // This will all behave correctly, but it's less efficient than we'd like.
+ var descriptors = new List<FileDescriptor>();
+ var descriptorsByName = new Dictionary<string, FileDescriptor>();
+ foreach (var data in descriptorData)
+ {
+ var proto = FileDescriptorProto.Parser.ParseFrom(data);
+ var dependencies = new List<FileDescriptor>();
+ foreach (var dependencyName in proto.Dependency)
+ {
+ if (!descriptorsByName.TryGetValue(dependencyName, out var dependency))
+ {
+ throw new ArgumentException($"Dependency missing: {dependencyName}");
+ }
+ dependencies.Add(dependency);
+ }
+ var pool = new DescriptorPool(dependencies);
+ FileDescriptor descriptor = new FileDescriptor(
+ data, proto, dependencies, pool,
+ allowUnknownDependencies: false, generatedCodeInfo: null);
+ descriptors.Add(descriptor);
+ if (descriptorsByName.ContainsKey(descriptor.Name))
+ {
+ throw new ArgumentException($"Duplicate descriptor name: {descriptor.Name}");
+ }
+ descriptorsByName.Add(descriptor.Name, descriptor);
+ }
+ return new ReadOnlyCollection<FileDescriptor>(descriptors);
+ }
+
+ /// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
diff --git a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
index 86942acc..dbb6768b 100755..100644
--- a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs
@@ -72,23 +72,21 @@ namespace Google.Protobuf.Reflection
ClrType = generatedCodeInfo?.ClrType;
ContainingType = parent;
- // Note use of generatedCodeInfo. rather than generatedCodeInfo?. here... we don't expect
- // to see any nested oneofs, types or enums in "not actually generated" code... we do
- // expect fields though (for map entry messages).
+ // If generatedCodeInfo is null, we just won't generate an accessor for any fields.
Oneofs = DescriptorUtil.ConvertAndMakeReadOnly(
proto.OneofDecl,
(oneof, index) =>
- new OneofDescriptor(oneof, file, this, index, generatedCodeInfo.OneofNames[index]));
+ new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index]));
NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.NestedType,
(type, index) =>
- new MessageDescriptor(type, file, this, index, generatedCodeInfo.NestedTypes[index]));
+ new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.EnumType,
(type, index) =>
- new EnumDescriptor(type, file, this, index, generatedCodeInfo.NestedEnums[index]));
+ new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index]));
fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
proto.Field,
diff --git a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
index 5906c2e3..c026bea6 100644
--- a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs
@@ -85,6 +85,16 @@ namespace Google.Protobuf.Reflection
/// Gets an accessor for reflective access to the values associated with the oneof
/// in a particular message.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// In descriptors for generated code, the value returned by this property will always be non-null.
+ /// </para>
+ /// <para>
+ /// In dynamically loaded descriptors, the value returned by this property will current be null;
+ /// if and when dynamic messages are supported, it will return a suitable accessor to work with
+ /// them.
+ /// </para>
+ /// </remarks>
/// <value>
/// The accessor used for reflective access.
/// </value>
@@ -110,6 +120,12 @@ namespace Google.Protobuf.Reflection
private OneofAccessor CreateAccessor(string clrName)
{
+ // We won't have a CLR name if this is from a dynamically-loaded FileDescriptor.
+ // TODO: Support dynamic messages.
+ if (clrName == null)
+ {
+ return null;
+ }
var caseProperty = containingType.ClrType.GetProperty(clrName + "Case");
if (caseProperty == null)
{
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
index 378b61d4..dd991106 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
@@ -159,7 +159,8 @@ namespace Google.Protobuf.WellKnownTypes {
private string typeUrl_ = "";
/// <summary>
/// A URL/resource name that uniquely identifies the type of the serialized
- /// protocol buffer message. The last segment of the URL's path must represent
+ /// protocol buffer message. This string must contain at least
+ /// one "/" character. 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).
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
index b73930b2..6ad31a50 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
@@ -25,11 +25,11 @@ namespace Google.Protobuf.WellKnownTypes {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy",
- "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKJAQoTY29tLmdv",
+ "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUKMAQoTY29tLmdv",
"b2dsZS5wcm90b2J1ZkIORmllbGRNYXNrUHJvdG9QAVo5Z29vZ2xlLmdvbGFu",
"Zy5vcmcvZ2VucHJvdG8vcHJvdG9idWYvZmllbGRfbWFzaztmaWVsZF9tYXNr",
- "ogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90",
- "bzM="));
+ "+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZw",
+ "cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
@@ -108,57 +108,49 @@ namespace Google.Protobuf.WellKnownTypes {
/// 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 repeated field is specified for an update operation, new values will
+ /// be appended to the existing repeated field in the target resource. 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:
+ /// update operation, then new value will be merged into the existing sub-message
+ /// in the target resource.
+ ///
+ /// For example, given the target message:
///
/// f {
/// b {
- /// d : 1
- /// x : 2
+ /// d: 1
+ /// x: 2
/// }
- /// c : 1
+ /// c: [1]
/// }
///
/// And an update message:
///
/// f {
/// b {
- /// d : 10
+ /// d: 10
/// }
+ /// c: [2]
/// }
///
/// then if the field mask is:
///
- /// paths: "f.b"
+ /// paths: ["f.b", "f.c"]
///
/// then the result will be:
///
/// f {
/// b {
- /// d : 10
+ /// d: 10
+ /// x: 2
/// }
- /// c : 1
+ /// c: [1, 2]
/// }
///
- /// However, if the update mask was:
- ///
- /// paths: "f.b.d"
- ///
- /// then the result would be:
- ///
- /// f {
- /// b {
- /// d : 10
- /// x : 2
- /// }
- /// c : 1
- /// }
+ /// An implementation may provide options to override this default behavior for
+ /// repeated and message fields.
///
/// 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.
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
index 4b0670f6..4b0670f6 100755..100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
index ef752be7..d1ab0f89 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
@@ -116,7 +116,7 @@ namespace Google.Protobuf.WellKnownTypes {
/// 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--
+ /// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
/// ) to obtain a formatter capable of generating timestamps in this format.
/// </summary>
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs
index aa403473..a9251974 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs
@@ -36,7 +36,7 @@ using System.Text;
namespace Google.Protobuf.WellKnownTypes
{
- public partial class Timestamp : ICustomDiagnosticMessage
+ public partial class Timestamp : ICustomDiagnosticMessage, IComparable<Timestamp>
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
// Constants determined programmatically, but then hard-coded so they can be constant expressions.
@@ -223,6 +223,109 @@ namespace Google.Protobuf.WellKnownTypes
}
/// <summary>
+ /// Given another timestamp, returns 0 if the timestamps are equivalent, -1 if this timestamp precedes the other, and 1 otherwise
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="other">Timestamp to compare</param>
+ /// <returns>an integer indicating whether this timestamp precedes or follows the other</returns>
+ public int CompareTo(Timestamp other)
+ {
+ return other == null ? 1
+ : Seconds < other.Seconds ? -1
+ : Seconds > other.Seconds ? 1
+ : Nanos < other.Nanos ? -1
+ : Nanos > other.Nanos ? 1
+ : 0;
+ }
+
+ /// <summary>
+ /// Compares two timestamps and returns whether the first is less than (chronologically precedes) the second
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if a precedes b</returns>
+ public static bool operator <(Timestamp a, Timestamp b)
+ {
+ return a.CompareTo(b) < 0;
+ }
+
+ /// <summary>
+ /// Compares two timestamps and returns whether the first is greater than (chronologically follows) the second
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if a follows b</returns>
+ public static bool operator >(Timestamp a, Timestamp b)
+ {
+ return a.CompareTo(b) > 0;
+ }
+
+ /// <summary>
+ /// Compares two timestamps and returns whether the first is less than (chronologically precedes) the second
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if a precedes b</returns>
+ public static bool operator <=(Timestamp a, Timestamp b)
+ {
+ return a.CompareTo(b) <= 0;
+ }
+
+ /// <summary>
+ /// Compares two timestamps and returns whether the first is greater than (chronologically follows) the second
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if a follows b</returns>
+ public static bool operator >=(Timestamp a, Timestamp b)
+ {
+ return a.CompareTo(b) >= 0;
+ }
+
+
+ /// <summary>
+ /// Returns whether two timestamps are equivalent
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if the two timestamps refer to the same nanosecond</returns>
+ public static bool operator ==(Timestamp a, Timestamp b)
+ {
+ return ReferenceEquals(a, b) || (a is null ? (b is null ? true : false) : a.Equals(b));
+ }
+
+ /// <summary>
+ /// Returns whether two timestamps differ
+ /// </summary>
+ /// <remarks>
+ /// Make sure the timestamps are normalized. Comparing non-normalized timestamps is not specified and may give unexpected results.
+ /// </remarks>
+ /// <param name="a"></param>
+ /// <param name="b"></param>
+ /// <returns>true if the two timestamps differ</returns>
+ public static bool operator !=(Timestamp a, Timestamp b)
+ {
+ return !(a == b);
+ }
+
+ /// <summary>
/// Returns a string representation of this <see cref="Timestamp"/> for diagnostic purposes.
/// </summary>
/// <remarks>
diff --git a/docs/options.md b/docs/options.md
new file mode 100644
index 00000000..700fef60
--- /dev/null
+++ b/docs/options.md
@@ -0,0 +1,196 @@
+# Protobuf Global Extension Registry
+
+This file contains a global registry of known extensions for descriptor.proto,
+so that any developer who wishes to use multiple 3rd party projects, each with
+their own extensions, can be confident that there won't be collisions in
+extension numbers.
+
+If you need an extension number for your custom option (see [custom options](
+https://developers.google.com/protocol-buffers/docs/proto#customoptions)),
+please [send us a pull request](https://github.com/protocolbuffers/protobuf/pulls) to
+add an entry to this doc, or [create an issue](https://github.com/protocolbuffers/protobuf/issues)
+with info about your project (name and website) so we can add an entry for you.
+
+## Existing Registered Extensions
+
+1. C# port of protocol buffers
+ * Website: https://github.com/jskeet/protobuf-csharp-port
+ * Extensions: 1000
+
+1. Perl/XS port of protocol buffers
+ * Website: http://code.google.com/p/protobuf-perlxs
+ * Extensions: 1001
+
+1. Objective-C port of protocol buffers
+ * Website: http://code.google.com/p/protobuf-objc
+ * Extensions: 1002
+
+1. Google Wave Federation Protocol open-source release (FedOne)
+ * Website: http://code.google.com/p/wave-protocol
+ * Extensions: 1003
+
+1. PHP code generator plugin
+ * Website: ???
+ * Extensions: 1004
+
+1. GWT code generator plugin (third-party!)
+ * Website: http://code.google.com/p/protobuf-gwt/
+ * Extensions: 1005
+
+1. Unix Domain RPC code generator plugin
+ * Website: http://go/udrpc
+ * Extensions: 1006
+
+1. Object-C generator plugin (Plausible Labs)
+ * Website: http://www.plausible.coop
+ * Extensions: 1007
+
+1. TBD (code42.com)
+ * Website: ???
+ * Extensions: 1008
+
+1. Goby Underwater Autonomy Project
+ * Website: https://github.com/GobySoft/goby
+ * Extensions: 1009
+
+1. Nanopb
+ * Website: http://kapsi.fi/~jpa/nanopb
+ * Extensions: 1010
+
+1. Bluefin AUV Communication Extensions
+ * Website: http://www.bluefinrobotics.com
+ * Extensions: 1011
+
+1. Dynamic Compact Control Language
+ * Website: http://github.com/GobySoft/dccl
+ * Extensions: 1012
+
+1. ScaleOut StateServer® Native C++ API
+ * Website: http://www.scaleoutsoftware.com
+ * Extensions: 1013
+
+1. FoundationDB SQL Layer
+ * Website: https://github.com/FoundationDB/sql-layer
+ * Extensions: 1014
+
+1. Fender
+ * Website: https://github.com/hassox/fender
+ * Extensions: 1015
+
+1. Vortex
+ * Website: http://www.prismtech.com/vortex
+ * Extensions: 1016
+
+1. tresorit
+ * Website: https://tresorit.com/
+ * Extensions: 1017
+
+1. CRIU (Checkpoint Restore In Userspace)
+ * Website: http://criu.org/Main_Page
+ * Extensions: 1018
+
+1. protobuf-c
+ * Website: https://github.com/protobuf-c/protobuf-c
+ * Extensions: 1019
+
+1. ScalePB
+ * Website: http://trueaccord.github.io/ScalaPB/
+ * Extensions: 1020
+
+1. protoc-gen-bq-schema
+ * Website: https://github.com/GoogleCloudPlatform/protoc-gen-bq-schema
+ * Extensions: 1021
+
+1. grpc-gateway
+ * Website: https://github.com/gengo/grpc-gateway
+ * Extensions: 1022
+
+1. Certificate Transparency
+ * Website: https://github.com/google/certificate-transparency
+ * Extensions: 1023
+
+1. JUNOS Router Telemetry
+ * Website: http://www.juniper.net
+ * Extensions: 1024
+
+1. Spine Event Engine
+ * Website: https://github.com/SpineEventEngine/core-java
+ * Extensions: 1025
+
+1. Aruba cloud platform
+ * Website: ???
+ * Extensions: 1026 -> 1030
+
+1. Voltha
+ * Website: ???
+ * Extensions: 1031 -> 1033
+
+1. gator
+ * Website: ???
+ * Extensions: 1034
+
+1. protoc-gen-flowtypes
+ * Website: https://github.com/tmc/grpcutil/tree/master/protoc-gen-flowtypes
+ * Extensions: 1035
+
+1. ProfaneDB
+ * Website: https://gitlab.com/ProfaneDB/ProfaneDB
+ * Extensions: 1036
+
+1. protobuf-net
+ * Website: https://github.com/mgravell/protobuf-net
+ * Extensions: 1037
+
+1. FICO / StreamEngine
+ * Website: http://www.fico.com/
+ * Extensions: 1038
+
+1. GopherJS
+ * Website: https://github.com/johanbrandhorst/protobuf
+ * Extensions: 1039
+
+1. ygot
+ * Website: https://github.com/openconfig/ygot
+ * Extensions: 1040
+
+1. go-grpcmw
+ * Website: https://github.com/MarquisIO/go-grpcmw
+ * Extensions: 1041
+
+1. grpc-gateway protoc-gen-swagger
+ * Website: https://github.com/grpc-ecosystem/grpc-gateway
+ * Extensions: 1042
+
+1. AN Message
+ * Website: TBD
+ * Extensions: 1043
+
+1. protofire
+ * Website: https://github.com/ribrdb/protofire
+ * Extensions: 1044
+
+1. Gravity
+ * Website: https://github.com/aphysci/gravity
+ * Extensions: 1045
+
+1. SEMI Standards – I&C Technical Committee
+ * Website: http://downloads.semi.org/web/wstdsbal.nsf/9c2b317e76523cca88257641005a47f5/88a5863a580e323088256e7b00707489!OpenDocument
+ * Extensions: 1046
+
+1. Elixir plugin
+ * Website: https://github.com/tony612/grpc-elixir
+ * Extensions: 1047
+
+1. API client generators
+ * Website: ???
+ * Extensions: 1048-1056
+
+1. Netifi Proteus
+ * Website: https://github.com/netifi-proteus
+ * Extensions: 1057
+
+1. CGSN Mooring Project
+ * Website: https://bitbucket.org/ooicgsn/cgsn-mooring
+ * Extensions: 1058
+
+
diff --git a/docs/performance.md b/docs/performance.md
index 6a5316c8..065a361a 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -1,4 +1,4 @@
-# Protobuf Perforamcne
+# Protobuf Performance
This benchmark result is tested on workstation with processor of Intel® Xeon® Processor E5-2630 and 32GB RAM
This table contains 3 languages' results:
@@ -301,4 +301,4 @@ This table contains 3 languages' results:
</tr>
</tbody></table>
-\* The cpp performance can be improved by using [tcmalloc](https://gperftools.github.io/gperftools/tcmalloc.html), please follow the (instruction)[https://github.com/google/protobuf/blob/master/benchmarks/README.md] to link with tcmalloc to get the faster result.
+\* The cpp performance can be improved by using [tcmalloc](https://gperftools.github.io/gperftools/tcmalloc.html), please follow the (instruction)[https://github.com/protocolbuffers/protobuf/blob/master/benchmarks/README.md] to link with tcmalloc to get the faster result.
diff --git a/docs/third_party.md b/docs/third_party.md
index 3f267dde..f710b51a 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -23,8 +23,10 @@ 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
+* Clojure: https://github.com/clojusc/protobuf
* Common Lisp: http://github.com/ndantam/s-protobuf
* Common Lisp: http://github.com/brown/protobuf
+* D: https://github.com/dcarp/protobuf-d
* D: https://github.com/msoucy/dproto
* D: http://256.makerslocal.org/wiki/index.php/ProtocolBuffer
* D: https://github.com/opticron/ProtocolBuffer
@@ -39,6 +41,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Erlang: https://code.google.com/p/protoc-gen-erl/
* Erlang: https://github.com/basho/erlang_protobuffs
* Erlang: https://github.com/tomas-abrahamsson/gpb
+* GDScript: https://github.com/oniksan/godobuf (Godot v3 engine plugin)
* Go: https://github.com/golang/protobuf (Google-official implementation)
* Go: https://github.com/akunspy/gopbuf
* Go: https://github.com/gogo/protobuf
@@ -87,7 +90,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Scala: http://github.com/jeffplaisance/scala-protobuf
* Scala: http://code.google.com/p/protobuf-scala
* Scala: https://github.com/SandroGrzicic/ScalaBuff
-* Scala: http://trueaccord.github.io/ScalaPB/
+* Scala: https://scalapb.github.io
* Swift: https://github.com/alexeyxo/protobuf-swift
* Swift: https://github.com/apple/swift-protobuf/
* Vala: https://launchpad.net/protobuf-vala
@@ -125,6 +128,8 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* https://github.com/johanbrandhorst/protobuf (GopherJS)
* https://github.com/awakesecurity/gRPC-haskell (Haskell)
* https://github.com/Yeolar/raster (C++)
+* https://github.com/jnordberg/wsrpc (JavaScript Node.js/Browser)
+* https://github.com/ppissias/xsrpcj (Java)
## Other Utilities
diff --git a/examples/WORKSPACE b/examples/WORKSPACE
index 153a5932..5884354a 100644
--- a/examples/WORKSPACE
+++ b/examples/WORKSPACE
@@ -3,7 +3,7 @@
http_archive(
name = "com_google_protobuf",
strip_prefix = "protobuf-master",
- urls = ["https://github.com/google/protobuf/archive/master.zip"],
+ urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"],
)
# This com_google_protobuf_cc repository is required for cc_proto_library
@@ -13,14 +13,14 @@ http_archive(
http_archive(
name = "com_google_protobuf_cc",
strip_prefix = "protobuf-master",
- urls = ["https://github.com/google/protobuf/archive/master.zip"],
+ urls = ["https://github.com/protocolbuffers/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"],
+ urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"],
)
# Similar to com_google_protobuf_cc but for Java lite. If you are building
@@ -29,7 +29,7 @@ http_archive(
http_archive(
name = "com_google_protobuf_javalite",
strip_prefix = "protobuf-javalite",
- urls = ["https://github.com/google/protobuf/archive/javalite.zip"],
+ urls = ["https://github.com/protocolbuffers/protobuf/archive/javalite.zip"],
)
http_archive(
diff --git a/examples/add_person.go b/examples/add_person.go
index 4f2e7f74..7ffb0ab0 100644
--- a/examples/add_person.go
+++ b/examples/add_person.go
@@ -10,7 +10,7 @@ import (
"strings"
"github.com/golang/protobuf/proto"
- pb "github.com/google/protobuf/examples/tutorial"
+ pb "github.com/protocolbuffers/protobuf/examples/tutorial"
)
func promptForAddress(r io.Reader) (*pb.Person, error) {
diff --git a/examples/add_person_test.go b/examples/add_person_test.go
index f8ba9338..d35f10ec 100644
--- a/examples/add_person_test.go
+++ b/examples/add_person_test.go
@@ -5,7 +5,7 @@ import (
"testing"
"github.com/golang/protobuf/proto"
- pb "github.com/google/protobuf/examples/tutorial"
+ pb "github.com/protocolbuffers/protobuf/examples/tutorial"
)
func TestPromptForAddressReturnsAddress(t *testing.T) {
diff --git a/examples/list_people.go b/examples/list_people.go
index 70bc589e..6c2c34ac 100644
--- a/examples/list_people.go
+++ b/examples/list_people.go
@@ -8,7 +8,7 @@ import (
"os"
"github.com/golang/protobuf/proto"
- pb "github.com/google/protobuf/examples/tutorial"
+ pb "github.com/protocolbuffers/protobuf/examples/tutorial"
)
func writePerson(w io.Writer, p *pb.Person) {
diff --git a/examples/list_people_test.go b/examples/list_people_test.go
index 887997fe..64ea4278 100644
--- a/examples/list_people_test.go
+++ b/examples/list_people_test.go
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
- pb "github.com/google/protobuf/examples/tutorial"
+ pb "github.com/protocolbuffers/protobuf/examples/tutorial"
)
func TestWritePersonWritesPerson(t *testing.T) {
diff --git a/generate_changelog.py b/generate_changelog.py
index d90a9b70..60803c59 100755
--- a/generate_changelog.py
+++ b/generate_changelog.py
@@ -20,11 +20,10 @@ languages = [
]),
Language("Java", [
"java",
- "javanano",
- "src/google/protobuf/compiler/cpp",
+ "src/google/protobuf/compiler/java",
]),
Language("Python", [
- "javanano",
+ "python",
"src/google/protobuf/compiler/python",
]),
Language("JavaScript", [
@@ -63,4 +62,4 @@ for language in languages:
print("")
print("To view a commit on GitHub: " +
- "https://github.com/google/protobuf/commit/<commit id>")
+ "https://github.com/protocolbuffers/protobuf/commit/<commit id>")
diff --git a/generate_descriptor_proto.sh b/generate_descriptor_proto.sh
index 8a5ed48a..e533d05b 100755
--- a/generate_descriptor_proto.sh
+++ b/generate_descriptor_proto.sh
@@ -18,14 +18,6 @@ __EOF__
exit 1
fi
-if test ! -e src/Makefile; then
- cat >&2 << __EOF__
-Could not find src/Makefile. You must run ./configure (and perhaps
-./autogen.sh) first.
-__EOF__
- exit 1
-fi
-
cd src
declare -a RUNTIME_PROTO_FILES=(\
@@ -51,7 +43,7 @@ while [ $# -gt 0 ]; do
case $1 in
--bootstrap_protoc)
BOOTSTRAP_PROTOC=$2
- shift
+ shift 2
;;
*)
break
@@ -78,8 +70,8 @@ do
PROTOC="./protoc"
fi
- $PROTOC --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \
- $PROTOC --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]}
+ $PROTOC --cpp_out=dllexport_decl=PROTOBUF_EXPORT:$TMP ${RUNTIME_PROTO_FILES[@]} && \
+ $PROTOC --cpp_out=dllexport_decl=PROTOC_EXPORT:$TMP ${COMPILER_PROTO_FILES[@]}
for PROTO_FILE in ${RUNTIME_PROTO_FILES[@]} ${COMPILER_PROTO_FILES[@]}; do
BASE_NAME=${PROTO_FILE%.*}
diff --git a/java/README.md b/java/README.md
index 5e4fb8b4..def4fd9a 100644
--- a/java/README.md
+++ b/java/README.md
@@ -13,13 +13,17 @@ generate Java code for your .proto files:
$ protoc --java_out=${OUTPUT_DIR} path/to/your/proto/file
Include the generated Java files in your project and add a dependency on the
-protobuf Java runtime. If you are using Maven, use the following:
+protobuf Java runtime.
+
+### Maven
+
+If you are using Maven, use the following:
```xml
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
- <version>3.5.1</version>
+ <version>3.6.1</version>
</dependency>
```
@@ -33,10 +37,18 @@ protobuf-java-util package:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
- <version>3.5.1</version>
+ <version>3.6.1</version>
</dependency>
```
+### Gradle
+
+If you are using Gradle, add the following to your `build.gradle` file's dependencies:
+```
+ compile 'com.google.protobuf:protobuf-java:3.6.1'
+```
+Again, be sure to check that the version number maches (or is newer than) the version number of protoc that you are using.
+
### Use Java Protocol Buffers on Android
For Android users, it's recommended to use protobuf Java Lite runtime because
diff --git a/java/compatibility_tests/v2.5.0/test.sh b/java/compatibility_tests/v2.5.0/test.sh
index 5d5e9ed4..2ea5b930 100755
--- a/java/compatibility_tests/v2.5.0/test.sh
+++ b/java/compatibility_tests/v2.5.0/test.sh
@@ -65,7 +65,7 @@ echo "Running compatibility tests between $VERSION_NUMBER and $OLD_VERSION"
# Download old version source for the compatibility test
[ -d protobuf ] || {
- git clone https://github.com/google/protobuf.git
+ git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git reset --hard v$TEST_VERSION
cd ..
diff --git a/java/core/pom.xml b/java/core/pom.xml
index 067749c6..9dbaff15 100644
--- a/java/core/pom.xml
+++ b/java/core/pom.xml
@@ -34,6 +34,11 @@
<artifactId>easymockclassextension</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
@@ -57,6 +62,15 @@
</includes>
</resource>
</resources>
+ <testResources>
+ <testResource>
+ <directory>${protobuf.source.dir}</directory>
+ <includes>
+ <include>google/protobuf/testdata/golden_message_oneof_implemented</include>
+ <include>google/protobuf/testdata/golden_packed_fields_message</include>
+ </includes>
+ </testResource>
+ </testResources>
<plugins>
<!-- Use Antrun plugin to generate sources with protoc -->
@@ -135,6 +149,7 @@
<Bundle-DocURL>https://developers.google.com/protocol-buffers/</Bundle-DocURL>
<Bundle-SymbolicName>com.google.protobuf</Bundle-SymbolicName>
<Export-Package>com.google.protobuf;version=${project.version}</Export-Package>
+ <Import-Package>sun.misc;resolution:=optional,*</Import-Package>
</instructions>
</configuration>
</plugin>
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 fc3c2a5d..fe1bebc7 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
@@ -32,7 +32,6 @@ 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;
@@ -45,15 +44,14 @@ import java.util.List;
import java.util.Map;
/**
- * A partial implementation of the {@link Message} interface which implements
- * as many methods of that interface as possible in terms of other methods.
+ * A partial implementation of the {@link Message} interface which implements as many methods of
+ * that interface as possible in terms of other methods.
*
* @author kenton@google.com Kenton Varda
*/
public abstract class AbstractMessage
// TODO(dweis): Update GeneratedMessage to parameterize with MessageType and BuilderType.
- extends AbstractMessageLite
- implements Message {
+ extends AbstractMessageLite implements Message {
@Override
public boolean isInitialized() {
@@ -61,24 +59,21 @@ public abstract class AbstractMessage
}
/**
- * Interface for the parent of a Builder that allows the builder to
- * communicate invalidations back to the parent for use when using nested
- * builders.
+ * Interface for the parent of a Builder that allows the builder to communicate invalidations back
+ * to the parent for use when using nested builders.
*/
protected interface BuilderParent {
/**
- * A builder becomes dirty whenever a field is modified -- including fields
- * in nested builders -- and becomes clean when build() is called. Thus,
- * when a builder becomes dirty, all its parents become dirty as well, and
- * when it becomes clean, all its children become clean. The dirtiness
- * state is used to invalidate certain cached values.
- * <br>
- * To this end, a builder calls markDirty() on its parent whenever it
- * transitions from clean to dirty. The parent must propagate this call to
- * its own parent, unless it was already dirty, in which case the
- * grandparent must necessarily already be dirty as well. The parent can
- * only transition back to "clean" after calling build() on all children.
+ * A builder becomes dirty whenever a field is modified -- including fields in nested builders
+ * -- and becomes clean when build() is called. Thus, when a builder becomes dirty, all its
+ * parents become dirty as well, and when it becomes clean, all its children become clean. The
+ * dirtiness state is used to invalidate certain cached values.
+ *
+ * <p>To this end, a builder calls markDirty() on its parent whenever it transitions from clean
+ * to dirty. The parent must propagate this call to its own parent, unless it was already dirty,
+ * in which case the grandparent must necessarily already be dirty as well. The parent can only
+ * transition back to "clean" after calling build() on all children.
*/
void markDirty();
}
@@ -108,8 +103,7 @@ public abstract class AbstractMessage
/** TODO(jieluo): Clear it when all subclasses have implemented this method. */
@Override
public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) {
- throw new UnsupportedOperationException(
- "getOneofFieldDescriptor() is not implemented.");
+ throw new UnsupportedOperationException("getOneofFieldDescriptor() is not implemented.");
}
@Override
@@ -157,8 +151,8 @@ public abstract class AbstractMessage
if (getDescriptorForType() != otherMessage.getDescriptorForType()) {
return false;
}
- return compareFields(getAllFields(), otherMessage.getAllFields()) &&
- getUnknownFields().equals(otherMessage.getUnknownFields());
+ return compareFields(getAllFields(), otherMessage.getAllFields())
+ && getUnknownFields().equals(otherMessage.getUnknownFields());
}
@Override
@@ -183,20 +177,17 @@ public abstract class AbstractMessage
}
/**
- * Compares two bytes fields. The parameters must be either a byte array or a
- * ByteString object. They can be of different type though.
+ * Compares two bytes fields. The parameters must be either a byte array or a ByteString object.
+ * They can be of different type though.
*/
private static boolean compareBytes(Object a, Object b) {
if (a instanceof byte[] && b instanceof byte[]) {
- return Arrays.equals((byte[])a, (byte[])b);
+ return Arrays.equals((byte[]) a, (byte[]) b);
}
return toByteString(a).equals(toByteString(b));
}
- /**
- * Converts a list of MapEntry messages into a Map used for equals() and
- * hashCode().
- */
+ /** Converts a list of MapEntry messages into a Map used for equals() and hashCode(). */
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map convertMapEntryListToMap(List list) {
if (list.isEmpty()) {
@@ -224,10 +215,7 @@ public abstract class AbstractMessage
return result;
}
- /**
- * Compares two map fields. The parameters must be a list of MapEntry
- * messages.
- */
+ /** Compares two map fields. The parameters must be a list of MapEntry messages. */
@SuppressWarnings({"rawtypes", "unchecked"})
private static boolean compareMapField(Object a, Object b) {
Map ma = convertMapEntryListToMap((List) a);
@@ -236,16 +224,13 @@ public abstract class AbstractMessage
}
/**
- * 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 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.
+ * 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 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.
*/
- static boolean compareFields(Map<FieldDescriptor, Object> a,
- Map<FieldDescriptor, Object> b) {
+ static boolean compareFields(Map<FieldDescriptor, Object> a, Map<FieldDescriptor, Object> b) {
if (a.size() != b.size()) {
return false;
}
@@ -287,10 +272,7 @@ public abstract class AbstractMessage
return true;
}
- /**
- * Calculates the hash code of a map field. {@code value} must be a list of
- * MapEntry messages.
- */
+ /** Calculates the hash code of a map field. {@code value} must be a list of MapEntry messages. */
@SuppressWarnings("unchecked")
private static int hashMapField(Object value) {
return MapFieldLite.calculateHashCodeForMap(convertMapEntryListToMap((List) value));
@@ -305,7 +287,7 @@ public abstract class AbstractMessage
hash = (37 * hash) + field.getNumber();
if (field.isMapField()) {
hash = (53 * hash) + hashMapField(value);
- } else if (field.getType() != FieldDescriptor.Type.ENUM){
+ } else if (field.getType() != FieldDescriptor.Type.ENUM) {
hash = (53 * hash) + value.hashCode();
} else if (field.isRepeated()) {
List<? extends EnumLite> list = (List<? extends EnumLite>) value;
@@ -318,8 +300,8 @@ public abstract class AbstractMessage
}
/**
- * Package private helper method for AbstractParser to create
- * UninitializedMessageException with missing field information.
+ * Package private helper method for AbstractParser to create UninitializedMessageException with
+ * missing field information.
*/
@Override
UninitializedMessageException newUninitializedMessageException() {
@@ -329,14 +311,12 @@ public abstract class AbstractMessage
// =================================================================
/**
- * A partial implementation of the {@link Message.Builder} interface which
- * implements as many methods of that interface as possible in terms of
- * other methods.
+ * A partial implementation of the {@link Message.Builder} interface which implements as many
+ * methods of that interface as possible in terms of other methods.
*/
@SuppressWarnings("unchecked")
- public static abstract class Builder<BuilderType extends Builder<BuilderType>>
- extends AbstractMessageLite.Builder
- implements Message.Builder {
+ public abstract static class Builder<BuilderType extends Builder<BuilderType>>
+ 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
@@ -354,8 +334,7 @@ public abstract class AbstractMessage
/** TODO(jieluo): Clear it when all subclasses have implemented this method. */
@Override
public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) {
- throw new UnsupportedOperationException(
- "getOneofFieldDescriptor() is not implemented.");
+ throw new UnsupportedOperationException("getOneofFieldDescriptor() is not implemented.");
}
/** TODO(jieluo): Clear it when all subclasses have implemented this method. */
@@ -366,8 +345,7 @@ public abstract class AbstractMessage
@Override
public BuilderType clear() {
- for (final Map.Entry<FieldDescriptor, Object> entry :
- getAllFields().entrySet()) {
+ for (final Map.Entry<FieldDescriptor, Object> entry : getAllFields().entrySet()) {
clearField(entry.getKey());
}
return (BuilderType) this;
@@ -392,11 +370,11 @@ public abstract class AbstractMessage
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.");
+ "mergeFrom(Message) can only merge messages of the same type.");
}
// Note: We don't attempt to verify that other's fields have valid
@@ -411,19 +389,21 @@ public abstract class AbstractMessage
for (final Map.Entry<FieldDescriptor, Object> entry : allFields.entrySet()) {
final FieldDescriptor field = entry.getKey();
if (field.isRepeated()) {
- for (final Object element : (List)entry.getValue()) {
+ for (final Object element : (List) entry.getValue()) {
addRepeatedField(field, element);
}
} else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
- final Message existingValue = (Message)getField(field);
+ final Message existingValue = (Message) getField(field);
if (existingValue == existingValue.getDefaultInstanceForType()) {
setField(field, entry.getValue());
} else {
- setField(field,
- existingValue.newBuilderForType()
- .mergeFrom(existingValue)
- .mergeFrom((Message)entry.getValue())
- .build());
+ setField(
+ field,
+ existingValue
+ .newBuilderForType()
+ .mergeFrom(existingValue)
+ .mergeFrom((Message) entry.getValue())
+ .build());
}
} else {
setField(field, entry.getValue());
@@ -436,20 +416,15 @@ public abstract class AbstractMessage
}
@Override
- public BuilderType mergeFrom(final CodedInputStream input)
- throws IOException {
+ public BuilderType mergeFrom(final CodedInputStream input) throws IOException {
return mergeFrom(input, ExtensionRegistry.getEmptyRegistry());
}
@Override
public BuilderType mergeFrom(
- final CodedInputStream input,
- final ExtensionRegistryLite extensionRegistry)
+ final CodedInputStream input, final ExtensionRegistryLite extensionRegistry)
throws IOException {
- boolean discardUnknown =
- getDescriptorForType().getFile().getSyntax() == Syntax.PROTO3
- ? input.shouldDiscardUnknownFieldsProto3()
- : input.shouldDiscardUnknownFields();
+ boolean discardUnknown = input.shouldDiscardUnknownFields();
final UnknownFieldSet.Builder unknownFields =
discardUnknown ? null : UnknownFieldSet.newBuilder(getUnknownFields());
while (true) {
@@ -460,11 +435,8 @@ public abstract class AbstractMessage
MessageReflection.BuilderAdapter builderAdapter =
new MessageReflection.BuilderAdapter(this);
- if (!MessageReflection.mergeFieldFrom(input, unknownFields,
- extensionRegistry,
- getDescriptorForType(),
- builderAdapter,
- tag)) {
+ if (!MessageReflection.mergeFieldFrom(
+ input, unknownFields, extensionRegistry, getDescriptorForType(), builderAdapter, tag)) {
// end group tag
break;
}
@@ -478,9 +450,7 @@ public abstract class AbstractMessage
@Override
public BuilderType mergeUnknownFields(final UnknownFieldSet unknownFields) {
setUnknownFields(
- UnknownFieldSet.newBuilder(getUnknownFields())
- .mergeFrom(unknownFields)
- .build());
+ UnknownFieldSet.newBuilder(getUnknownFields()).mergeFrom(unknownFields).build());
return (BuilderType) this;
}
@@ -501,36 +471,30 @@ public abstract class AbstractMessage
return TextFormat.printToString(this);
}
- /**
- * Construct an UninitializedMessageException reporting missing fields in
- * the given message.
- */
- protected static UninitializedMessageException
- newUninitializedMessageException(Message message) {
- return new UninitializedMessageException(
- MessageReflection.findMissingFields(message));
+ /** Construct an UninitializedMessageException reporting missing fields in the given message. */
+ protected static UninitializedMessageException newUninitializedMessageException(
+ Message message) {
+ return new UninitializedMessageException(MessageReflection.findMissingFields(message));
}
/**
- * Used to support nested builders and called to mark this builder as clean.
- * Clean builders will propagate the {@link BuilderParent#markDirty()} event
- * to their parent builders, while dirty builders will not, as their parents
- * should be dirty already.
+ * Used to support nested builders and called to mark this builder as clean. Clean builders will
+ * propagate the {@link BuilderParent#markDirty()} event to their parent builders, while dirty
+ * builders will not, as their parents should be dirty already.
*
- * NOTE: Implementations that don't support nested builders don't need to
- * override this method.
+ * <p>NOTE: Implementations that don't support nested builders don't need to override this
+ * method.
*/
void markClean() {
throw new IllegalStateException("Should be overridden by subclasses.");
}
/**
- * Used to support nested builders and called when this nested builder is
- * no longer used by its parent builder and should release the reference
- * to its parent builder.
+ * Used to support nested builders and called when this nested builder is no longer used by its
+ * parent builder and should release the reference to its parent builder.
*
- * NOTE: Implementations that don't support nested builders don't need to
- * override this method.
+ * <p>NOTE: Implementations that don't support nested builders don't need to override this
+ * method.
*/
void dispose() {
throw new IllegalStateException("Should be overridden by subclasses.");
@@ -556,73 +520,63 @@ public abstract class AbstractMessage
// bug.
@Override
- public BuilderType mergeFrom(final ByteString data)
- throws InvalidProtocolBufferException {
+ public BuilderType mergeFrom(final ByteString data) throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data);
}
@Override
public BuilderType mergeFrom(
- final ByteString data,
- final ExtensionRegistryLite extensionRegistry)
+ final ByteString data, final ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data, extensionRegistry);
}
@Override
- public BuilderType mergeFrom(final byte[] data)
- throws InvalidProtocolBufferException {
+ public BuilderType mergeFrom(final byte[] data) throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data);
}
@Override
- public BuilderType mergeFrom(
- final byte[] data, final int off, final int len)
+ public BuilderType mergeFrom(final byte[] data, final int off, final int len)
throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data, off, len);
}
@Override
- public BuilderType mergeFrom(
- final byte[] data,
- final ExtensionRegistryLite extensionRegistry)
+ public BuilderType mergeFrom(final byte[] data, final ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data, extensionRegistry);
}
@Override
public BuilderType mergeFrom(
- final byte[] data, final int off, final int len,
+ final byte[] data,
+ final int off,
+ final int len,
final ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
return (BuilderType) super.mergeFrom(data, off, len, extensionRegistry);
}
@Override
- public BuilderType mergeFrom(final InputStream input)
- throws IOException {
+ public BuilderType mergeFrom(final InputStream input) throws IOException {
return (BuilderType) super.mergeFrom(input);
}
@Override
public BuilderType mergeFrom(
- final InputStream input,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
+ final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException {
return (BuilderType) super.mergeFrom(input, extensionRegistry);
}
@Override
- public boolean mergeDelimitedFrom(final InputStream input)
- throws IOException {
+ public boolean mergeDelimitedFrom(final InputStream input) throws IOException {
return super.mergeDelimitedFrom(input);
}
@Override
public boolean mergeDelimitedFrom(
- final InputStream input,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
+ final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException {
return super.mergeDelimitedFrom(input, extensionRegistry);
}
}
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 b22bbaab..17205750 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractMessageLite.java
@@ -41,22 +41,20 @@ import java.util.Collection;
import java.util.List;
/**
- * A partial implementation of the {@link MessageLite} interface which
- * implements as many methods of that interface as possible in terms of other
- * methods.
+ * A partial implementation of the {@link MessageLite} interface which implements as many methods of
+ * that interface as possible in terms of other methods.
*
* @author kenton@google.com Kenton Varda
*/
public abstract class AbstractMessageLite<
- MessageType extends AbstractMessageLite<MessageType, BuilderType>,
- BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>>
- implements MessageLite {
+ MessageType extends AbstractMessageLite<MessageType, BuilderType>,
+ BuilderType extends AbstractMessageLite.Builder<MessageType, BuilderType>>
+ implements MessageLite {
protected int memoizedHashCode = 0;
@Override
public ByteString toByteString() {
try {
- final ByteString.CodedBuilder out =
- ByteString.newCodedBuilder(getSerializedSize());
+ final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize());
writeTo(out.getCodedOutput());
return out.build();
} catch (IOException e) {
@@ -79,10 +77,8 @@ public abstract class AbstractMessageLite<
@Override
public void writeTo(final OutputStream output) throws IOException {
- final int bufferSize =
- CodedOutputStream.computePreferredBufferSize(getSerializedSize());
- final CodedOutputStream codedOutput =
- CodedOutputStream.newInstance(output, bufferSize);
+ final int bufferSize = CodedOutputStream.computePreferredBufferSize(getSerializedSize());
+ final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize);
writeTo(codedOutput);
codedOutput.flush();
}
@@ -90,10 +86,10 @@ public abstract class AbstractMessageLite<
@Override
public void writeDelimitedTo(final OutputStream output) throws IOException {
final int serialized = getSerializedSize();
- final int bufferSize = CodedOutputStream.computePreferredBufferSize(
- CodedOutputStream.computeRawVarint32Size(serialized) + serialized);
- final CodedOutputStream codedOutput =
- CodedOutputStream.newInstance(output, bufferSize);
+ final int bufferSize =
+ CodedOutputStream.computePreferredBufferSize(
+ CodedOutputStream.computeRawVarint32Size(serialized) + serialized);
+ final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize);
codedOutput.writeRawVarint32(serialized);
writeTo(codedOutput);
codedOutput.flush();
@@ -110,16 +106,16 @@ public abstract class AbstractMessageLite<
}
- /**
- * Package private helper method for AbstractParser to create
- * UninitializedMessageException.
- */
+ /** Package private helper method for AbstractParser to create UninitializedMessageException. */
UninitializedMessageException newUninitializedMessageException() {
return new UninitializedMessageException(this);
}
private String getSerializingExceptionMessage(String target) {
- return "Serializing " + getClass().getName() + " to a " + target
+ return "Serializing "
+ + getClass().getName()
+ + " to a "
+ + target
+ " threw an IOException (should never happen).";
}
@@ -141,14 +137,13 @@ public abstract class AbstractMessageLite<
}
/**
- * A partial implementation of the {@link Message.Builder} interface which
- * implements as many methods of that interface as possible in terms of
- * other methods.
+ * A partial implementation of the {@link Message.Builder} interface which implements as many
+ * methods of that interface as possible in terms of other methods.
*/
@SuppressWarnings("unchecked")
public abstract static class Builder<
- MessageType extends AbstractMessageLite<MessageType, BuilderType>,
- BuilderType extends Builder<MessageType, BuilderType>>
+ MessageType extends AbstractMessageLite<MessageType, BuilderType>,
+ BuilderType extends Builder<MessageType, BuilderType>>
implements MessageLite.Builder {
// The compiler produces an error if this is not declared explicitly.
@Override
@@ -204,8 +199,7 @@ public abstract class AbstractMessageLite<
public BuilderType mergeFrom(final byte[] data, final int off, final int len)
throws InvalidProtocolBufferException {
try {
- final CodedInputStream input =
- CodedInputStream.newInstance(data, off, len);
+ final CodedInputStream input = CodedInputStream.newInstance(data, off, len);
mergeFrom(input);
input.checkLastTagWas(0);
return (BuilderType) this;
@@ -230,8 +224,7 @@ public abstract class AbstractMessageLite<
final ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
try {
- final CodedInputStream input =
- CodedInputStream.newInstance(data, off, len);
+ final CodedInputStream input = CodedInputStream.newInstance(data, off, len);
mergeFrom(input, extensionRegistry);
input.checkLastTagWas(0);
return (BuilderType) this;
@@ -260,10 +253,9 @@ public abstract class AbstractMessageLite<
}
/**
- * An InputStream implementations which reads from some other InputStream
- * but is limited to a particular number of bytes. Used by
- * mergeDelimitedFrom(). This is intentionally package-private so that
- * UnknownFieldSet can share it.
+ * An InputStream implementations which reads from some other InputStream but is limited to a
+ * particular number of bytes. Used by mergeDelimitedFrom(). This is intentionally
+ * package-private so that UnknownFieldSet can share it.
*/
static final class LimitedInputStream extends FilterInputStream {
private int limit;
@@ -291,8 +283,7 @@ public abstract class AbstractMessageLite<
}
@Override
- public int read(final byte[] b, final int off, int len)
- throws IOException {
+ public int read(final byte[] b, final int off, int len) throws IOException {
if (limit <= 0) {
return -1;
}
@@ -329,8 +320,7 @@ public abstract class AbstractMessageLite<
@Override
public boolean mergeDelimitedFrom(final InputStream input) throws IOException {
- return mergeDelimitedFrom(input,
- ExtensionRegistryLite.getEmptyRegistry());
+ return mergeDelimitedFrom(input, ExtensionRegistryLite.getEmptyRegistry());
}
@Override
@@ -347,7 +337,10 @@ public abstract class AbstractMessageLite<
protected abstract BuilderType internalMergeFrom(MessageType message);
private String getReadingExceptionMessage(String target) {
- return "Reading " + getClass().getName() + " from a " + target
+ return "Reading "
+ + getClass().getName()
+ + " from a "
+ + target
+ " threw an IOException (should never happen).";
}
@@ -370,12 +363,9 @@ public abstract class AbstractMessageLite<
}
}
- /**
- * Construct an UninitializedMessageException reporting missing fields in
- * the given message.
- */
- protected static UninitializedMessageException
- newUninitializedMessageException(MessageLite message) {
+ /** Construct an UninitializedMessageException reporting missing fields in the given message. */
+ protected static UninitializedMessageException newUninitializedMessageException(
+ MessageLite message) {
return new UninitializedMessageException(message);
}
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 ba570e3d..abfaca8c 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractParser.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractParser.java
@@ -36,23 +36,19 @@ import java.io.InputStream;
import java.nio.ByteBuffer;
/**
- * A partial implementation of the {@link Parser} interface which implements
- * as many methods of that interface as possible in terms of other methods.
+ * A partial implementation of the {@link Parser} interface which implements as many methods of that
+ * interface as possible in terms of other methods.
*
- * Note: This class implements all the convenience methods in the
- * {@link Parser} interface. See {@link Parser} for related javadocs.
- * Subclasses need to implement
- * {@link Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)}
+ * <p>Note: This class implements all the convenience methods in the {@link Parser} interface. See
+ * {@link Parser} for related javadocs. Subclasses need to implement {@link
+ * Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)}
*
* @author liujisi@google.com (Pherl Liu)
*/
public abstract class AbstractParser<MessageType extends MessageLite>
implements Parser<MessageType> {
- /**
- * Creates an UninitializedMessageException for MessageType.
- */
- private UninitializedMessageException
- newUninitializedMessageException(MessageType message) {
+ /** Creates an UninitializedMessageException for MessageType. */
+ private UninitializedMessageException newUninitializedMessageException(MessageType message) {
if (message instanceof AbstractMessageLite) {
return ((AbstractMessageLite) message).newUninitializedMessageException();
}
@@ -75,8 +71,8 @@ public abstract class AbstractParser<MessageType extends MessageLite>
return message;
}
- private static final ExtensionRegistryLite EMPTY_REGISTRY
- = ExtensionRegistryLite.getEmptyRegistry();
+ private static final ExtensionRegistryLite EMPTY_REGISTRY =
+ ExtensionRegistryLite.getEmptyRegistry();
@Override
public MessageType parsePartialFrom(CodedInputStream input)
@@ -87,8 +83,7 @@ public abstract class AbstractParser<MessageType extends MessageLite>
@Override
public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialFrom(input, extensionRegistry));
+ return checkMessageInitialized(parsePartialFrom(input, extensionRegistry));
}
@Override
@@ -193,8 +188,7 @@ public abstract class AbstractParser<MessageType extends MessageLite>
public MessageType parseFrom(
byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialFrom(data, off, len, extensionRegistry));
+ return checkMessageInitialized(parsePartialFrom(data, off, len, extensionRegistry));
}
@Override
@@ -235,8 +229,7 @@ public abstract class AbstractParser<MessageType extends MessageLite>
@Override
public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialFrom(input, extensionRegistry));
+ return checkMessageInitialized(parsePartialFrom(input, extensionRegistry));
}
@Override
@@ -271,8 +264,7 @@ public abstract class AbstractParser<MessageType extends MessageLite>
@Override
public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialDelimitedFrom(input, extensionRegistry));
+ return checkMessageInitialized(parsePartialDelimitedFrom(input, extensionRegistry));
}
@Override
diff --git a/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java b/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java
index b17db6e0..3220f640 100644
--- a/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java
+++ b/java/core/src/main/java/com/google/protobuf/AbstractProtobufList.java
@@ -31,7 +31,6 @@
package com.google.protobuf;
import com.google.protobuf.Internal.ProtobufList;
-
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
@@ -39,23 +38,19 @@ import java.util.RandomAccess;
/**
* An abstract implementation of {@link ProtobufList} which manages mutability semantics. All mutate
- * methods must check if the list is mutable before proceeding. Subclasses must invoke
- * {@link #ensureIsMutable()} manually when overriding those methods.
- * <p>
- * This implementation assumes all subclasses are array based, supporting random access.
+ * methods must check if the list is mutable before proceeding. Subclasses must invoke {@link
+ * #ensureIsMutable()} manually when overriding those methods.
+ *
+ * <p>This implementation assumes all subclasses are array based, supporting random access.
*/
abstract class AbstractProtobufList<E> extends AbstractList<E> implements ProtobufList<E> {
protected static final int DEFAULT_CAPACITY = 10;
- /**
- * Whether or not this list is modifiable.
- */
+ /** Whether or not this list is modifiable. */
private boolean isMutable;
- /**
- * Constructs a mutable list by default.
- */
+ /** Constructs a mutable list by default. */
AbstractProtobufList() {
isMutable = true;
}
@@ -115,7 +110,7 @@ abstract class AbstractProtobufList<E> extends AbstractList<E> implements Protob
ensureIsMutable();
return super.addAll(c);
}
-
+
@Override
public boolean addAll(int index, Collection<? extends E> c) {
ensureIsMutable();
@@ -127,47 +122,47 @@ abstract class AbstractProtobufList<E> extends AbstractList<E> implements Protob
ensureIsMutable();
super.clear();
}
-
+
@Override
public boolean isModifiable() {
return isMutable;
}
-
+
@Override
public final void makeImmutable() {
isMutable = false;
}
-
+
@Override
public E remove(int index) {
ensureIsMutable();
return super.remove(index);
}
-
+
@Override
public boolean remove(Object o) {
ensureIsMutable();
return super.remove(o);
}
-
+
@Override
public boolean removeAll(Collection<?> c) {
ensureIsMutable();
return super.removeAll(c);
}
-
+
@Override
public boolean retainAll(Collection<?> c) {
ensureIsMutable();
return super.retainAll(c);
}
-
+
@Override
public E set(int index, E element) {
ensureIsMutable();
return super.set(index, element);
}
-
+
/**
* Throws an {@link UnsupportedOperationException} if the list is immutable. Subclasses are
* responsible for invoking this method on mutate operations.
diff --git a/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java b/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java
index d535efb9..8af80057 100644
--- a/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java
+++ b/java/core/src/main/java/com/google/protobuf/BlockingRpcChannel.java
@@ -31,21 +31,21 @@
package com.google.protobuf;
/**
- * <p>Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel}
- * is the blocking equivalent to {@link RpcChannel}.
+ * Abstract interface for a blocking RPC channel. {@code BlockingRpcChannel} is the blocking
+ * equivalent to {@link RpcChannel}.
*
* @author kenton@google.com Kenton Varda
* @author cpovirk@google.com Chris Povirk
*/
public interface BlockingRpcChannel {
/**
- * Call the given method of the remote service and blocks until it returns.
- * {@code callBlockingMethod()} is the blocking equivalent to
- * {@link RpcChannel#callMethod}.
+ * Call the given method of the remote service and blocks until it returns. {@code
+ * callBlockingMethod()} is the blocking equivalent to {@link RpcChannel#callMethod}.
*/
Message callBlockingMethod(
Descriptors.MethodDescriptor method,
RpcController controller,
Message request,
- Message responsePrototype) throws ServiceException;
+ Message responsePrototype)
+ throws ServiceException;
}
diff --git a/java/core/src/main/java/com/google/protobuf/BlockingService.java b/java/core/src/main/java/com/google/protobuf/BlockingService.java
index d01f0b8f..e2b99c96 100644
--- a/java/core/src/main/java/com/google/protobuf/BlockingService.java
+++ b/java/core/src/main/java/com/google/protobuf/BlockingService.java
@@ -37,28 +37,21 @@ package com.google.protobuf;
* @author cpovirk@google.com Chris Povirk
*/
public interface BlockingService {
- /**
- * Equivalent to {@link Service#getDescriptorForType}.
- */
+ /** Equivalent to {@link Service#getDescriptorForType}. */
Descriptors.ServiceDescriptor getDescriptorForType();
/**
- * Equivalent to {@link Service#callMethod}, except that
- * {@code callBlockingMethod()} returns the result of the RPC or throws a
- * {@link ServiceException} if there is a failure, rather than passing the
- * information to a callback.
+ * Equivalent to {@link Service#callMethod}, except that {@code callBlockingMethod()} returns the
+ * result of the RPC or throws a {@link ServiceException} if there is a failure, rather than
+ * passing the information to a callback.
*/
- Message callBlockingMethod(Descriptors.MethodDescriptor method,
- RpcController controller,
- Message request) throws ServiceException;
+ Message callBlockingMethod(
+ Descriptors.MethodDescriptor method, RpcController controller, Message request)
+ throws ServiceException;
- /**
- * Equivalent to {@link Service#getRequestPrototype}.
- */
+ /** Equivalent to {@link Service#getRequestPrototype}. */
Message getRequestPrototype(Descriptors.MethodDescriptor method);
- /**
- * Equivalent to {@link Service#getResponsePrototype}.
- */
+ /** Equivalent to {@link Service#getResponsePrototype}. */
Message getResponsePrototype(Descriptors.MethodDescriptor method);
}
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 4d7a9727..2c8929e5 100644
--- a/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
@@ -46,6 +46,7 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
implements BooleanList, RandomAccess, PrimitiveNonBoxingCollection {
private static final BooleanArrayList EMPTY_LIST = new BooleanArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
@@ -54,9 +55,7 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
return EMPTY_LIST;
}
- /**
- * The backing store for the list.
- */
+ /** The backing store for the list. */
private boolean[] array;
/**
@@ -65,16 +64,14 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
*/
private int size;
- /**
- * Constructs a new mutable {@code BooleanArrayList} with default capacity.
- */
+ /** Constructs a new mutable {@code BooleanArrayList} with default capacity. */
BooleanArrayList() {
this(new boolean[DEFAULT_CAPACITY], 0);
}
/**
- * Constructs a new mutable {@code BooleanArrayList}
- * containing the same elements as {@code other}.
+ * Constructs a new mutable {@code BooleanArrayList} containing the same elements as {@code
+ * other}.
*/
private BooleanArrayList(boolean[] other, int size) {
array = other;
@@ -168,17 +165,13 @@ final class BooleanArrayList extends AbstractProtobufList<Boolean>
addBoolean(index, element);
}
- /**
- * Like {@link #add(Boolean)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Boolean)} but more efficient in that it doesn't box the element. */
@Override
public void addBoolean(boolean element) {
addBoolean(size, element);
}
- /**
- * Like {@link #add(int, Boolean)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(int, Boolean)} but more efficient in that it doesn't box the element. */
private void addBoolean(int index, boolean element) {
ensureIsMutable();
if (index < 0 || index > size) {
diff --git a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
index 6157a52f..2cb3ada6 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
@@ -40,45 +40,40 @@ import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
-/**
- * Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s.
- */
+/** Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s. */
final class ByteBufferWriter {
private ByteBufferWriter() {}
/**
- * Minimum size for a cached buffer. This prevents us from allocating buffers that are too
- * small to be easily reused.
+ * Minimum size for a cached buffer. This prevents us from allocating buffers that are too small
+ * to be easily reused.
*/
// TODO(nathanmittler): tune this property or allow configuration?
private static final int MIN_CACHED_BUFFER_SIZE = 1024;
/**
- * Maximum size for a cached buffer. If a larger buffer is required, it will be allocated
- * but not cached.
+ * Maximum size for a cached buffer. If a larger buffer is required, it will be allocated but not
+ * cached.
*/
// TODO(nathanmittler): tune this property or allow configuration?
private static final int MAX_CACHED_BUFFER_SIZE = 16 * 1024;
- /**
- * The fraction of the requested buffer size under which the buffer will be reallocated.
- */
+ /** The fraction of the requested buffer size under which the buffer will be reallocated. */
// TODO(nathanmittler): tune this property or allow configuration?
private static final float BUFFER_REALLOCATION_THRESHOLD = 0.5f;
/**
- * Keeping a soft reference to a thread-local buffer. This buffer is used for writing a
- * {@link ByteBuffer} to an {@link OutputStream} when no zero-copy alternative was available.
- * Using a "soft" reference since VMs may keep this reference around longer than "weak"
- * (e.g. HotSpot will maintain soft references until memory pressure warrants collection).
+ * Keeping a soft reference to a thread-local buffer. This buffer is used for writing a {@link
+ * ByteBuffer} to an {@link OutputStream} when no zero-copy alternative was available. Using a
+ * "soft" reference since VMs may keep this reference around longer than "weak" (e.g. HotSpot will
+ * maintain soft references until memory pressure warrants collection).
*/
private static final ThreadLocal<SoftReference<byte[]>> BUFFER =
new ThreadLocal<SoftReference<byte[]>>();
- /**
- * This is a hack for GAE, where {@code FileOutputStream} is unavailable.
- */
+ /** This is a hack for GAE, where {@code FileOutputStream} is unavailable. */
private static final Class<?> FILE_OUTPUT_STREAM_CLASS = safeGetClass("java.io.FileOutputStream");
+
private static final long CHANNEL_FIELD_OFFSET = getChannelFieldOffset(FILE_OUTPUT_STREAM_CLASS);
/**
@@ -100,7 +95,7 @@ final class ByteBufferWriter {
// Optimized write for array-backed buffers.
// Note that we're taking the risk that a malicious OutputStream could modify the array.
output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
- } else if (!writeToChannel(buffer, output)){
+ } else if (!writeToChannel(buffer, output)) {
// Read all of the data from the buffer to an array.
// TODO(nathanmittler): Consider performance improvements for other "known" stream types.
final byte[] array = getOrCreateBuffer(buffer.remaining());
@@ -171,6 +166,7 @@ final class ByteBufferWriter {
return null;
}
}
+
private static long getChannelFieldOffset(Class<?> clazz) {
try {
if (clazz != null && UnsafeUtil.hasUnsafeArrayOperations()) {
diff --git a/java/core/src/main/java/com/google/protobuf/ByteOutput.java b/java/core/src/main/java/com/google/protobuf/ByteOutput.java
index ee588753..dba7a379 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteOutput.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteOutput.java
@@ -37,9 +37,9 @@ import java.nio.ByteBuffer;
* An output target for raw bytes. This interface provides semantics that support two types of
* writing:
*
- * <p><b>Traditional write operations:</b>
- * (as defined by {@link java.io.OutputStream}) where the target method is responsible for either
- * copying the data or completing the write before returning from the method call.
+ * <p><b>Traditional write operations:</b> (as defined by {@link java.io.OutputStream}) where the
+ * target method is responsible for either copying the data or completing the write before returning
+ * from the method call.
*
* <p><b>Lazy write operations:</b> where the caller guarantees that it will never modify the
* provided buffer and it can therefore be considered immutable. The target method is free to
@@ -57,9 +57,9 @@ public abstract class ByteOutput {
public abstract void write(byte value) throws IOException;
/**
- * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will
- * not be processed prior to the return of this method call, since {@code value} may be
- * reused/altered by the caller.
+ * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will not be
+ * processed prior to the return of this method call, since {@code value} may be reused/altered by
+ * the caller.
*
* <p>NOTE: This method <strong>MUST NOT</strong> modify the {@code value}. Doing so is a
* programming error and will lead to data corruption which will be difficult to debug.
@@ -87,15 +87,15 @@ public abstract class ByteOutput {
public abstract void writeLazy(byte[] value, int offset, int length) throws IOException;
/**
- * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will
- * not be processed prior to the return of this method call, since {@code value} may be
- * reused/altered by the caller.
+ * Writes a sequence of bytes. The {@link ByteOutput} must copy {@code value} if it will not be
+ * processed prior to the return of this method call, since {@code value} may be reused/altered by
+ * the caller.
*
* <p>NOTE: This method <strong>MUST NOT</strong> modify the {@code value}. Doing so is a
* programming error and will lead to data corruption which will be difficult to debug.
*
* @param value the bytes to be written. Upon returning from this call, the {@code position} of
- * this buffer will be set to the {@code limit}
+ * this buffer will be set to the {@code limit}
* @throws IOException thrown if an error occurred while writing
*/
public abstract void write(ByteBuffer value) throws IOException;
@@ -109,7 +109,7 @@ public abstract class ByteOutput {
* programming error and will lead to data corruption which will be difficult to debug.
*
* @param value the bytes to be written. Upon returning from this call, the {@code position} of
- * this buffer will be set to the {@code limit}
+ * this buffer will be set to the {@code limit}
* @throws IOException thrown if an error occurred while writing
*/
public abstract void writeLazy(ByteBuffer value) throws IOException;
diff --git a/java/core/src/main/java/com/google/protobuf/ByteString.java b/java/core/src/main/java/com/google/protobuf/ByteString.java
index d67bb54a..844d8a53 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteString.java
@@ -46,6 +46,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
@@ -66,41 +67,36 @@ import java.util.NoSuchElementException;
public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
- * When two strings to be concatenated have a combined length shorter than
- * this, we just copy their bytes on {@link #concat(ByteString)}.
- * The trade-off is copy size versus the overhead of creating tree nodes
- * in {@link RopeByteString}.
+ * When two strings to be concatenated have a combined length shorter than this, we just copy
+ * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of
+ * creating tree nodes in {@link RopeByteString}.
*/
static final int CONCATENATE_BY_COPY_SIZE = 128;
/**
- * When copying an InputStream into a ByteString with .readFrom(),
- * the chunks in the underlying rope start at 256 bytes, but double
- * each iteration up to 8192 bytes.
+ * When copying an InputStream into a ByteString with .readFrom(), the chunks in the underlying
+ * rope start at 256 bytes, but double each iteration up to 8192 bytes.
*/
- static final int MIN_READ_FROM_CHUNK_SIZE = 0x100; // 256b
- static final int MAX_READ_FROM_CHUNK_SIZE = 0x2000; // 8k
+ static final int MIN_READ_FROM_CHUNK_SIZE = 0x100; // 256b
- /**
- * Empty {@code ByteString}.
- */
+ static final int MAX_READ_FROM_CHUNK_SIZE = 0x2000; // 8k
+
+ /** Empty {@code ByteString}. */
public static final ByteString EMPTY = new LiteralByteString(Internal.EMPTY_BYTE_ARRAY);
/**
* An interface to efficiently copy {@code byte[]}.
*
- * <p>One of the noticeable costs of copying a byte[] into a new array using
- * {@code System.arraycopy} is nullification of a new buffer before the copy. It has been shown
- * the Hotspot VM is capable to intrisicfy {@code Arrays.copyOfRange} operation to avoid this
+ * <p>One of the noticeable costs of copying a byte[] into a new array using {@code
+ * System.arraycopy} is nullification of a new buffer before the copy. It has been shown the
+ * Hotspot VM is capable to intrisicfy {@code Arrays.copyOfRange} operation to avoid this
* expensive nullification and provide substantial performance gain. Unfortunately this does not
- * hold on Android runtimes and could make the copy slightly slower due to additional code in
- * the {@code Arrays.copyOfRange}. Thus we provide two different implementation for array copier
- * for Hotspot and Android runtimes.
+ * hold on Android runtimes and could make the copy slightly slower due to additional code in the
+ * {@code Arrays.copyOfRange}. Thus we provide two different implementation for array copier for
+ * Hotspot and Android runtimes.
*/
private interface ByteArrayCopier {
- /**
- * Copies the specified range of the specified array into a new array
- */
+ /** Copies the specified range of the specified array into a new array */
byte[] copyFrom(byte[] bytes, int offset, int size);
}
@@ -123,15 +119,16 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
private static final ByteArrayCopier byteArrayCopier;
+
static {
byteArrayCopier =
Android.isOnAndroidDevice() ? new SystemByteArrayCopier() : new ArraysByteArrayCopier();
}
/**
- * Cached hash value. Intentionally accessed via a data race, which
- * is safe because of the Java Memory Model's "no out-of-thin-air values"
- * guarantees for ints. A value of 0 implies that the hash has not been set.
+ * Cached hash value. Intentionally accessed via a data race, which is safe because of the Java
+ * Memory Model's "no out-of-thin-air values" guarantees for ints. A value of 0 implies that the
+ * hash has not been set.
*/
private int hash = 0;
@@ -139,10 +136,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
ByteString() {}
/**
- * Gets the byte at the given index. This method should be used only for
- * random access to individual bytes. To access bytes sequentially, use the
- * {@link ByteIterator} returned by {@link #iterator()}, and call {@link
- * #substring(int, int)} first if necessary.
+ * Gets the byte at the given index. This method should be used only for random access to
+ * individual bytes. To access bytes sequentially, use the {@link ByteIterator} returned by {@link
+ * #iterator()}, and call {@link #substring(int, int)} first if necessary.
*
* @param index index of byte
* @return the value
@@ -151,9 +147,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
public abstract byte byteAt(int index);
/**
- * Return a {@link ByteString.ByteIterator} over the bytes in the ByteString.
- * To avoid auto-boxing, you may get the iterator manually and call
- * {@link ByteIterator#nextByte()}.
+ * Return a {@link ByteString.ByteIterator} over the bytes in the ByteString. To avoid
+ * auto-boxing, you may get the iterator manually and call {@link ByteIterator#nextByte()}.
*
* @return the iterator
*/
@@ -191,13 +186,11 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * This interface extends {@code Iterator<Byte>}, so that we can return an
- * unboxed {@code byte}.
+ * This interface extends {@code Iterator<Byte>}, so that we can return an unboxed {@code byte}.
*/
public interface ByteIterator extends Iterator<Byte> {
/**
- * An alternative to {@link Iterator#next()} that returns an
- * unboxed primitive {@code byte}.
+ * An alternative to {@link Iterator#next()} that returns an unboxed primitive {@code byte}.
*
* @return the next {@code byte} in the iteration
* @throws NoSuchElementException if the iteration has no more elements
@@ -222,59 +215,113 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
// =================================================================
+ // Comparison
+
+ private static final int UNSIGNED_BYTE_MASK = 0xFF;
+
+ /**
+ * Returns the value of the given byte as an integer, interpreting the byte as an unsigned value.
+ * That is, returns {@code value + 256} if {@code value} is negative; {@code value} itself
+ * otherwise.
+ *
+ * <p>Note: This code was copied from {@link com.google.common.primitives.UnsignedBytes#toInt}, as
+ * Guava libraries cannot be used in the {@code com.google.protobuf} package.
+ */
+ private static int toInt(byte value) {
+ return value & UNSIGNED_BYTE_MASK;
+ }
+
+ /**
+ * Compares two {@link ByteString}s lexicographically, treating their contents as unsigned byte
+ * values between 0 and 255 (inclusive).
+ *
+ * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it
+ * is interpreted as an unsigned value, {@code 255}.
+ */
+ private static final Comparator<ByteString> UNSIGNED_LEXICOGRAPHICAL_COMPARATOR =
+ new Comparator<ByteString>() {
+ @Override
+ public int compare(ByteString former, ByteString latter) {
+ ByteIterator formerBytes = former.iterator();
+ ByteIterator latterBytes = latter.iterator();
+
+ while (formerBytes.hasNext() && latterBytes.hasNext()) {
+ // Note: This code was copied from com.google.common.primitives.UnsignedBytes#compare,
+ // as Guava libraries cannot be used in the {@code com.google.protobuf} package.
+ int result =
+ Integer.compare(toInt(formerBytes.nextByte()), toInt(latterBytes.nextByte()));
+ if (result != 0) {
+ return result;
+ }
+ }
+
+ return Integer.compare(former.size(), latter.size());
+ }
+ };
+
+ /**
+ * Returns a {@link Comparator<ByteString>} which compares {@link ByteString}-s lexicographically
+ * as sequences of unsigned bytes (i.e. values between 0 and 255, inclusive).
+ *
+ * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it
+ * is interpreted as an unsigned value, {@code 255}:
+ *
+ * <ul>
+ * <li>{@code `-1` -> 0b11111111 (two's complement) -> 255}
+ * <li>{@code `1` -> 0b00000001 -> 1}
+ * </ul>
+ */
+ public static Comparator<ByteString> unsignedLexicographicalComparator() {
+ return UNSIGNED_LEXICOGRAPHICAL_COMPARATOR;
+ }
+
+ // =================================================================
// ByteString -> substring
/**
- * Return the substring from {@code beginIndex}, inclusive, to the end of the
- * string.
+ * Return the substring from {@code beginIndex}, inclusive, to the end of the string.
*
* @param beginIndex start at this index
* @return substring sharing underlying data
- * @throws IndexOutOfBoundsException if {@code beginIndex < 0} or
- * {@code beginIndex > size()}.
+ * @throws IndexOutOfBoundsException if {@code beginIndex < 0} or {@code beginIndex > size()}.
*/
public final ByteString substring(int beginIndex) {
return substring(beginIndex, size());
}
/**
- * Return the substring from {@code beginIndex}, inclusive, to {@code
- * endIndex}, exclusive.
+ * Return the substring from {@code beginIndex}, inclusive, to {@code endIndex}, exclusive.
*
* @param beginIndex start at this index
- * @param endIndex the last character is the one before this index
+ * @param endIndex the last character is the one before this index
* @return substring sharing underlying data
- * @throws IndexOutOfBoundsException if {@code beginIndex < 0},
- * {@code endIndex > size()}, or {@code beginIndex > endIndex}.
+ * @throws IndexOutOfBoundsException if {@code beginIndex < 0}, {@code endIndex > size()}, or
+ * {@code beginIndex > endIndex}.
*/
public abstract ByteString substring(int beginIndex, int endIndex);
/**
- * Tests if this bytestring starts with the specified prefix.
- * Similar to {@link String#startsWith(String)}
+ * Tests if this bytestring starts with the specified prefix. Similar to {@link
+ * String#startsWith(String)}
*
* @param prefix the prefix.
- * @return <code>true</code> if the byte sequence represented by the
- * argument is a prefix of the byte sequence represented by
- * this string; <code>false</code> otherwise.
+ * @return <code>true</code> if the byte sequence represented by the argument is a prefix of the
+ * byte sequence represented by this string; <code>false</code> otherwise.
*/
public final boolean startsWith(ByteString prefix) {
- return size() >= prefix.size() &&
- substring(0, prefix.size()).equals(prefix);
+ return size() >= prefix.size() && substring(0, prefix.size()).equals(prefix);
}
/**
- * Tests if this bytestring ends with the specified suffix.
- * Similar to {@link String#endsWith(String)}
+ * Tests if this bytestring ends with the specified suffix. Similar to {@link
+ * String#endsWith(String)}
*
* @param suffix the suffix.
- * @return <code>true</code> if the byte sequence represented by the
- * argument is a suffix of the byte sequence represented by
- * this string; <code>false</code> otherwise.
+ * @return <code>true</code> if the byte sequence represented by the argument is a suffix of the
+ * byte sequence represented by this string; <code>false</code> otherwise.
*/
public final boolean endsWith(ByteString suffix) {
- return size() >= suffix.size() &&
- substring(size() - suffix.size()).equals(suffix);
+ return size() >= suffix.size() && substring(size() - suffix.size()).equals(suffix);
}
// =================================================================
@@ -287,8 +334,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
* @param offset offset in source array
* @param size number of bytes to copy
* @return new {@code ByteString}
+ * @throws IndexOutOfBoundsException if {@code offset} or {@code size} are out of bounds
*/
public static ByteString copyFrom(byte[] bytes, int offset, int size) {
+ checkRange(offset, offset + size, bytes.length);
return new LiteralByteString(byteArrayCopier.copyFrom(bytes, offset, size));
}
@@ -302,9 +351,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return copyFrom(bytes, 0, bytes.length);
}
- /**
- * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage.
- */
+ /** Wraps the given bytes into a {@code ByteString}. Intended for internal only usage. */
static ByteString wrap(ByteBuffer buffer) {
if (buffer.hasArray()) {
final int offset = buffer.arrayOffset();
@@ -315,8 +362,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Wraps the given bytes into a {@code ByteString}. Intended for internal only
- * usage to force a classload of ByteString before LiteralByteString.
+ * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage to force a
+ * classload of ByteString before LiteralByteString.
*/
static ByteString wrap(byte[] bytes) {
// TODO(dweis): Return EMPTY when bytes are empty to reduce allocations?
@@ -324,31 +371,31 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Wraps the given bytes into a {@code ByteString}. Intended for internal only
- * usage to force a classload of ByteString before BoundedByteString and
- * LiteralByteString.
+ * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage to force a
+ * classload of ByteString before BoundedByteString and LiteralByteString.
*/
static ByteString wrap(byte[] bytes, int offset, int length) {
return new BoundedByteString(bytes, offset, length);
}
/**
- * Copies the next {@code size} bytes from a {@code java.nio.ByteBuffer} into
- * a {@code ByteString}.
+ * Copies the next {@code size} bytes from a {@code java.nio.ByteBuffer} into a {@code
+ * ByteString}.
*
* @param bytes source buffer
* @param size number of bytes to copy
* @return new {@code ByteString}
+ * @throws IndexOutOfBoundsException if {@code size > bytes.remaining()}
*/
public static ByteString copyFrom(ByteBuffer bytes, int size) {
+ checkRange(0, size, bytes.remaining());
byte[] copy = new byte[size];
bytes.get(copy);
return new LiteralByteString(copy);
}
/**
- * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into
- * a {@code ByteString}.
+ * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into a {@code ByteString}.
*
* @param bytes sourceBuffer
* @return new {@code ByteString}
@@ -358,8 +405,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Encodes {@code text} into a sequence of bytes using the named charset
- * and returns the result as a {@code ByteString}.
+ * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as
+ * a {@code ByteString}.
*
* @param text source string
* @param charsetName encoding to use
@@ -372,8 +419,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Encodes {@code text} into a sequence of bytes using the named charset
- * and returns the result as a {@code ByteString}.
+ * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as
+ * a {@code ByteString}.
*
* @param text source string
* @param charset encode using this charset
@@ -384,8 +431,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Encodes {@code text} into a sequence of UTF-8 bytes and returns the
- * result as a {@code ByteString}.
+ * Encodes {@code text} into a sequence of UTF-8 bytes and returns the result as a {@code
+ * ByteString}.
*
* @param text source string
* @return new {@code ByteString}
@@ -398,60 +445,48 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// InputStream -> ByteString
/**
- * Completely reads the given stream's bytes into a
- * {@code ByteString}, blocking if necessary until all bytes are
- * read through to the end of the stream.
- *
- * <b>Performance notes:</b> The returned {@code ByteString} is an
- * immutable tree of byte arrays ("chunks") of the stream data. The
- * first chunk is small, with subsequent chunks each being double
- * the size, up to 8K.
- *
- * <p>Each byte read from the input stream will be copied twice to ensure
- * that the resulting ByteString is truly immutable.
- *
- * @param streamToDrain The source stream, which is read completely
- * but not closed.
- * @return A new {@code ByteString} which is made up of chunks of
- * various sizes, depending on the behavior of the underlying
- * stream.
- * @throws IOException IOException is thrown if there is a problem
- * reading the underlying stream.
+ * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary
+ * until all bytes are read through to the end of the stream.
+ *
+ * <p><b>Performance notes:</b> The returned {@code ByteString} is an immutable tree of byte
+ * arrays ("chunks") of the stream data. The first chunk is small, with subsequent chunks each
+ * being double the size, up to 8K.
+ *
+ * <p>Each byte read from the input stream will be copied twice to ensure that the resulting
+ * ByteString is truly immutable.
+ *
+ * @param streamToDrain The source stream, which is read completely but not closed.
+ * @return A new {@code ByteString} which is made up of chunks of various sizes, depending on the
+ * behavior of the underlying stream.
+ * @throws IOException IOException is thrown if there is a problem reading the underlying stream.
*/
- public static ByteString readFrom(InputStream streamToDrain)
- throws IOException {
+ public static ByteString readFrom(InputStream streamToDrain) throws IOException {
return readFrom(streamToDrain, MIN_READ_FROM_CHUNK_SIZE, MAX_READ_FROM_CHUNK_SIZE);
}
/**
- * Completely reads the given stream's bytes into a
- * {@code ByteString}, blocking if necessary until all bytes are
- * read through to the end of the stream.
- *
- * <b>Performance notes:</b> The returned {@code ByteString} is an
- * immutable tree of byte arrays ("chunks") of the stream data. The
- * chunkSize parameter sets the size of these byte arrays.
- *
- * <p>Each byte read from the input stream will be copied twice to ensure
- * that the resulting ByteString is truly immutable.
- *
- * @param streamToDrain The source stream, which is read completely
- * but not closed.
- * @param chunkSize The size of the chunks in which to read the
- * stream.
- * @return A new {@code ByteString} which is made up of chunks of
- * the given size.
- * @throws IOException IOException is thrown if there is a problem
- * reading the underlying stream.
+ * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary
+ * until all bytes are read through to the end of the stream.
+ *
+ * <p><b>Performance notes:</b> The returned {@code ByteString} is an immutable tree of byte
+ * arrays ("chunks") of the stream data. The chunkSize parameter sets the size of these byte
+ * arrays.
+ *
+ * <p>Each byte read from the input stream will be copied twice to ensure that the resulting
+ * ByteString is truly immutable.
+ *
+ * @param streamToDrain The source stream, which is read completely but not closed.
+ * @param chunkSize The size of the chunks in which to read the stream.
+ * @return A new {@code ByteString} which is made up of chunks of the given size.
+ * @throws IOException IOException is thrown if there is a problem reading the underlying stream.
*/
- public static ByteString readFrom(InputStream streamToDrain, int chunkSize)
- throws IOException {
+ public static ByteString readFrom(InputStream streamToDrain, int chunkSize) throws IOException {
return readFrom(streamToDrain, chunkSize, chunkSize);
}
// Helper method that takes the chunk size range as a parameter.
- public static ByteString readFrom(InputStream streamToDrain, int minChunkSize,
- int maxChunkSize) throws IOException {
+ public static ByteString readFrom(InputStream streamToDrain, int minChunkSize, int maxChunkSize)
+ throws IOException {
Collection<ByteString> results = new ArrayList<ByteString>();
// copy the inbound bytes into a list of chunks; the chunk size
@@ -470,42 +505,39 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Blocks until a chunk of the given size can be made from the
- * stream, or EOF is reached. Calls read() repeatedly in case the
- * given stream implementation doesn't completely fill the given
+ * Blocks until a chunk of the given size can be made from the stream, or EOF is reached. Calls
+ * read() repeatedly in case the given stream implementation doesn't completely fill the given
* buffer in one read() call.
*
- * @return A chunk of the desired size, or else a chunk as large as
- * was available when end of stream was reached. Returns null if the
- * given stream had no more data in it.
+ * @return A chunk of the desired size, or else a chunk as large as was available when end of
+ * stream was reached. Returns null if the given stream had no more data in it.
*/
- private static ByteString readChunk(InputStream in, final int chunkSize)
- throws IOException {
- final byte[] buf = new byte[chunkSize];
- int bytesRead = 0;
- while (bytesRead < chunkSize) {
- final int count = in.read(buf, bytesRead, chunkSize - bytesRead);
- if (count == -1) {
- break;
- }
- bytesRead += count;
+ private static ByteString readChunk(InputStream in, final int chunkSize) throws IOException {
+ final byte[] buf = new byte[chunkSize];
+ int bytesRead = 0;
+ while (bytesRead < chunkSize) {
+ final int count = in.read(buf, bytesRead, chunkSize - bytesRead);
+ if (count == -1) {
+ break;
}
+ bytesRead += count;
+ }
- if (bytesRead == 0) {
- return null;
- }
+ if (bytesRead == 0) {
+ return null;
+ }
- // Always make a copy since InputStream could steal a reference to buf.
- return ByteString.copyFrom(buf, 0, bytesRead);
+ // Always make a copy since InputStream could steal a reference to buf.
+ return ByteString.copyFrom(buf, 0, bytesRead);
}
// =================================================================
// Multiple ByteStrings -> One ByteString
/**
- * Concatenate the given {@code ByteString} to this one. Short concatenations,
- * of total size smaller than {@link ByteString#CONCATENATE_BY_COPY_SIZE}, are
- * produced by copying the underlying bytes (as per Rope.java, <a
+ * Concatenate the given {@code ByteString} to this one. Short concatenations, of total size
+ * smaller than {@link ByteString#CONCATENATE_BY_COPY_SIZE}, are produced by copying the
+ * underlying bytes (as per Rope.java, <a
* href="http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf">
* BAP95 </a>. In general, the concatenate involves no copying.
*
@@ -514,21 +546,20 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
*/
public final ByteString concat(ByteString other) {
if (Integer.MAX_VALUE - size() < other.size()) {
- throw new IllegalArgumentException("ByteString would be too long: " +
- size() + "+" + other.size());
+ throw new IllegalArgumentException(
+ "ByteString would be too long: " + size() + "+" + other.size());
}
return RopeByteString.concatenate(this, other);
}
/**
- * Concatenates all byte strings in the iterable and returns the result.
- * This is designed to run in O(list size), not O(total bytes).
+ * Concatenates all byte strings in the iterable and returns the result. This is designed to run
+ * in O(list size), not O(total bytes).
*
- * <p>The returned {@code ByteString} is not necessarily a unique object.
- * If the list is empty, the returned object is the singleton empty
- * {@code ByteString}. If the list has only one element, that
- * {@code ByteString} will be returned without copying.
+ * <p>The returned {@code ByteString} is not necessarily a unique object. If the list is empty,
+ * the returned object is the singleton empty {@code ByteString}. If the list has only one
+ * element, that {@code ByteString} will be returned without copying.
*
* @param byteStrings strings to be concatenated
* @return new {@code ByteString}
@@ -538,9 +569,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
final int size;
if (!(byteStrings instanceof Collection)) {
int tempSize = 0;
- for (Iterator<ByteString> iter = byteStrings.iterator(); iter.hasNext();
- iter.next(), ++tempSize) {
- }
+ for (Iterator<ByteString> iter = byteStrings.iterator();
+ iter.hasNext();
+ iter.next(), ++tempSize) {}
size = tempSize;
} else {
size = ((Collection<ByteString>) byteStrings).size();
@@ -578,6 +609,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Copies bytes into a buffer at the given offset.
*
+ * <p>To copy a subset of bytes, you call this method on the return value of {@link
+ * #substring(int, int)}. Example: {@code byteString.substring(start, end).copyTo(target, offset)}
+ *
* @param target buffer to copy into
* @param offset in the target buffer
* @throws IndexOutOfBoundsException if the offset is negative or too large
@@ -589,15 +623,16 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Copies bytes into a buffer.
*
- * @param target buffer to copy into
+ * @param target buffer to copy into
* @param sourceOffset offset within these bytes
* @param targetOffset offset within the target buffer
* @param numberToCopy number of bytes to copy
- * @throws IndexOutOfBoundsException if an offset or size is negative or too
- * large
+ * @throws IndexOutOfBoundsException if an offset or size is negative or too large
+ * @deprecation Instead, call {@code byteString.substring(sourceOffset, sourceOffset +
+ * numberToCopy).copyTo(target, targetOffset)}
*/
- public final void copyTo(byte[] target, int sourceOffset, int targetOffset,
- int numberToCopy) {
+ @Deprecated
+ public final void copyTo(byte[] target, int sourceOffset, int targetOffset, int numberToCopy) {
checkRange(sourceOffset, sourceOffset + numberToCopy, size());
checkRange(targetOffset, targetOffset + numberToCopy, target.length);
if (numberToCopy > 0) {
@@ -606,21 +641,22 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Internal (package private) implementation of
- * {@link #copyTo(byte[],int,int,int)}.
- * It assumes that all error checking has already been performed and that
- * {@code numberToCopy > 0}.
+ * Internal (package private) implementation of {@link #copyTo(byte[],int,int,int)}. It assumes
+ * that all error checking has already been performed and that {@code numberToCopy > 0}.
*/
- protected abstract void copyToInternal(byte[] target, int sourceOffset,
- int targetOffset, int numberToCopy);
+ protected abstract void copyToInternal(
+ byte[] target, int sourceOffset, int targetOffset, int numberToCopy);
/**
* Copies bytes into a ByteBuffer.
*
+ * <p>To copy a subset of bytes, you call this method on the return value of {@link
+ * #substring(int, int)}. Example: {@code byteString.substring(start, end).copyTo(target)}
+ *
* @param target ByteBuffer to copy into.
* @throws java.nio.ReadOnlyBufferException if the {@code target} is read-only
- * @throws java.nio.BufferOverflowException if the {@code target}'s
- * remaining() space is not large enough to hold the data.
+ * @throws java.nio.BufferOverflowException if the {@code target}'s remaining() space is not large
+ * enough to hold the data.
*/
public abstract void copyTo(ByteBuffer target);
@@ -642,22 +678,21 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Writes a copy of the contents of this byte string to the specified output stream argument.
*
- * @param out the output stream to which to write the data.
- * @throws IOException if an I/O error occurs.
+ * @param out the output stream to which to write the data.
+ * @throws IOException if an I/O error occurs.
*/
public abstract void writeTo(OutputStream out) throws IOException;
/**
* Writes a specified part of this byte string to an output stream.
*
- * @param out the output stream to which to write the data.
- * @param sourceOffset offset within these bytes
- * @param numberToWrite number of bytes to write
- * @throws IOException if an I/O error occurs.
+ * @param out the output stream to which to write the data.
+ * @param sourceOffset offset within these bytes
+ * @param numberToWrite number of bytes to write
+ * @throws IOException if an I/O error occurs.
* @throws IndexOutOfBoundsException if an offset or size is negative or too large
*/
- final void writeTo(OutputStream out, int sourceOffset, int numberToWrite)
- throws IOException {
+ final void writeTo(OutputStream out, int sourceOffset, int numberToWrite) throws IOException {
checkRange(sourceOffset, sourceOffset + numberToWrite, size());
if (numberToWrite > 0) {
writeToInternal(out, sourceOffset, numberToWrite);
@@ -665,59 +700,55 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Internal version of {@link #writeTo(OutputStream,int,int)} that assumes
- * all error checking has already been done.
+ * Internal version of {@link #writeTo(OutputStream,int,int)} that assumes all error checking has
+ * already been done.
*/
abstract void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite)
throws IOException;
/**
- * Writes this {@link ByteString} to the provided {@link ByteOutput}. Calling
- * this method may result in multiple operations on the target {@link ByteOutput}.
+ * Writes this {@link ByteString} to the provided {@link ByteOutput}. Calling this method may
+ * result in multiple operations on the target {@link ByteOutput}.
*
* <p>This method may expose internal backing buffers of the {@link ByteString} to the {@link
* ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious
* {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution!
*
- * @param byteOutput the output target to receive the bytes
- * @throws IOException if an I/O error occurs
+ * @param byteOutput the output target to receive the bytes
+ * @throws IOException if an I/O error occurs
* @see UnsafeByteOperations#unsafeWriteTo(ByteString, ByteOutput)
*/
abstract void writeTo(ByteOutput byteOutput) throws IOException;
/**
- * Constructs a read-only {@code java.nio.ByteBuffer} whose content
- * is equal to the contents of this byte string.
- * The result uses the same backing array as the byte string, if possible.
+ * Constructs a read-only {@code java.nio.ByteBuffer} whose content is equal to the contents of
+ * this byte string. The result uses the same backing array as the byte string, if possible.
*
* @return wrapped bytes
*/
public abstract ByteBuffer asReadOnlyByteBuffer();
/**
- * Constructs a list of read-only {@code java.nio.ByteBuffer} objects
- * such that the concatenation of their contents is equal to the contents
- * of this byte string. The result uses the same backing arrays as the
- * byte string.
- * <p>
- * By returning a list, implementations of this method may be able to avoid
- * copying even when there are multiple backing arrays.
+ * Constructs a list of read-only {@code java.nio.ByteBuffer} objects such that the concatenation
+ * of their contents is equal to the contents of this byte string. The result uses the same
+ * backing arrays as the byte string.
+ *
+ * <p>By returning a list, implementations of this method may be able to avoid copying even when
+ * there are multiple backing arrays.
*
* @return a list of wrapped bytes
*/
public abstract List<ByteBuffer> asReadOnlyByteBufferList();
/**
- * Constructs a new {@code String} by decoding the bytes using the
- * specified charset.
+ * Constructs a new {@code String} by decoding the bytes using the specified charset.
*
* @param charsetName encode using this charset
* @return new string
* @throws UnsupportedEncodingException if charset isn't recognized
*/
- public final String toString(String charsetName)
- throws UnsupportedEncodingException {
+ public final String toString(String charsetName) throws UnsupportedEncodingException {
try {
return toString(Charset.forName(charsetName));
} catch (UnsupportedCharsetException e) {
@@ -728,8 +759,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Constructs a new {@code String} by decoding the bytes using the
- * specified charset. Returns the same empty String if empty.
+ * Constructs a new {@code String} by decoding the bytes using the specified charset. Returns the
+ * same empty String if empty.
*
* @param charset encode using this charset
* @return new string
@@ -739,8 +770,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Constructs a new {@code String} by decoding the bytes using the
- * specified charset.
+ * Constructs a new {@code String} by decoding the bytes using the specified charset.
*
* @param charset encode using this charset
* @return new string
@@ -760,50 +790,45 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Tells whether this {@code ByteString} represents a well-formed UTF-8
- * byte sequence, such that the original bytes can be converted to a
- * String object and then round tripped back to bytes without loss.
+ * Tells whether this {@code ByteString} represents a well-formed UTF-8 byte sequence, such that
+ * the original bytes can be converted to a String object and then round tripped back to bytes
+ * without loss.
+ *
+ * <p>More precisely, returns {@code true} whenever:
*
- * <p>More precisely, returns {@code true} whenever: <pre> {@code
+ * <pre>{@code
* Arrays.equals(byteString.toByteArray(),
* new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8"))
* }</pre>
*
- * <p>This method returns {@code false} for "overlong" byte sequences,
- * as well as for 3-byte sequences that would map to a surrogate
- * character, in accordance with the restricted definition of UTF-8
- * introduced in Unicode 3.1. Note that the UTF-8 decoder included in
- * Oracle's JDK has been modified to also reject "overlong" byte
- * sequences, but (as of 2011) still accepts 3-byte surrogate
- * character byte sequences.
+ * <p>This method returns {@code false} for "overlong" byte sequences, as well as for 3-byte
+ * sequences that would map to a surrogate character, in accordance with the restricted definition
+ * of UTF-8 introduced in Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has
+ * been modified to also reject "overlong" byte sequences, but (as of 2011) still accepts 3-byte
+ * surrogate character byte sequences.
*
* <p>See the Unicode Standard,<br>
* Table 3-6. <em>UTF-8 Bit Distribution</em>,<br>
* Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>.
*
- * @return whether the bytes in this {@code ByteString} are a
- * well-formed UTF-8 byte sequence
+ * @return whether the bytes in this {@code ByteString} are a well-formed UTF-8 byte sequence
*/
public abstract boolean isValidUtf8();
/**
- * Tells whether the given byte sequence is a well-formed, malformed, or
- * incomplete UTF-8 byte sequence. This method accepts and returns a partial
- * state result, allowing the bytes for a complete UTF-8 byte sequence to be
- * composed from multiple {@code ByteString} segments.
- *
- * @param state either {@code 0} (if this is the initial decoding operation)
- * or the value returned from a call to a partial decoding method for the
- * previous bytes
+ * Tells whether the given byte sequence is a well-formed, malformed, or incomplete UTF-8 byte
+ * sequence. This method accepts and returns a partial state result, allowing the bytes for a
+ * complete UTF-8 byte sequence to be composed from multiple {@code ByteString} segments.
+ *
+ * @param state either {@code 0} (if this is the initial decoding operation) or the value returned
+ * from a call to a partial decoding method for the previous bytes
* @param offset offset of the first byte to check
* @param length number of bytes to check
- *
- * @return {@code -1} if the partial byte sequence is definitely malformed,
- * {@code 0} if it is well-formed (no additional input needed), or, if the
- * byte sequence is "incomplete", i.e. apparently terminated in the middle of
- * a character, an opaque integer "state" value containing enough information
- * to decode the character when passed to a subsequent invocation of a
- * partial decoding method.
+ * @return {@code -1} if the partial byte sequence is definitely malformed, {@code 0} if it is
+ * well-formed (no additional input needed), or, if the byte sequence is "incomplete", i.e.
+ * apparently terminated in the middle of a character, an opaque integer "state" value
+ * containing enough information to decode the character when passed to a subsequent
+ * invocation of a partial decoding method.
*/
protected abstract int partialIsValidUtf8(int state, int offset, int length);
@@ -813,9 +838,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
@Override
public abstract boolean equals(Object o);
- /**
- * Base class for leaf {@link ByteString}s (i.e. non-ropes).
- */
+ /** Base class for leaf {@link ByteString}s (i.e. non-ropes). */
abstract static class LeafByteString extends ByteString {
@Override
protected final int getTreeDepth() {
@@ -829,10 +852,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
- * Check equality of the substring of given length of this object starting at
- * zero with another {@code ByteString} substring starting at offset.
+ * Check equality of the substring of given length of this object starting at zero with another
+ * {@code ByteString} substring starting at offset.
*
- * @param other what to compare a substring in
+ * @param other what to compare a substring in
* @param offset offset into other
* @param length number of bytes to compare
* @return true for equality of substrings, else false.
@@ -841,8 +864,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Compute the hashCode using the traditional algorithm from {@link
- * ByteString}.
+ * Compute the hashCode using the traditional algorithm from {@link ByteString}.
*
* @return hashCode value
*/
@@ -866,26 +888,23 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Creates an {@code InputStream} which can be used to read the bytes.
- * <p>
- * The {@link InputStream} returned by this method is guaranteed to be
- * completely non-blocking. The method {@link InputStream#available()}
- * returns the number of bytes remaining in the stream. The methods
- * {@link InputStream#read(byte[])}, {@link InputStream#read(byte[],int,int)}
- * and {@link InputStream#skip(long)} will read/skip as many bytes as are
- * available. The method {@link InputStream#markSupported()} returns
- * {@code true}.
- * <p>
- * The methods in the returned {@link InputStream} might <b>not</b> be
- * thread safe.
+ *
+ * <p>The {@link InputStream} returned by this method is guaranteed to be completely non-blocking.
+ * The method {@link InputStream#available()} returns the number of bytes remaining in the stream.
+ * The methods {@link InputStream#read(byte[])}, {@link InputStream#read(byte[],int,int)} and
+ * {@link InputStream#skip(long)} will read/skip as many bytes as are available. The method {@link
+ * InputStream#markSupported()} returns {@code true}.
+ *
+ * <p>The methods in the returned {@link InputStream} might <b>not</b> be thread safe.
*
* @return an input stream that returns the bytes of this byte string.
*/
public abstract InputStream newInput();
/**
- * Creates a {@link CodedInputStream} which can be used to read the bytes.
- * Using this is often more efficient than creating a {@link CodedInputStream}
- * that wraps the result of {@link #newInput()}.
+ * Creates a {@link CodedInputStream} which can be used to read the bytes. Using this is often
+ * more efficient than creating a {@link CodedInputStream} that wraps the result of {@link
+ * #newInput()}.
*
* @return stream based on wrapped data
*/
@@ -897,10 +916,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Creates a new {@link Output} with the given initial capacity. Call {@link
* Output#toByteString()} to create the {@code ByteString} instance.
- * <p>
- * A {@link ByteString.Output} offers the same functionality as a
- * {@link ByteArrayOutputStream}, except that it returns a {@link ByteString}
- * rather than a {@code byte} array.
+ *
+ * <p>A {@link ByteString.Output} offers the same functionality as a {@link
+ * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte}
+ * array.
*
* @param initialCapacity estimate of number of bytes to be written
* @return {@code OutputStream} for building a {@code ByteString}
@@ -910,12 +929,12 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Creates a new {@link Output}. Call {@link Output#toByteString()} to create
- * the {@code ByteString} instance.
- * <p>
- * A {@link ByteString.Output} offers the same functionality as a
- * {@link ByteArrayOutputStream}, except that it returns a {@link ByteString}
- * rather than a {@code byte array}.
+ * Creates a new {@link Output}. Call {@link Output#toByteString()} to create the {@code
+ * ByteString} instance.
+ *
+ * <p>A {@link ByteString.Output} offers the same functionality as a {@link
+ * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte
+ * array}.
*
* @return {@code OutputStream} for building a {@code ByteString}
*/
@@ -924,8 +943,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to
- * create the {@code ByteString} instance.
+ * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to create the {@code
+ * ByteString} instance.
*/
public static final class Output extends OutputStream {
// Implementation note.
@@ -947,10 +966,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
private int bufferPos;
/**
- * Creates a new ByteString output stream with the specified
- * initial capacity.
+ * Creates a new ByteString output stream with the specified initial capacity.
*
- * @param initialCapacity the initial capacity of the output stream.
+ * @param initialCapacity the initial capacity of the output stream.
*/
Output(int initialCapacity) {
if (initialCapacity < 0) {
@@ -966,43 +984,41 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
if (bufferPos == buffer.length) {
flushFullBuffer(1);
}
- buffer[bufferPos++] = (byte)b;
+ buffer[bufferPos++] = (byte) b;
}
@Override
- public synchronized void write(byte[] b, int offset, int length) {
+ public synchronized void write(byte[] b, int offset, int length) {
if (length <= buffer.length - bufferPos) {
// The bytes can fit into the current buffer.
System.arraycopy(b, offset, buffer, bufferPos, length);
bufferPos += length;
} else {
// Use up the current buffer
- int copySize = buffer.length - bufferPos;
+ int copySize = buffer.length - bufferPos;
System.arraycopy(b, offset, buffer, bufferPos, copySize);
offset += copySize;
length -= copySize;
// Flush the buffer, and get a new buffer at least big enough to cover
// what we still need to output
flushFullBuffer(length);
- System.arraycopy(b, offset, buffer, 0 /* count */, length);
+ System.arraycopy(b, offset, buffer, /* count= */ 0, length);
bufferPos = length;
}
}
/**
- * Creates a byte string. Its size is the current size of this output
- * stream and its output has been copied to it.
+ * Creates a byte string. Its size is the current size of this output stream and its output has
+ * been copied to it.
*
- * @return the current contents of this output stream, as a byte string.
+ * @return the current contents of this output stream, as a byte string.
*/
public synchronized ByteString toByteString() {
flushLastBuffer();
return ByteString.copyFrom(flushedBuffers);
}
- /**
- * Implement java.util.Arrays.copyOf() for jdk 1.5.
- */
+ /** Implement java.util.Arrays.copyOf() for jdk 1.5. */
private byte[] copyArray(byte[] buffer, int length) {
byte[] result = new byte[length];
System.arraycopy(buffer, 0, result, 0, Math.min(buffer.length, length));
@@ -1010,11 +1026,11 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Writes the complete contents of this byte array output stream to
- * the specified output stream argument.
+ * Writes the complete contents of this byte array output stream to the specified output stream
+ * argument.
*
* @param out the output stream to which to write the data.
- * @throws IOException if an I/O error occurs.
+ * @throws IOException if an I/O error occurs.
*/
public void writeTo(OutputStream out) throws IOException {
ByteString[] cachedFlushBuffers;
@@ -1023,8 +1039,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
synchronized (this) {
// Copy the information we need into local variables so as to hold
// the lock for as short a time as possible.
- cachedFlushBuffers =
- flushedBuffers.toArray(new ByteString[flushedBuffers.size()]);
+ cachedFlushBuffers = flushedBuffers.toArray(new ByteString[flushedBuffers.size()]);
cachedBuffer = buffer;
cachedBufferPos = bufferPos;
}
@@ -1038,16 +1053,15 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
/**
* Returns the current size of the output stream.
*
- * @return the current size of the output stream
+ * @return the current size of the output stream
*/
public synchronized int size() {
return flushedBuffersTotalBytes + bufferPos;
}
/**
- * Resets this stream, so that all currently accumulated output in the
- * output stream is discarded. The output stream can be used again,
- * reusing the already allocated buffer space.
+ * Resets this stream, so that all currently accumulated output in the output stream is
+ * discarded. The output stream can be used again, reusing the already allocated buffer space.
*/
public synchronized void reset() {
flushedBuffers.clear();
@@ -1057,32 +1071,31 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
@Override
public String toString() {
- return String.format("<ByteString.Output@%s size=%d>",
+ return String.format(
+ "<ByteString.Output@%s size=%d>",
Integer.toHexString(System.identityHashCode(this)), size());
}
/**
- * Internal function used by writers. The current buffer is full, and the
- * writer needs a new buffer whose size is at least the specified minimum
- * size.
+ * Internal function used by writers. The current buffer is full, and the writer needs a new
+ * buffer whose size is at least the specified minimum size.
*/
- private void flushFullBuffer(int minSize) {
+ private void flushFullBuffer(int minSize) {
flushedBuffers.add(new LiteralByteString(buffer));
flushedBuffersTotalBytes += buffer.length;
// We want to increase our total capacity by 50%, but as a minimum,
// the new buffer should also at least be >= minSize and
// >= initial Capacity.
- int newSize = Math.max(initialCapacity,
- Math.max(minSize, flushedBuffersTotalBytes >>> 1));
+ int newSize = Math.max(initialCapacity, Math.max(minSize, flushedBuffersTotalBytes >>> 1));
buffer = new byte[newSize];
bufferPos = 0;
}
/**
- * Internal function used by {@link #toByteString()}. The current buffer may
- * or may not be full, but it needs to be flushed.
+ * Internal function used by {@link #toByteString()}. The current buffer may or may not be full,
+ * but it needs to be flushed.
*/
- private void flushLastBuffer() {
+ private void flushLastBuffer() {
if (bufferPos < buffer.length) {
if (bufferPos > 0) {
byte[] bufferCopy = copyArray(buffer, bufferPos);
@@ -1105,17 +1118,15 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Constructs a new {@code ByteString} builder, which allows you to
- * efficiently construct a {@code ByteString} by writing to a {@link
- * CodedOutputStream}. Using this is much more efficient than calling {@code
- * newOutput()} and wrapping that in a {@code CodedOutputStream}.
+ * Constructs a new {@code ByteString} builder, which allows you to efficiently construct a {@code
+ * ByteString} by writing to a {@link CodedOutputStream}. Using this is much more efficient than
+ * calling {@code newOutput()} and wrapping that in a {@code CodedOutputStream}.
*
- * <p>This is package-private because it's a somewhat confusing interface.
- * Users can call {@link Message#toByteString()} instead of calling this
- * directly.
+ * <p>This is package-private because it's a somewhat confusing interface. Users can call {@link
+ * Message#toByteString()} instead of calling this directly.
*
- * @param size The target byte size of the {@code ByteString}. You must write
- * exactly this many bytes before building the result.
+ * @param size The target byte size of the {@code ByteString}. You must write exactly this many
+ * bytes before building the result.
* @return the builder
*/
static CodedBuilder newCodedBuilder(int size) {
@@ -1151,16 +1162,16 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// public API.
/**
- * Return the depth of the tree representing this {@code ByteString}, if any,
- * whose root is this node. If this is a leaf node, return 0.
+ * Return the depth of the tree representing this {@code ByteString}, if any, whose root is this
+ * node. If this is a leaf node, return 0.
*
* @return tree depth or zero
*/
protected abstract int getTreeDepth();
/**
- * Return {@code true} if this ByteString is literal (a leaf node) or a
- * flat-enough tree in the sense of {@link RopeByteString}.
+ * Return {@code true} if this ByteString is literal (a leaf node) or a flat-enough tree in the
+ * sense of {@link RopeByteString}.
*
* @return true if the tree is flat enough
*/
@@ -1176,10 +1187,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Compute the hash across the value bytes starting with the given hash, and
- * return the result. This is used to compute the hash across strings
- * represented as a set of pieces by allowing the hash computation to be
- * continued from piece to piece.
+ * Compute the hash across the value bytes starting with the given hash, and return the result.
+ * This is used to compute the hash across strings represented as a set of pieces by allowing the
+ * hash computation to be continued from piece to piece.
*
* @param h starting hash value
* @param offset offset into this value to start looking at data values
@@ -1231,16 +1241,15 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
@Override
public final String toString() {
- return String.format("<ByteString@%s size=%d>",
- Integer.toHexString(System.identityHashCode(this)), size());
+ return String.format(
+ "<ByteString@%s size=%d>", Integer.toHexString(System.identityHashCode(this)), size());
}
/**
- * This class implements a {@link com.google.protobuf.ByteString} backed by a
- * single array of bytes, contiguous in memory. It supports substring by
- * pointing to only a sub-range of the underlying byte array, meaning that a
- * substring will reference the full byte-array of the string it's made from,
- * exactly as with {@link String}.
+ * This class implements a {@link com.google.protobuf.ByteString} backed by a single array of
+ * bytes, contiguous in memory. It supports substring by pointing to only a sub-range of the
+ * underlying byte array, meaning that a substring will reference the full byte-array of the
+ * string it's made from, exactly as with {@link String}.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -1252,12 +1261,14 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
protected final byte[] bytes;
/**
- * Creates a {@code LiteralByteString} backed by the given array, without
- * copying.
+ * Creates a {@code LiteralByteString} backed by the given array, without copying.
*
* @param bytes array to wrap
*/
LiteralByteString(byte[] bytes) {
+ if (bytes == null) {
+ throw new NullPointerException();
+ }
this.bytes = bytes;
}
@@ -1388,10 +1399,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Check equality of the substring of given length of this object starting at
- * zero with another {@code LiteralByteString} substring starting at offset.
+ * Check equality of the substring of given length of this object starting at zero with another
+ * {@code LiteralByteString} substring starting at offset.
*
- * @param other what to compare a substring in
+ * @param other what to compare a substring in
* @param offset offset into other
* @param length number of bytes to compare
* @return true for equality of substrings, else false.
@@ -1411,10 +1422,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
byte[] thisBytes = bytes;
byte[] otherBytes = lbsOther.bytes;
int thisLimit = getOffsetIntoBytes() + length;
- for (
- int thisIndex = getOffsetIntoBytes(),
+ for (int thisIndex = getOffsetIntoBytes(),
otherIndex = lbsOther.getOffsetIntoBytes() + offset;
- (thisIndex < thisLimit); ++thisIndex, ++otherIndex) {
+ (thisIndex < thisLimit);
+ ++thisIndex, ++otherIndex) {
if (thisBytes[thisIndex] != otherBytes[otherIndex]) {
return false;
}
@@ -1443,7 +1454,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// We trust CodedInputStream not to modify the bytes, or to give anyone
// else access to them.
return CodedInputStream.newInstance(
- bytes, getOffsetIntoBytes(), size(), true /* bufferIsImmutable */);
+ bytes, getOffsetIntoBytes(), size(), /* bufferIsImmutable= */ true);
}
// =================================================================
@@ -1460,14 +1471,12 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * This class is used to represent the substring of a {@link ByteString} over a
- * single byte array. In terms of the public API of {@link ByteString}, you end
- * up here by calling {@link ByteString#copyFrom(byte[])} followed by {@link
- * ByteString#substring(int, int)}.
+ * This class is used to represent the substring of a {@link ByteString} over a single byte array.
+ * In terms of the public API of {@link ByteString}, you end up here by calling {@link
+ * ByteString#copyFrom(byte[])} followed by {@link ByteString#substring(int, int)}.
*
- * <p>This class contains most of the overhead involved in creating a substring
- * from a {@link LiteralByteString}. The overhead involves some range-checking
- * and two extra fields.
+ * <p>This class contains most of the overhead involved in creating a substring from a {@link
+ * LiteralByteString}. The overhead involves some range-checking and two extra fields.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -1479,15 +1488,13 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
private final int bytesLength;
/**
- * Creates a {@code BoundedByteString} backed by the sub-range of given array,
- * without copying.
+ * Creates a {@code BoundedByteString} backed by the sub-range of given array, without copying.
*
- * @param bytes array to wrap
+ * @param bytes array to wrap
* @param offset index to first byte to use in bytes
* @param length number of bytes to use from bytes
- * @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0},
- * or if {@code offset + length >
- * bytes.length}.
+ * @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0}, or if {@code
+ * offset + length > bytes.length}.
*/
BoundedByteString(byte[] bytes, int offset, int length) {
super(bytes);
@@ -1498,10 +1505,9 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
- * Gets the byte at the given index.
- * Throws {@link ArrayIndexOutOfBoundsException}
- * for backwards-compatibility reasons although it would more properly be
- * {@link IndexOutOfBoundsException}.
+ * Gets the byte at the given index. Throws {@link ArrayIndexOutOfBoundsException} for
+ * backwards-compatibility reasons although it would more properly be {@link
+ * IndexOutOfBoundsException}.
*
* @param index index of byte
* @return the value
@@ -1529,10 +1535,10 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
// ByteString -> byte[]
@Override
- protected void copyToInternal(byte[] target, int sourceOffset, int targetOffset,
- int numberToCopy) {
- System.arraycopy(bytes, getOffsetIntoBytes() + sourceOffset, target,
- targetOffset, numberToCopy);
+ protected void copyToInternal(
+ byte[] target, int sourceOffset, int targetOffset, int numberToCopy) {
+ System.arraycopy(
+ bytes, getOffsetIntoBytes() + sourceOffset, target, targetOffset, numberToCopy);
}
// =================================================================
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 1297462e..df4cc664 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -64,12 +64,6 @@ public abstract class CodedInputStream {
// Integer.MAX_VALUE == 0x7FFFFFF == INT_MAX from limits.h
private static final int DEFAULT_SIZE_LIMIT = Integer.MAX_VALUE;
- /**
- * Whether to enable our custom UTF-8 decode codepath which does not use {@link StringCoding}.
- * Currently disabled.
- */
- private static final boolean ENABLE_CUSTOM_UTF8_DECODE = false;
-
/** Visible for subclasses. See setRecursionLimit() */
int recursionDepth;
@@ -83,8 +77,11 @@ public abstract class CodedInputStream {
return newInstance(input, DEFAULT_BUFFER_SIZE);
}
- /** Create a new CodedInputStream wrapping the given InputStream. */
- static CodedInputStream newInstance(final InputStream input, int bufferSize) {
+ /** Create a new CodedInputStream wrapping the given InputStream, with a specified buffer size. */
+ public static CodedInputStream newInstance(final InputStream input, int bufferSize) {
+ if (bufferSize <= 0) {
+ throw new IllegalArgumentException("bufferSize must be > 0");
+ }
if (input == null) {
// TODO(nathanmittler): Ideally we should throw here. This is done for backward compatibility.
return newInstance(EMPTY_BYTE_ARRAY);
@@ -136,7 +133,7 @@ public abstract class CodedInputStream {
/** Create a new CodedInputStream wrapping the given byte array slice. */
public static CodedInputStream newInstance(final byte[] buf, final int off, final int len) {
- return newInstance(buf, off, len, false /* bufferIsImmutable */);
+ return newInstance(buf, off, len, /* bufferIsImmutable= */ false);
}
/** Create a new CodedInputStream wrapping the given byte array slice. */
@@ -172,7 +169,7 @@ public abstract class CodedInputStream {
* trying to alter the ByteBuffer's status.
*/
public static CodedInputStream newInstance(ByteBuffer buf) {
- return newInstance(buf, false /* bufferIsImmutable */);
+ return newInstance(buf, /* bufferIsImmutable= */ false);
}
/** Create a new CodedInputStream wrapping the given buffer. */
@@ -416,22 +413,7 @@ 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;
- }
+ private boolean shouldDiscardUnknownFields = false;
/**
* Sets this {@code CodedInputStream} to discard unknown fields. Only applies to full runtime
@@ -442,7 +424,7 @@ public abstract class CodedInputStream {
* runtime.
*/
final void discardUnknownFields() {
- explicitDiscardUnknownFields = true;
+ shouldDiscardUnknownFields = true;
}
/**
@@ -450,7 +432,7 @@ public abstract class CodedInputStream {
* default.
*/
final void unsetDiscardUnknownFields() {
- explicitDiscardUnknownFields = false;
+ shouldDiscardUnknownFields = false;
}
/**
@@ -458,19 +440,7 @@ public abstract class CodedInputStream {
* 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;
+ return shouldDiscardUnknownFields;
}
/**
@@ -831,19 +801,9 @@ public abstract class CodedInputStream {
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= (limit - pos)) {
- if (ENABLE_CUSTOM_UTF8_DECODE) {
- String result = Utf8.decodeUtf8(buffer, pos, size);
- pos += size;
- return result;
- } else {
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(buffer, pos, pos + size)) {
- throw InvalidProtocolBufferException.invalidUtf8();
- }
- final int tempPos = pos;
- pos += size;
- return new String(buffer, tempPos, size, UTF_8);
- }
+ String result = Utf8.decodeUtf8(buffer, pos, size);
+ pos += size;
+ return result;
}
if (size == 0) {
@@ -1559,25 +1519,10 @@ public abstract class CodedInputStream {
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= remaining()) {
- if (ENABLE_CUSTOM_UTF8_DECODE) {
- final int bufferPos = bufferPos(pos);
- String result = Utf8.decodeUtf8(buffer, bufferPos, size);
- pos += size;
- return result;
- } else {
- // TODO(nathanmittler): Is there a way to avoid this copy?
- // 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();
- }
-
- String result = new String(bytes, UTF_8);
- pos += size;
- return result;
- }
+ final int bufferPos = bufferPos(pos);
+ String result = Utf8.decodeUtf8(buffer, bufferPos, size);
+ pos += size;
+ return result;
}
if (size == 0) {
@@ -2345,15 +2290,7 @@ public abstract class CodedInputStream {
bytes = readRawBytesSlowPath(size);
tempPos = 0;
}
- if (ENABLE_CUSTOM_UTF8_DECODE) {
- return Utf8.decodeUtf8(bytes, tempPos, size);
- } else {
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(bytes, tempPos, tempPos + size)) {
- throw InvalidProtocolBufferException.invalidUtf8();
- }
- return new String(bytes, tempPos, size, UTF_8);
- }
+ return Utf8.decodeUtf8(bytes, tempPos, size);
}
@Override
@@ -3373,34 +3310,15 @@ public abstract class CodedInputStream {
public String readStringRequireUtf8() throws IOException {
final int size = readRawVarint32();
if (size > 0 && size <= currentByteBufferLimit - currentByteBufferPos) {
- if (ENABLE_CUSTOM_UTF8_DECODE) {
- final int bufferPos = (int) (currentByteBufferPos - currentByteBufferStartPos);
- String result = Utf8.decodeUtf8(currentByteBuffer, bufferPos, size);
- currentByteBufferPos += size;
- return result;
- } else {
- 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;
- }
+ final int bufferPos = (int) (currentByteBufferPos - currentByteBufferStartPos);
+ String result = Utf8.decodeUtf8(currentByteBuffer, bufferPos, size);
+ currentByteBufferPos += size;
+ return result;
}
if (size >= 0 && size <= remaining()) {
byte[] bytes = new byte[size];
readRawBytesTo(bytes, 0, size);
- if (ENABLE_CUSTOM_UTF8_DECODE) {
- return Utf8.decodeUtf8(bytes, 0, size);
- } else {
- if (!Utf8.isValidUtf8(bytes)) {
- throw InvalidProtocolBufferException.invalidUtf8();
- }
- String result = new String(bytes, UTF_8);
- return result;
- }
+ return Utf8.decodeUtf8(bytes, 0, size);
}
if (size == 0) {
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 7b1ac651..975cb90e 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
@@ -47,12 +47,11 @@ import java.util.logging.Logger;
/**
* Encodes and writes protocol message fields.
*
- * <p>This class contains two kinds of methods: methods that write specific
- * protocol message constructs and field types (e.g. {@link #writeTag} and
- * {@link #writeInt32}) and methods that write low-level values (e.g.
- * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are
- * writing encoded protocol messages, you should use the former methods, but if
- * you are writing some other format of your own design, use the latter.
+ * <p>This class contains two kinds of methods: methods that write specific protocol message
+ * constructs and field types (e.g. {@link #writeTag} and {@link #writeInt32}) and methods that
+ * write low-level values (e.g. {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are
+ * writing encoded protocol messages, you should use the former methods, but if you are writing some
+ * other format of your own design, use the latter.
*
* <p>This class is totally unsynchronized.
*/
@@ -60,23 +59,17 @@ 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();
- /**
- * @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead.
- */
- @Deprecated
- public static final int LITTLE_ENDIAN_32_SIZE = FIXED32_SIZE;
+ /** @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead. */
+ @Deprecated public static final int LITTLE_ENDIAN_32_SIZE = FIXED32_SIZE;
- /**
- * The buffer size used in {@link #newInstance(OutputStream)}.
- */
+ /** The buffer size used in {@link #newInstance(OutputStream)}. */
public static final int DEFAULT_BUFFER_SIZE = 4096;
/**
- * Returns the buffer size to efficiently write dataLength bytes to this
- * CodedOutputStream. Used by AbstractMessageLite.
+ * Returns the buffer size to efficiently write dataLength bytes to this CodedOutputStream. Used
+ * by AbstractMessageLite.
*
- * @return the buffer size to efficiently write dataLength bytes to this
- * CodedOutputStream.
+ * @return the buffer size to efficiently write dataLength bytes to this CodedOutputStream.
*/
static int computePreferredBufferSize(int dataLength) {
if (dataLength > DEFAULT_BUFFER_SIZE) {
@@ -88,9 +81,9 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
* Create a new {@code CodedOutputStream} wrapping the given {@code OutputStream}.
*
- * <p> NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or
- * modify the provided byte arrays. Doing so may result in corrupted data, which would be
- * difficult to debug.
+ * <p>NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or modify
+ * the provided byte arrays. Doing so may result in corrupted data, which would be difficult to
+ * debug.
*/
public static CodedOutputStream newInstance(final OutputStream output) {
return newInstance(output, DEFAULT_BUFFER_SIZE);
@@ -100,30 +93,28 @@ public abstract class CodedOutputStream extends ByteOutput {
* Create a new {@code CodedOutputStream} wrapping the given {@code OutputStream} with a given
* buffer size.
*
- * <p> NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or
- * modify the provided byte arrays. Doing so may result in corrupted data, which would be
- * difficult to debug.
+ * <p>NOTE: The provided {@link OutputStream} <strong>MUST NOT</strong> retain access or modify
+ * the provided byte arrays. Doing so may result in corrupted data, which would be difficult to
+ * debug.
*/
public static CodedOutputStream newInstance(final OutputStream output, final int bufferSize) {
return new OutputStreamEncoder(output, bufferSize);
}
/**
- * Create a new {@code CodedOutputStream} that writes directly to the given
- * byte array. If more bytes are written than fit in the array,
- * {@link OutOfSpaceException} will be thrown. Writing directly to a flat
- * array is faster than writing to an {@code OutputStream}. See also
- * {@link ByteString#newCodedBuilder}.
+ * Create a new {@code CodedOutputStream} that writes directly to the given byte array. If more
+ * bytes are written than fit in the array, {@link OutOfSpaceException} will be thrown. Writing
+ * directly to a flat array is faster than writing to an {@code OutputStream}. See also {@link
+ * ByteString#newCodedBuilder}.
*/
public static CodedOutputStream newInstance(final byte[] flatArray) {
return newInstance(flatArray, 0, flatArray.length);
}
/**
- * Create a new {@code CodedOutputStream} that writes directly to the given
- * byte array slice. If more bytes are written than fit in the slice,
- * {@link OutOfSpaceException} will be thrown. Writing directly to a flat
- * array is faster than writing to an {@code OutputStream}. See also
+ * Create a new {@code CodedOutputStream} that writes directly to the given byte array slice. If
+ * more bytes are written than fit in the slice, {@link OutOfSpaceException} will be thrown.
+ * Writing directly to a flat array is faster than writing to an {@code OutputStream}. See also
* {@link ByteString#newCodedBuilder}.
*/
public static CodedOutputStream newInstance(
@@ -162,9 +153,9 @@ public abstract class CodedOutputStream extends ByteOutput {
* implies:
*
* <ul>
- * <li>repeated serialization of a message will return the same bytes
- * <li>different processes of the same binary (which may be executing on different machines) will
- * serialize equal messages to the same bytes.
+ * <li>repeated serialization of a message will return the same bytes
+ * <li>different processes of the same binary (which may be executing on different machines)
+ * will serialize equal messages to the same bytes.
* </ul>
*
* <p>Note the deterministic serialization is NOT canonical across languages; it is also unstable
@@ -173,14 +164,14 @@ public abstract class CodedOutputStream extends ByteOutput {
* their own canonicalization specification and implement the serializer using reflection APIs
* rather than relying on this API.
*
- * <p> Once set, the serializer will: (Note this is an implementation detail and may subject to
+ * <p>Once set, the serializer will: (Note this is an implementation detail and may subject to
* change in the future)
*
* <ul>
- * <li> sort map entries by keys in lexicographical order or numerical order. Note: For string
- * keys, the order is based on comparing the Unicode value of each character in the strings.
- * The order may be different from the deterministic serialization in other languages where
- * maps are sorted on the lexicographical order of the UTF8 encoded keys.
+ * <li>sort map entries by keys in lexicographical order or numerical order. Note: For string
+ * keys, the order is based on comparing the Unicode value of each character in the strings.
+ * The order may be different from the deterministic serialization in other languages where
+ * maps are sorted on the lexicographical order of the UTF8 encoded keys.
* </ul>
*/
public void useDeterministicSerialization() {
@@ -190,31 +181,32 @@ public abstract class CodedOutputStream extends ByteOutput {
boolean isSerializationDeterministic() {
return serializationDeterministic;
}
+
private boolean serializationDeterministic;
/**
* Create a new {@code CodedOutputStream} that writes to the given {@link ByteBuffer}.
*
* @deprecated the size parameter is no longer used since use of an internal buffer is useless
- * (and wasteful) when writing to a {@link ByteBuffer}. Use {@link #newInstance(ByteBuffer)}
- * instead.
+ * (and wasteful) when writing to a {@link ByteBuffer}. Use {@link #newInstance(ByteBuffer)}
+ * instead.
*/
@Deprecated
- public static CodedOutputStream newInstance(ByteBuffer byteBuffer,
- @SuppressWarnings("unused") int unused) {
+ public static CodedOutputStream newInstance(
+ ByteBuffer byteBuffer, @SuppressWarnings("unused") int unused) {
return newInstance(byteBuffer);
}
/**
* Create a new {@code CodedOutputStream} that writes to the provided {@link ByteOutput}.
*
- * <p> NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing
- * so may result in corrupted data, which would be difficult to debug.
+ * <p>NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing so
+ * may result in corrupted data, which would be difficult to debug.
*
* @param byteOutput the output target for encoded bytes.
* @param bufferSize the size of the internal scratch buffer to be used for string encoding.
- * Setting this to {@code 0} will disable buffering, requiring an allocation for each encoded
- * string.
+ * Setting this to {@code 0} will disable buffering, requiring an allocation for each encoded
+ * string.
*/
static CodedOutputStream newInstance(ByteOutput byteOutput, int bufferSize) {
if (bufferSize < 0) {
@@ -225,8 +217,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
// Disallow construction outside of this class.
- private CodedOutputStream() {
- }
+ private CodedOutputStream() {}
// -----------------------------------------------------------------
@@ -294,8 +285,8 @@ public abstract class CodedOutputStream extends ByteOutput {
public abstract void writeBool(int fieldNumber, boolean value) throws IOException;
/**
- * Write an enum field, including tag, to the stream. The provided value is the numeric
- * value used to represent the enum value on the wire (not the enum ordinal value).
+ * Write an enum field, including tag, to the stream. The provided value is the numeric value used
+ * to represent the enum value on the wire (not the enum ordinal value).
*/
public final void writeEnum(final int fieldNumber, final int value) throws IOException {
writeInt32(fieldNumber, value);
@@ -319,21 +310,17 @@ public abstract class CodedOutputStream extends ByteOutput {
throws IOException;
/**
- * Write a {@code bytes} field, including tag, to the stream.
- * This method will write all content of the ByteBuffer regardless of the
- * current position and limit (i.e., the number of bytes to be written is
- * value.capacity(), not value.remaining()). Furthermore, this method doesn't
- * alter the state of the passed-in ByteBuffer. Its position, limit, mark,
- * etc. will remain unchanged. If you only want to write the remaining bytes
- * of a ByteBuffer, you can call
- * {@code writeByteBuffer(fieldNumber, byteBuffer.slice())}.
+ * Write a {@code bytes} field, including tag, to the stream. This method will write all content
+ * of the ByteBuffer regardless of the current position and limit (i.e., the number of bytes to be
+ * written is value.capacity(), not value.remaining()). Furthermore, this method doesn't alter the
+ * state of the passed-in ByteBuffer. Its position, limit, mark, etc. will remain unchanged. If
+ * you only want to write the remaining bytes of a ByteBuffer, you can call {@code
+ * writeByteBuffer(fieldNumber, byteBuffer.slice())}.
*/
// Abstract to avoid overhead of additional virtual method calls.
public abstract void writeByteBuffer(int fieldNumber, ByteBuffer value) throws IOException;
- /**
- * Write a single byte.
- */
+ /** Write a single byte. */
public final void writeRawByte(final byte value) throws IOException {
write(value);
}
@@ -348,9 +335,7 @@ public abstract class CodedOutputStream extends ByteOutput {
write(value, 0, value.length);
}
- /**
- * Write part of an array of bytes.
- */
+ /** Write part of an array of bytes. */
public final void writeRawBytes(final byte[] value, int offset, int length) throws IOException {
write(value, offset, length);
}
@@ -361,13 +346,11 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Write a ByteBuffer. This method will write all content of the ByteBuffer
- * regardless of the current position and limit (i.e., the number of bytes
- * to be written is value.capacity(), not value.remaining()). Furthermore,
- * this method doesn't alter the state of the passed-in ByteBuffer. Its
- * position, limit, mark, etc. will remain unchanged. If you only want to
- * write the remaining bytes of a ByteBuffer, you can call
- * {@code writeRawBytes(byteBuffer.slice())}.
+ * Write a ByteBuffer. This method will write all content of the ByteBuffer regardless of the
+ * current position and limit (i.e., the number of bytes to be written is value.capacity(), not
+ * value.remaining()). Furthermore, this method doesn't alter the state of the passed-in
+ * ByteBuffer. Its position, limit, mark, etc. will remain unchanged. If you only want to write
+ * the remaining bytes of a ByteBuffer, you can call {@code writeRawBytes(byteBuffer.slice())}.
*/
// Abstract to avoid overhead of additional virtual method calls.
public abstract void writeRawBytes(final ByteBuffer value) throws IOException;
@@ -379,16 +362,16 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
- * Write a MessageSet extension field to the stream. For historical reasons,
- * the wire format differs from normal fields.
+ * Write a MessageSet extension field to the stream. For historical reasons, the wire format
+ * differs from normal fields.
*/
// Abstract to avoid overhead of additional virtual method calls.
public abstract void writeMessageSetExtension(final int fieldNumber, final MessageLite value)
throws IOException;
/**
- * Write an unparsed MessageSet extension field to the stream. For
- * historical reasons, the wire format differs from normal fields.
+ * Write an unparsed MessageSet extension field to the stream. For historical reasons, the wire
+ * format differs from normal fields.
*/
// Abstract to avoid overhead of additional virtual method calls.
public abstract void writeRawMessageSetExtension(final int fieldNumber, final ByteString value)
@@ -457,8 +440,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Write an enum field to the stream. The provided value is the numeric
- * value used to represent the enum value on the wire (not the enum ordinal value).
+ * Write an enum field to the stream. The provided value is the numeric value used to represent
+ * the enum value on the wire (not the enum ordinal value).
*/
public final void writeEnumNoTag(final int value) throws IOException {
writeInt32NoTag(value);
@@ -483,7 +466,7 @@ public abstract class CodedOutputStream extends ByteOutput {
public abstract void writeMessageNoTag(final MessageLite value) throws IOException;
- //=================================================================
+ // =================================================================
@ExperimentalApi
@Override
@@ -508,161 +491,160 @@ public abstract class CodedOutputStream extends ByteOutput {
// =================================================================
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code int32} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code int32} field, including
+ * tag.
*/
public static int computeInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint32} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code uint32} field, including
+ * tag.
*/
public static int computeUInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint32} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code sint32} field, including
+ * tag.
*/
public static int computeSInt32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed32} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code fixed32} field, including
+ * tag.
*/
public static int computeFixed32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed32} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code sfixed32} field, including
+ * tag.
*/
public static int computeSFixed32Size(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code int64} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code int64} field, including
+ * tag.
*/
public static int computeInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint64} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code uint64} field, including
+ * tag.
*/
public static int computeUInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint64} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code sint64} field, including
+ * tag.
*/
public static int computeSInt64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed64} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code fixed64} field, including
+ * tag.
*/
public static int computeFixed64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed64} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code sfixed64} field, including
+ * tag.
*/
public static int computeSFixed64Size(final int fieldNumber, final long value) {
return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code float} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code float} field, including
+ * tag.
*/
public static int computeFloatSize(final int fieldNumber, final float value) {
return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code double} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code double} field, including
+ * tag.
*/
public static int computeDoubleSize(final int fieldNumber, final double value) {
return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code bool} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code bool} field, including tag.
*/
public static int computeBoolSize(final int fieldNumber, final boolean value) {
return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * enum field, including tag. The provided value is the numeric
- * value used to represent the enum value on the wire (not the enum ordinal value).
+ * Compute the number of bytes that would be needed to encode an enum field, including tag. The
+ * provided value is the numeric value used to represent the enum value on the wire (not the enum
+ * ordinal value).
*/
public static int computeEnumSize(final int fieldNumber, final int value) {
return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code string} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code string} field, including
+ * tag.
*/
public static int computeStringSize(final int fieldNumber, final String value) {
return computeTagSize(fieldNumber) + computeStringSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code bytes} field, including
+ * tag.
*/
public static int computeBytesSize(final int fieldNumber, final ByteString value) {
return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code bytes} field, including
+ * tag.
*/
public static int computeByteArraySize(final int fieldNumber, final byte[] value) {
return computeTagSize(fieldNumber) + computeByteArraySizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code bytes} field, including
+ * tag.
*/
public static int computeByteBufferSize(final int fieldNumber, final ByteBuffer value) {
return computeTagSize(fieldNumber) + computeByteBufferSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * embedded message in lazy field, including tag.
+ * Compute the number of bytes that would be needed to encode an embedded message in lazy field,
+ * including tag.
*/
public static int computeLazyFieldSize(final int fieldNumber, final LazyFieldLite value) {
return computeTagSize(fieldNumber) + computeLazyFieldSizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode an
- * embedded message field, including tag.
+ * Compute the number of bytes that would be needed to encode an embedded message field, including
+ * tag.
*/
public static int computeMessageSize(final int fieldNumber, final MessageLite value) {
return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
@@ -670,9 +652,8 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
- * Compute the number of bytes that would be needed to encode a
- * MessageSet extension to the stream. For historical reasons,
- * the wire format differs from normal fields.
+ * Compute the number of bytes that would be needed to encode a MessageSet extension to the
+ * stream. For historical reasons, the wire format differs from normal fields.
*/
public static int computeMessageSetExtensionSize(final int fieldNumber, final MessageLite value) {
return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2
@@ -681,9 +662,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Compute the number of bytes that would be needed to encode an
- * unparsed MessageSet extension field to the stream. For
- * historical reasons, the wire format differs from normal fields.
+ * Compute the number of bytes that would be needed to encode an unparsed MessageSet extension
+ * field to the stream. For historical reasons, the wire format differs from normal fields.
*/
public static int computeRawMessageSetExtensionSize(
final int fieldNumber, final ByteString value) {
@@ -693,9 +673,9 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Compute the number of bytes that would be needed to encode an
- * lazily parsed MessageSet extension field to the stream. For
- * historical reasons, the wire format differs from normal fields.
+ * Compute the number of bytes that would be needed to encode an lazily parsed MessageSet
+ * extension field to the stream. For historical reasons, the wire format differs from normal
+ * fields.
*/
public static int computeLazyFieldMessageSetExtensionSize(
final int fieldNumber, final LazyFieldLite value) {
@@ -712,8 +692,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code int32} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code int32} field, including
+ * tag.
*/
public static int computeInt32SizeNoTag(final int value) {
if (value >= 0) {
@@ -724,12 +704,9 @@ public abstract class CodedOutputStream extends ByteOutput {
}
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint32} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code uint32} field. */
public static int computeUInt32SizeNoTag(final int value) {
- if ((value & (~0 << 7)) == 0) {
+ if ((value & (~0 << 7)) == 0) {
return 1;
}
if ((value & (~0 << 14)) == 0) {
@@ -744,41 +721,32 @@ public abstract class CodedOutputStream extends ByteOutput {
return 5;
}
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint32} field.
- */
+ /** Compute the number of bytes that would be needed to encode an {@code sint32} field. */
public static int computeSInt32SizeNoTag(final int value) {
return computeUInt32SizeNoTag(encodeZigZag32(value));
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed32} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code fixed32} field. */
public static int computeFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) {
return FIXED32_SIZE;
}
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed32} field.
- */
+ /** Compute the number of bytes that would be needed to encode an {@code sfixed32} field. */
public static int computeSFixed32SizeNoTag(@SuppressWarnings("unused") final int unused) {
return FIXED32_SIZE;
}
/**
- * Compute the number of bytes that would be needed to encode an
- * {@code int64} field, including tag.
+ * Compute the number of bytes that would be needed to encode an {@code int64} field, including
+ * tag.
*/
public static int computeInt64SizeNoTag(final long value) {
return computeUInt64SizeNoTag(value);
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code uint64} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code uint64} field, including
+ * tag.
*/
public static int computeUInt64SizeNoTag(long value) {
// handle two popular special cases up front ...
@@ -791,10 +759,12 @@ public abstract class CodedOutputStream extends ByteOutput {
// ... leaving us with 8 remaining, which we can divide and conquer
int n = 2;
if ((value & (~0L << 35)) != 0L) {
- n += 4; value >>>= 28;
+ n += 4;
+ value >>>= 28;
}
if ((value & (~0L << 21)) != 0L) {
- n += 2; value >>>= 14;
+ n += 2;
+ value >>>= 14;
}
if ((value & (~0L << 14)) != 0L) {
n += 1;
@@ -802,67 +772,51 @@ public abstract class CodedOutputStream extends ByteOutput {
return n;
}
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sint64} field.
- */
+ /** Compute the number of bytes that would be needed to encode an {@code sint64} field. */
public static int computeSInt64SizeNoTag(final long value) {
return computeUInt64SizeNoTag(encodeZigZag64(value));
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code fixed64} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code fixed64} field. */
public static int computeFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) {
return FIXED64_SIZE;
}
- /**
- * Compute the number of bytes that would be needed to encode an
- * {@code sfixed64} field.
- */
+ /** Compute the number of bytes that would be needed to encode an {@code sfixed64} field. */
public static int computeSFixed64SizeNoTag(@SuppressWarnings("unused") final long unused) {
return FIXED64_SIZE;
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code float} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code float} field, including
+ * tag.
*/
public static int computeFloatSizeNoTag(@SuppressWarnings("unused") final float unused) {
return FIXED32_SIZE;
}
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code double} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code double} field, including
+ * tag.
*/
public static int computeDoubleSizeNoTag(@SuppressWarnings("unused") final double unused) {
return FIXED64_SIZE;
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bool} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code bool} field. */
public static int computeBoolSizeNoTag(@SuppressWarnings("unused") final boolean unused) {
return 1;
}
/**
- * Compute the number of bytes that would be needed to encode an enum field.
- * The provided value is the numeric value used to represent the enum value on the wire
- * (not the enum ordinal value).
+ * Compute the number of bytes that would be needed to encode an enum field. The provided value is
+ * the numeric value used to represent the enum value on the wire (not the enum ordinal value).
*/
public static int computeEnumSizeNoTag(final int value) {
return computeInt32SizeNoTag(value);
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code string} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code string} field. */
public static int computeStringSizeNoTag(final String value) {
int length;
try {
@@ -877,41 +831,29 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Compute the number of bytes that would be needed to encode an embedded
- * message stored in lazy field.
+ * Compute the number of bytes that would be needed to encode an embedded message stored in lazy
+ * field.
*/
public static int computeLazyFieldSizeNoTag(final LazyFieldLite value) {
return computeLengthDelimitedFieldSize(value.getSerializedSize());
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */
public static int computeBytesSizeNoTag(final ByteString value) {
return computeLengthDelimitedFieldSize(value.size());
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */
public static int computeByteArraySizeNoTag(final byte[] value) {
return computeLengthDelimitedFieldSize(value.length);
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code bytes} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */
public static int computeByteBufferSizeNoTag(final ByteBuffer value) {
return computeLengthDelimitedFieldSize(value.capacity());
}
- /**
- * Compute the number of bytes that would be needed to encode an embedded
- * message field.
- */
+ /** Compute the number of bytes that would be needed to encode an embedded message field. */
public static int computeMessageSizeNoTag(final MessageLite value) {
return computeLengthDelimitedFieldSize(value.getSerializedSize());
}
@@ -922,14 +864,13 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers
- * into values that can be efficiently encoded with varint. (Otherwise,
- * negative values must be sign-extended to 64 bits to be varint encoded,
- * thus always taking 10 bytes on the wire.)
+ * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be
+ * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
+ * to be varint encoded, thus always taking 10 bytes on the wire.)
*
* @param n A signed 32-bit integer.
- * @return An unsigned 32-bit integer, stored in a signed int because
- * Java has no explicit unsigned support.
+ * @return An unsigned 32-bit integer, stored in a signed int because Java has no explicit
+ * unsigned support.
*/
public static int encodeZigZag32(final int n) {
// Note: the right-shift must be arithmetic
@@ -937,14 +878,13 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
- * into values that can be efficiently encoded with varint. (Otherwise,
- * negative values must be sign-extended to 64 bits to be varint encoded,
- * thus always taking 10 bytes on the wire.)
+ * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be
+ * efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
+ * to be varint encoded, thus always taking 10 bytes on the wire.)
*
* @param n A signed 64-bit integer.
- * @return An unsigned 64-bit integer, stored in a signed int because
- * Java has no explicit unsigned support.
+ * @return An unsigned 64-bit integer, stored in a signed int because Java has no explicit
+ * unsigned support.
*/
public static long encodeZigZag64(final long n) {
// Note: the right-shift must be arithmetic
@@ -954,23 +894,22 @@ public abstract class CodedOutputStream extends ByteOutput {
// =================================================================
/**
- * Flushes the stream and forces any buffered bytes to be written. This
- * does not flush the underlying OutputStream.
+ * Flushes the stream and forces any buffered bytes to be written. This does not flush the
+ * underlying OutputStream.
*/
public abstract void flush() throws IOException;
/**
- * If writing to a flat array, return the space left in the array.
- * Otherwise, throws {@code UnsupportedOperationException}.
+ * If writing to a flat array, return the space left in the array. Otherwise, throws {@code
+ * UnsupportedOperationException}.
*/
public abstract int spaceLeft();
/**
- * Verifies that {@link #spaceLeft()} returns zero. It's common to create
- * a byte array that is exactly big enough to hold a message, then write to
- * it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()}
- * after writing verifies that the message was actually as big as expected,
- * which can help catch bugs.
+ * Verifies that {@link #spaceLeft()} returns zero. It's common to create a byte array that is
+ * exactly big enough to hold a message, then write to it with a {@code CodedOutputStream}.
+ * Calling {@code checkNoSpaceLeft()} after writing verifies that the message was actually as big
+ * as expected, which can help catch bugs.
*/
public final void checkNoSpaceLeft() {
if (spaceLeft() != 0) {
@@ -979,9 +918,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * If you create a CodedOutputStream around a simple flat array, you must
- * not attempt to write more bytes than the array has space. Otherwise,
- * this exception will be thrown.
+ * If you create a CodedOutputStream around a simple flat array, you must not attempt to write
+ * more bytes than the array has space. Otherwise, this exception will be thrown.
*/
public static class OutOfSpaceException extends IOException {
private static final long serialVersionUID = -6947486886997889499L;
@@ -1007,9 +945,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Get the total number of bytes successfully written to this stream. The
- * returned value is not guaranteed to be accurate if exceptions have been
- * found in the middle of writing.
+ * Get the total number of bytes successfully written to this stream. The returned value is not
+ * guaranteed to be accurate if exceptions have been found in the middle of writing.
*/
public abstract int getTotalBytesWritten();
@@ -1021,8 +958,10 @@ public abstract class CodedOutputStream extends ByteOutput {
final void inefficientWriteStringNoTag(String value, UnpairedSurrogateException cause)
throws IOException {
- logger.log(Level.WARNING,
- "Converting ill-formed UTF-16. Your Protocol Buffer will not round trip correctly!", cause);
+ logger.log(
+ Level.WARNING,
+ "Converting ill-formed UTF-16. Your Protocol Buffer will not round trip correctly!",
+ cause);
// Unfortunately there does not appear to be any way to tell Java to encode
// UTF-8 directly into our buffer, so we have to let it create its own byte
@@ -1066,8 +1005,8 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
- * Compute the number of bytes that would be needed to encode a
- * {@code group} field, including tag.
+ * Compute the number of bytes that would be needed to encode a {@code group} field, including
+ * tag.
*
* @deprecated groups are deprecated.
*/
@@ -1077,10 +1016,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
- /**
- * Compute the number of bytes that would be needed to encode a
- * {@code group} field.
- */
+ /** Compute the number of bytes that would be needed to encode a {@code group} field. */
@Deprecated
public static int computeGroupSizeNoTag(final MessageLite value) {
return value.getSerializedSize();
@@ -1088,8 +1024,8 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
- * Encode and write a varint. {@code value} is treated as
- * unsigned, so it won't be sign-extended if negative.
+ * Encode and write a varint. {@code value} is treated as unsigned, so it won't be sign-extended
+ * if negative.
*
* @deprecated use {@link #writeUInt32NoTag} instead.
*/
@@ -1109,9 +1045,8 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * Compute the number of bytes that would be needed to encode a varint.
- * {@code value} is treated as unsigned, so it won't be sign-extended if
- * negative.
+ * Compute the number of bytes that would be needed to encode a varint. {@code value} is treated
+ * as unsigned, so it won't be sign-extended if negative.
*
* @deprecated use {@link #computeUInt32SizeNoTag(int)} instead.
*/
@@ -1152,9 +1087,7 @@ public abstract class CodedOutputStream extends ByteOutput {
// =================================================================
- /**
- * A {@link CodedOutputStream} that writes directly to a byte array.
- */
+ /** A {@link CodedOutputStream} that writes directly to a byte array. */
private static class ArrayEncoder extends CodedOutputStream {
private final byte[] buffer;
private final int offset;
@@ -1166,9 +1099,10 @@ public abstract class CodedOutputStream extends ByteOutput {
throw new NullPointerException("buffer");
}
if ((offset | length | (buffer.length - (offset + length))) < 0) {
- throw new IllegalArgumentException(String.format(
- "Array range is invalid. Buffer.length=%d, offset=%d, length=%d",
- buffer.length, offset, length));
+ throw new IllegalArgumentException(
+ String.format(
+ "Array range is invalid. Buffer.length=%d, offset=%d, length=%d",
+ buffer.length, offset, length));
}
this.buffer = buffer;
this.offset = offset;
@@ -1501,15 +1435,17 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * A {@link CodedOutputStream} that writes directly to a heap {@link ByteBuffer}. Writes are
- * done directly to the underlying array. The buffer position is only updated after a flush.
+ * A {@link CodedOutputStream} that writes directly to a heap {@link ByteBuffer}. Writes are done
+ * directly to the underlying array. The buffer position is only updated after a flush.
*/
private static final class HeapNioEncoder extends ArrayEncoder {
private final ByteBuffer byteBuffer;
private int initialPosition;
HeapNioEncoder(ByteBuffer byteBuffer) {
- super(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(),
+ super(
+ byteBuffer.array(),
+ byteBuffer.arrayOffset() + byteBuffer.position(),
byteBuffer.remaining());
this.byteBuffer = byteBuffer;
this.initialPosition = byteBuffer.position();
@@ -1604,16 +1540,14 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void writeByteBuffer(final int fieldNumber, final ByteBuffer value)
- throws IOException {
+ public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeUInt32NoTag(value.capacity());
writeRawBytes(value);
}
@Override
- public void writeMessage(final int fieldNumber, final MessageLite value)
- throws IOException {
+ public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeMessageNoTag(value);
}
@@ -2186,9 +2120,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
}
- /**
- * Abstract base class for buffered encoders.
- */
+ /** Abstract base class for buffered encoders. */
private abstract static class AbstractBufferedEncoder extends CodedOutputStream {
final byte[] buffer;
final int limit;
@@ -2346,8 +2278,8 @@ public abstract class CodedOutputStream extends ByteOutput {
/**
* A {@link CodedOutputStream} that decorates a {@link ByteOutput}. It internal buffer only to
- * support string encoding operations. All other writes are just passed through to the
- * {@link ByteOutput}.
+ * support string encoding operations. All other writes are just passed through to the {@link
+ * ByteOutput}.
*/
private static final class ByteOutputEncoder extends AbstractBufferedEncoder {
private final ByteOutput out;
@@ -2433,8 +2365,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void writeByteBuffer(final int fieldNumber, final ByteBuffer value)
- throws IOException {
+ public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeUInt32NoTag(value.capacity());
writeRawBytes(value);
@@ -2464,8 +2395,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void writeMessage(final int fieldNumber, final MessageLite value)
- throws IOException {
+ public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeMessageNoTag(value);
}
@@ -2738,8 +2668,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void writeByteBuffer(final int fieldNumber, final ByteBuffer value)
- throws IOException {
+ public void writeByteBuffer(final int fieldNumber, final ByteBuffer value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeUInt32NoTag(value.capacity());
writeRawBytes(value);
@@ -2769,8 +2698,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void writeMessage(final int fieldNumber, final MessageLite value)
- throws IOException {
+ public void writeMessage(final int fieldNumber, final MessageLite value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeMessageNoTag(value);
}
@@ -2916,8 +2844,7 @@ public abstract class CodedOutputStream extends ByteOutput {
}
@Override
- public void write(byte[] value, int offset, int length)
- throws IOException {
+ public void write(byte[] value, int offset, int length) throws IOException {
if (limit - position >= length) {
// We have room in the current buffer.
System.arraycopy(value, offset, buffer, position, length);
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 75b16fe3..8f751925 100644
--- a/java/core/src/main/java/com/google/protobuf/Descriptors.java
+++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java
@@ -49,29 +49,25 @@ import java.util.logging.Logger;
/**
* Contains a collection of classes which describe protocol message types.
*
- * Every message type has a {@link Descriptor}, which lists all
- * its fields and other information about a type. You can get a message
- * type's descriptor by calling {@code MessageType.getDescriptor()}, or
- * (given a message object of the type) {@code message.getDescriptorForType()}.
- * Furthermore, each message is associated with a {@link FileDescriptor} for
- * a relevant {@code .proto} file. You can obtain it by calling
- * {@code Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors
- * for all the messages defined in that file, and file descriptors for all the
- * imported {@code .proto} files.
+ * <p>Every message type has a {@link Descriptor}, which lists all its fields and other information
+ * about a type. You can get a message type's descriptor by calling {@code
+ * MessageType.getDescriptor()}, or (given a message object of the type) {@code
+ * message.getDescriptorForType()}. Furthermore, each message is associated with a {@link
+ * FileDescriptor} for a relevant {@code .proto} file. You can obtain it by calling {@code
+ * Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors for all the messages defined
+ * in that file, and file descriptors for all the imported {@code .proto} files.
*
- * Descriptors are built from DescriptorProtos, as defined in
- * {@code google/protobuf/descriptor.proto}.
+ * <p>Descriptors are built from DescriptorProtos, as defined in {@code
+ * google/protobuf/descriptor.proto}.
*
* @author kenton@google.com Kenton Varda
*/
public final class Descriptors {
- private static final Logger logger =
- Logger.getLogger(Descriptors.class.getName());
+ private static final Logger logger = Logger.getLogger(Descriptors.class.getName());
/**
- * Describes a {@code .proto} file, including everything defined within.
- * That includes, in particular, descriptors for all the messages and
- * file descriptors for all other imported {@code .proto} files
- * (dependencies).
+ * Describes a {@code .proto} file, including everything defined within. That includes, in
+ * particular, descriptors for all the messages and file descriptors for all other imported {@code
+ * .proto} files (dependencies).
*/
public static final class FileDescriptor extends GenericDescriptor {
/** Convert the descriptor to its protocol message representation. */
@@ -99,14 +95,17 @@ public final class Descriptors {
}
/**
- * Get the proto package name. This is the package name given by the
- * {@code package} statement in the {@code .proto} file, which differs
- * from the Java package.
+ * Get the proto package name. This is the package name given by the {@code package} statement
+ * in the {@code .proto} file, which differs from the Java package.
*/
- public String getPackage() { return proto.getPackage(); }
+ public String getPackage() {
+ return proto.getPackage();
+ }
/** Get the {@code FileOptions}, defined in {@code descriptor.proto}. */
- public FileOptions getOptions() { return proto.getOptions(); }
+ public FileOptions getOptions() {
+ return proto.getOptions();
+ }
/** Get a list of top-level message types declared in this file. */
public List<Descriptor> getMessageTypes() {
@@ -147,6 +146,7 @@ public final class Descriptors {
Syntax(String name) {
this.name = name;
}
+
private final String name;
}
@@ -159,7 +159,7 @@ public final class Descriptors {
}
/**
- * Find a message type in the file by name. Does not find nested types.
+ * Find a message type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The message type's descriptor, or {@code null} if not found.
@@ -174,16 +174,15 @@ public final class Descriptors {
name = getPackage() + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
- if (result != null && result instanceof Descriptor &&
- result.getFile() == this) {
- return (Descriptor)result;
+ if (result != null && result instanceof Descriptor && result.getFile() == this) {
+ return (Descriptor) result;
} else {
return null;
}
}
/**
- * Find an enum type in the file by name. Does not find nested types.
+ * Find an enum type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The enum type's descriptor, or {@code null} if not found.
@@ -198,9 +197,8 @@ public final class Descriptors {
name = getPackage() + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
- if (result != null && result instanceof EnumDescriptor &&
- result.getFile() == this) {
- return (EnumDescriptor)result;
+ if (result != null && result instanceof EnumDescriptor && result.getFile() == this) {
+ return (EnumDescriptor) result;
} else {
return null;
}
@@ -222,17 +220,15 @@ public final class Descriptors {
name = getPackage() + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
- if (result != null && result instanceof ServiceDescriptor &&
- result.getFile() == this) {
- return (ServiceDescriptor)result;
+ if (result != null && result instanceof ServiceDescriptor && result.getFile() == this) {
+ return (ServiceDescriptor) result;
} else {
return null;
}
}
/**
- * Find an extension in the file by name. Does not find extensions nested
- * inside message types.
+ * Find an extension in the file by name. Does not find extensions nested inside message types.
*
* @param name The unqualified extension name to look for.
* @return The extension's descriptor, or {@code null} if not found.
@@ -245,9 +241,8 @@ public final class Descriptors {
name = getPackage() + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
- if (result != null && result instanceof FieldDescriptor &&
- result.getFile() == this) {
- return (FieldDescriptor)result;
+ if (result != null && result instanceof FieldDescriptor && result.getFile() == this) {
+ return (FieldDescriptor) result;
} else {
return null;
}
@@ -257,36 +252,31 @@ public final class Descriptors {
* Construct a {@code FileDescriptor}.
*
* @param proto The protocol message form of the FileDescriptor.
- * @param dependencies {@code FileDescriptor}s corresponding to all of
- * the file's dependencies.
- * @throws DescriptorValidationException {@code proto} is not a valid
- * descriptor. This can occur for a number of reasons, e.g.
- * because a field has an undefined type or because two messages
- * were defined with the same name.
+ * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
+ * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
+ * for a number of reasons, e.g. because a field has an undefined type or because two
+ * messages were defined with the same name.
*/
- public static FileDescriptor buildFrom(final FileDescriptorProto proto,
- final FileDescriptor[] dependencies)
- throws DescriptorValidationException {
+ public static FileDescriptor buildFrom(
+ final FileDescriptorProto proto, final FileDescriptor[] dependencies)
+ throws DescriptorValidationException {
return buildFrom(proto, dependencies, false);
}
-
/**
* Construct a {@code FileDescriptor}.
*
* @param proto The protocol message form of the FileDescriptor.
- * @param dependencies {@code FileDescriptor}s corresponding to all of
- * the file's dependencies.
- * @param allowUnknownDependencies If true, non-exist dependenncies will be
- * ignored and undefined message types will be replaced with a
- * placeholder type.
- * @throws DescriptorValidationException {@code proto} is not a valid
- * descriptor. This can occur for a number of reasons, e.g.
- * because a field has an undefined type or because two messages
- * were defined with the same name.
+ * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
+ * @param allowUnknownDependencies If true, non-exist dependenncies will be ignored and
+ * undefined message types will be replaced with a placeholder type.
+ * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
+ * for a number of reasons, e.g. because a field has an undefined type or because two
+ * messages were defined with the same name.
*/
public static FileDescriptor buildFrom(
- final FileDescriptorProto proto, final FileDescriptor[] dependencies,
+ final FileDescriptorProto proto,
+ final FileDescriptor[] dependencies,
final boolean allowUnknownDependencies)
throws DescriptorValidationException {
// Building descriptors involves two steps: translating and linking.
@@ -298,18 +288,16 @@ public final class Descriptors {
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
- final DescriptorPool pool = new DescriptorPool(
- dependencies, allowUnknownDependencies);
- final FileDescriptor result = new FileDescriptor(
- proto, dependencies, pool, allowUnknownDependencies);
+ final DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies);
+ final FileDescriptor result =
+ new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies);
result.crossLink();
return result;
}
/**
- * This method is to be called by generated code only. It is equivalent
- * to {@code buildFrom} except that the {@code FileDescriptorProto} is
- * encoded in protocol buffer wire format.
+ * This method is to be called by generated code only. It is equivalent to {@code buildFrom}
+ * except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format.
*/
public static void internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
@@ -339,7 +327,7 @@ public final class Descriptors {
proto = FileDescriptorProto.parseFrom(descriptorBytes);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
- "Failed to parse protocol buffer descriptor for generated code.", e);
+ "Failed to parse protocol buffer descriptor for generated code.", e);
}
final FileDescriptor result;
@@ -349,11 +337,10 @@ public final class Descriptors {
result = buildFrom(proto, dependencies, true);
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException(
- "Invalid embedded descriptor for \"" + proto.getName() + "\".", e);
+ "Invalid embedded descriptor for \"" + proto.getName() + "\".", e);
}
- final ExtensionRegistry registry =
- descriptorAssigner.assignDescriptors(result);
+ final ExtensionRegistry registry = descriptorAssigner.assignDescriptors(result);
if (registry != null) {
// We must re-parse the proto using the registry.
@@ -361,8 +348,7 @@ public final class Descriptors {
proto = FileDescriptorProto.parseFrom(descriptorBytes, registry);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
- "Failed to parse protocol buffer descriptor for generated code.",
- e);
+ "Failed to parse protocol buffer descriptor for generated code.", e);
}
result.setProto(proto);
@@ -370,8 +356,8 @@ public final class Descriptors {
}
/**
- * This method is to be called by generated code only. It uses Java
- * reflection to load the dependencies' descriptors.
+ * This method is to be called by generated code only. It uses Java reflection to load the
+ * dependencies' descriptors.
*/
public static void internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
@@ -382,54 +368,46 @@ public final class Descriptors {
List<FileDescriptor> descriptors = new ArrayList<FileDescriptor>();
for (int i = 0; i < dependencies.length; i++) {
try {
- Class<?> clazz =
- descriptorOuterClass.getClassLoader().loadClass(dependencies[i]);
- descriptors.add(
- (FileDescriptor) clazz.getField("descriptor").get(null));
+ Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencies[i]);
+ descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null));
} catch (Exception e) {
// We allow unknown dependencies by default. If a dependency cannot
// be found we only generate a warning.
- logger.warning("Descriptors for \"" + dependencyFileNames[i] +
- "\" can not be found.");
+ logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found.");
}
}
FileDescriptor[] descriptorArray = new FileDescriptor[descriptors.size()];
descriptors.toArray(descriptorArray);
- internalBuildGeneratedFileFrom(
- descriptorDataParts, descriptorArray, descriptorAssigner);
+ internalBuildGeneratedFileFrom(descriptorDataParts, descriptorArray, descriptorAssigner);
}
/**
- * This method is to be called by generated code only. It is used to
- * update the FileDescriptorProto associated with the descriptor by
- * parsing it again with the given ExtensionRegistry. This is needed to
- * recognize custom options.
+ * This method is to be called by generated code only. It is used to update the
+ * FileDescriptorProto associated with the descriptor by parsing it again with the given
+ * ExtensionRegistry. This is needed to recognize custom options.
*/
public static void internalUpdateFileDescriptor(
- final FileDescriptor descriptor,
- final ExtensionRegistry registry) {
+ final FileDescriptor descriptor, final ExtensionRegistry registry) {
ByteString bytes = descriptor.proto.toByteString();
FileDescriptorProto proto;
try {
proto = FileDescriptorProto.parseFrom(bytes, registry);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
- "Failed to parse protocol buffer descriptor for generated code.", e);
+ "Failed to parse protocol buffer descriptor for generated code.", e);
}
descriptor.setProto(proto);
}
/**
- * This class should be used by generated code only. When calling
- * {@link FileDescriptor#internalBuildGeneratedFileFrom}, the caller
- * provides a callback implementing this interface. The callback is called
- * after the FileDescriptor has been constructed, in order to assign all
- * the global variables defined in the generated code which point at parts
- * of the FileDescriptor. The callback returns an ExtensionRegistry which
- * contains any extensions which might be used in the descriptor -- that
- * is, extensions of the various "Options" messages defined in
- * descriptor.proto. The callback may also return null to indicate that
- * no extensions are used in the descriptor.
+ * This class should be used by generated code only. When calling {@link
+ * FileDescriptor#internalBuildGeneratedFileFrom}, the caller provides a callback implementing
+ * this interface. The callback is called after the FileDescriptor has been constructed, in
+ * order to assign all the global variables defined in the generated code which point at parts
+ * of the FileDescriptor. The callback returns an ExtensionRegistry which contains any
+ * extensions which might be used in the descriptor -- that is, extensions of the various
+ * "Options" messages defined in descriptor.proto. The callback may also return null to indicate
+ * that no extensions are used in the descriptor.
*/
public interface InternalDescriptorAssigner {
ExtensionRegistry assignDescriptors(FileDescriptor root);
@@ -444,16 +422,16 @@ public final class Descriptors {
private final FileDescriptor[] publicDependencies;
private final DescriptorPool pool;
- private FileDescriptor(final FileDescriptorProto proto,
- final FileDescriptor[] dependencies,
- final DescriptorPool pool,
- boolean allowUnknownDependencies)
- throws DescriptorValidationException {
+ private FileDescriptor(
+ final FileDescriptorProto proto,
+ final FileDescriptor[] dependencies,
+ final DescriptorPool pool,
+ boolean allowUnknownDependencies)
+ throws DescriptorValidationException {
this.pool = pool;
this.proto = proto;
this.dependencies = dependencies.clone();
- HashMap<String, FileDescriptor> nameToFileMap =
- new HashMap<String, FileDescriptor>();
+ HashMap<String, FileDescriptor> nameToFileMap = new HashMap<String, FileDescriptor>();
for (FileDescriptor file : dependencies) {
nameToFileMap.put(file.getName(), file);
}
@@ -461,15 +439,13 @@ public final class Descriptors {
for (int i = 0; i < proto.getPublicDependencyCount(); i++) {
int index = proto.getPublicDependency(i);
if (index < 0 || index >= proto.getDependencyCount()) {
- throw new DescriptorValidationException(this,
- "Invalid public dependency index.");
+ throw new DescriptorValidationException(this, "Invalid public dependency index.");
}
String name = proto.getDependency(index);
FileDescriptor file = nameToFileMap.get(name);
if (file == null) {
if (!allowUnknownDependencies) {
- throw new DescriptorValidationException(this,
- "Invalid public dependency: " + name);
+ throw new DescriptorValidationException(this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
} else {
@@ -483,8 +459,7 @@ public final class Descriptors {
messageTypes = new Descriptor[proto.getMessageTypeCount()];
for (int i = 0; i < proto.getMessageTypeCount(); i++) {
- messageTypes[i] =
- new Descriptor(proto.getMessageType(i), this, null, i);
+ messageTypes[i] = new Descriptor(proto.getMessageType(i), this, null, i);
}
enumTypes = new EnumDescriptor[proto.getEnumTypeCount()];
@@ -499,20 +474,19 @@ public final class Descriptors {
extensions = new FieldDescriptor[proto.getExtensionCount()];
for (int i = 0; i < proto.getExtensionCount(); i++) {
- extensions[i] = new FieldDescriptor(
- proto.getExtension(i), this, null, i, true);
+ extensions[i] = new FieldDescriptor(proto.getExtension(i), this, null, i, true);
}
}
- /**
- * Create a placeholder FileDescriptor for a message Descriptor.
- */
- FileDescriptor(String packageName, Descriptor message)
- throws DescriptorValidationException {
+ /** Create a placeholder FileDescriptor for a message Descriptor. */
+ FileDescriptor(String packageName, Descriptor message) throws DescriptorValidationException {
this.pool = new DescriptorPool(new FileDescriptor[0], true);
- this.proto = FileDescriptorProto.newBuilder()
- .setName(message.getFullName() + ".placeholder.proto")
- .setPackage(packageName).addMessageType(message.toProto()).build();
+ this.proto =
+ FileDescriptorProto.newBuilder()
+ .setName(message.getFullName() + ".placeholder.proto")
+ .setPackage(packageName)
+ .addMessageType(message.toProto())
+ .build();
this.dependencies = new FileDescriptor[0];
this.publicDependencies = new FileDescriptor[0];
@@ -541,14 +515,12 @@ public final class Descriptors {
}
/**
- * Replace our {@link FileDescriptorProto} with the given one, which is
- * identical except that it might contain extensions that weren't present
- * in the original. This method is needed for bootstrapping when a file
- * defines custom options. The options may be defined in the file itself,
- * so we can't actually parse them until we've constructed the descriptors,
- * but to construct the descriptors we have to have parsed the descriptor
- * protos. So, we have to parse the descriptor protos a second time after
- * constructing the descriptors.
+ * Replace our {@link FileDescriptorProto} with the given one, which is identical except that it
+ * might contain extensions that weren't present in the original. This method is needed for
+ * bootstrapping when a file defines custom options. The options may be defined in the file
+ * itself, so we can't actually parse them until we've constructed the descriptors, but to
+ * construct the descriptors we have to have parsed the descriptor protos. So, we have to parse
+ * the descriptor protos a second time after constructing the descriptors.
*/
private void setProto(final FileDescriptorProto proto) {
this.proto = proto;
@@ -580,19 +552,24 @@ public final class Descriptors {
/** Describes a message type. */
public static final class Descriptor extends GenericDescriptor {
/**
- * Get the index of this descriptor within its parent. In other words,
- * given a {@link FileDescriptor} {@code file}, the following is true:
+ * Get the index of this descriptor within its parent. In other words, given a {@link
+ * FileDescriptor} {@code file}, the following is true:
+ *
* <pre>
* for all i in [0, file.getMessageTypeCount()):
* file.getMessageType(i).getIndex() == i
* </pre>
+ *
* Similarly, for a {@link Descriptor} {@code messageType}:
+ *
* <pre>
* for all i in [0, messageType.getNestedTypeCount()):
* messageType.getNestedType(i).getIndex() == i
* </pre>
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -607,14 +584,15 @@ public final class Descriptors {
}
/**
- * Get the type's fully-qualified name, within the proto language's
- * namespace. This differs from the Java name. For example, given this
- * {@code .proto}:
+ * Get the type's fully-qualified name, within the proto language's namespace. This differs from
+ * the Java name. For example, given this {@code .proto}:
+ *
* <pre>
* package foo.bar;
* option java_package = "com.example.protos"
* message Baz {}
* </pre>
+ *
* {@code Baz}'s full name is "foo.bar.Baz".
*/
@Override
@@ -629,10 +607,14 @@ public final class Descriptors {
}
/** If this is a nested type, get the outer descriptor, otherwise null. */
- public Descriptor getContainingType() { return containingType; }
+ public Descriptor getContainingType() {
+ return containingType;
+ }
/** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */
- public MessageOptions getOptions() { return proto.getOptions(); }
+ public MessageOptions getOptions() {
+ return proto.getOptions();
+ }
/** Get a list of this message type's fields. */
public List<FieldDescriptor> getFields() {
@@ -661,8 +643,7 @@ public final class Descriptors {
/** Determines if the given field number is an extension. */
public boolean isExtensionNumber(final int number) {
- for (final DescriptorProto.ExtensionRange range :
- proto.getExtensionRangeList()) {
+ for (final DescriptorProto.ExtensionRange range : proto.getExtensionRangeList()) {
if (range.getStart() <= number && number < range.getEnd()) {
return true;
}
@@ -672,8 +653,7 @@ public final class Descriptors {
/** Determines if the given field number is reserved. */
public boolean isReservedNumber(final int number) {
- for (final DescriptorProto.ReservedRange range :
- proto.getReservedRangeList()) {
+ for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) {
if (range.getStart() <= number && number < range.getEnd()) {
return true;
}
@@ -693,8 +673,8 @@ public final class Descriptors {
}
/**
- * Indicates whether the message can be extended. That is, whether it has
- * any "extensions x to y" ranges declared on it.
+ * Indicates whether the message can be extended. That is, whether it has any "extensions x to
+ * y" ranges declared on it.
*/
public boolean isExtendable() {
return proto.getExtensionRangeList().size() != 0;
@@ -702,14 +682,14 @@ public final class Descriptors {
/**
* Finds a field by name.
+ *
* @param name The unqualified name of the field (e.g. "foo").
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByName(final String name) {
- final GenericDescriptor result =
- file.pool.findSymbol(fullName + '.' + name);
+ final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result != null && result instanceof FieldDescriptor) {
- return (FieldDescriptor)result;
+ return (FieldDescriptor) result;
} else {
return null;
}
@@ -717,24 +697,24 @@ public final class Descriptors {
/**
* Finds a field by field number.
+ *
* @param number The field number within this message type.
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByNumber(final int number) {
- return file.pool.fieldsByNumber.get(
- new DescriptorPool.DescriptorIntPair(this, number));
+ return file.pool.fieldsByNumber.get(new DescriptorPool.DescriptorIntPair(this, number));
}
/**
* Finds a nested message type by name.
+ *
* @param name The unqualified name of the nested type (e.g. "Foo").
* @return The types's descriptor, or {@code null} if not found.
*/
public Descriptor findNestedTypeByName(final String name) {
- final GenericDescriptor result =
- file.pool.findSymbol(fullName + '.' + name);
+ final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result != null && result instanceof Descriptor) {
- return (Descriptor)result;
+ return (Descriptor) result;
} else {
return null;
}
@@ -742,14 +722,14 @@ public final class Descriptors {
/**
* Finds a nested enum type by name.
+ *
* @param name The unqualified name of the nested type (e.g. "Foo").
* @return The types's descriptor, or {@code null} if not found.
*/
public EnumDescriptor findEnumTypeByName(final String name) {
- final GenericDescriptor result =
- file.pool.findSymbol(fullName + '.' + name);
+ final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result != null && result instanceof EnumDescriptor) {
- return (EnumDescriptor)result;
+ return (EnumDescriptor) result;
} else {
return null;
}
@@ -776,9 +756,12 @@ public final class Descriptors {
packageName = fullname.substring(0, pos);
}
this.index = 0;
- this.proto = DescriptorProto.newBuilder().setName(name).addExtensionRange(
- DescriptorProto.ExtensionRange.newBuilder().setStart(1)
- .setEnd(536870912).build()).build();
+ this.proto =
+ DescriptorProto.newBuilder()
+ .setName(name)
+ .addExtensionRange(
+ DescriptorProto.ExtensionRange.newBuilder().setStart(1).setEnd(536870912).build())
+ .build();
this.fullName = fullname;
this.containingType = null;
@@ -792,11 +775,12 @@ public final class Descriptors {
this.file = new FileDescriptor(packageName, this);
}
- private Descriptor(final DescriptorProto proto,
- final FileDescriptor file,
- final Descriptor parent,
- final int index)
- throws DescriptorValidationException {
+ private Descriptor(
+ final DescriptorProto proto,
+ final FileDescriptor file,
+ final Descriptor parent,
+ final int index)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
@@ -805,32 +789,27 @@ public final class Descriptors {
oneofs = new OneofDescriptor[proto.getOneofDeclCount()];
for (int i = 0; i < proto.getOneofDeclCount(); i++) {
- oneofs[i] = new OneofDescriptor(
- proto.getOneofDecl(i), file, this, i);
+ oneofs[i] = new OneofDescriptor(proto.getOneofDecl(i), file, this, i);
}
nestedTypes = new Descriptor[proto.getNestedTypeCount()];
for (int i = 0; i < proto.getNestedTypeCount(); i++) {
- nestedTypes[i] = new Descriptor(
- proto.getNestedType(i), file, this, i);
+ nestedTypes[i] = new Descriptor(proto.getNestedType(i), file, this, i);
}
enumTypes = new EnumDescriptor[proto.getEnumTypeCount()];
for (int i = 0; i < proto.getEnumTypeCount(); i++) {
- enumTypes[i] = new EnumDescriptor(
- proto.getEnumType(i), file, this, i);
+ enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), file, this, i);
}
fields = new FieldDescriptor[proto.getFieldCount()];
for (int i = 0; i < proto.getFieldCount(); i++) {
- fields[i] = new FieldDescriptor(
- proto.getField(i), file, this, i, false);
+ fields[i] = new FieldDescriptor(proto.getField(i), file, this, i, false);
}
extensions = new FieldDescriptor[proto.getExtensionCount()];
for (int i = 0; i < proto.getExtensionCount(); i++) {
- extensions[i] = new FieldDescriptor(
- proto.getExtension(i), file, this, i, true);
+ extensions[i] = new FieldDescriptor(proto.getExtension(i), file, this, i, true);
}
for (int i = 0; i < proto.getOneofDeclCount(); i++) {
@@ -891,15 +870,16 @@ public final class Descriptors {
// =================================================================
/** Describes a field of a message type. */
- public static final class FieldDescriptor
- extends GenericDescriptor
- implements Comparable<FieldDescriptor>,
- FieldSet.FieldDescriptorLite<FieldDescriptor> {
+ public static final class FieldDescriptor extends GenericDescriptor
+ implements Comparable<FieldDescriptor>, FieldSet.FieldDescriptorLite<FieldDescriptor> {
/**
* Get the index of this descriptor within its parent.
+ *
* @see Descriptors.Descriptor#getIndex()
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -921,6 +901,7 @@ public final class Descriptors {
/**
* Get the field's fully-qualified name.
+ *
* @see Descriptors.Descriptor#getFullName()
*/
@Override
@@ -934,10 +915,12 @@ public final class Descriptors {
}
/**
- * Get the field's java type. This is just for convenience. Every
- * {@code FieldDescriptorProto.Type} maps to exactly one Java type.
+ * Get the field's java type. This is just for convenience. Every {@code
+ * FieldDescriptorProto.Type} maps to exactly one Java type.
*/
- public JavaType getJavaType() { return type.getJavaType(); }
+ public JavaType getJavaType() {
+ return type.getJavaType();
+ }
/** For internal use only. */
@Override
@@ -952,7 +935,9 @@ public final class Descriptors {
}
/** Get the field's declared type. */
- public Type getType() { return type; }
+ public Type getType() {
+ return type;
+ }
/** For internal use only. */
@Override
@@ -976,15 +961,15 @@ public final class Descriptors {
}
public boolean isMapField() {
- return getType() == Type.MESSAGE && isRepeated()
+ return getType() == Type.MESSAGE
+ && isRepeated()
&& getMessageType().getOptions().getMapEntry();
}
// I'm pretty sure values() constructs a new array every time, since there
// is nothing stopping the caller from mutating the array. Therefore we
// make a static copy here.
- private static final WireFormat.FieldType[] table =
- WireFormat.FieldType.values();
+ private static final WireFormat.FieldType[] table = WireFormat.FieldType.values();
/** Is this field declared required? */
public boolean isRequired() {
@@ -1002,8 +987,9 @@ public final class Descriptors {
return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REPEATED;
}
- /** Does this field have the {@code [packed = true]} option or is this field
- * packable in proto3 and not explicitly setted to unpacked?
+ /**
+ * Does this field have the {@code [packed = true]} option or is this field packable in proto3
+ * and not explicitly setted to unpacked?
*/
@Override
public boolean isPacked() {
@@ -1023,42 +1009,50 @@ public final class Descriptors {
}
/** Returns true if the field had an explicitly-defined default value. */
- public boolean hasDefaultValue() { return proto.hasDefaultValue(); }
+ public boolean hasDefaultValue() {
+ return proto.hasDefaultValue();
+ }
/**
- * Returns the field's default value. Valid for all types except for
- * messages and groups. For all other types, the object returned is of
- * the same class that would returned by Message.getField(this).
+ * Returns the field's default value. Valid for all types except for messages and groups. For
+ * all other types, the object returned is of the same class that would returned by
+ * Message.getField(this).
*/
public Object getDefaultValue() {
if (getJavaType() == JavaType.MESSAGE) {
throw new UnsupportedOperationException(
- "FieldDescriptor.getDefaultValue() called on an embedded message " +
- "field.");
+ "FieldDescriptor.getDefaultValue() called on an embedded message field.");
}
return defaultValue;
}
/** Get the {@code FieldOptions}, defined in {@code descriptor.proto}. */
- public FieldOptions getOptions() { return proto.getOptions(); }
+ public FieldOptions getOptions() {
+ return proto.getOptions();
+ }
/** Is this field an extension? */
- public boolean isExtension() { return proto.hasExtendee(); }
+ public boolean isExtension() {
+ return proto.hasExtendee();
+ }
/**
- * Get the field's containing type. For extensions, this is the type being
- * extended, not the location where the extension was defined. See
- * {@link #getExtensionScope()}.
+ * Get the field's containing type. For extensions, this is the type being extended, not the
+ * location where the extension was defined. See {@link #getExtensionScope()}.
*/
- public Descriptor getContainingType() { return containingType; }
+ public Descriptor getContainingType() {
+ return containingType;
+ }
/** Get the field's containing oneof. */
- public OneofDescriptor getContainingOneof() { return containingOneof; }
+ public OneofDescriptor getContainingOneof() {
+ return containingOneof;
+ }
/**
- * For extensions defined nested within message types, gets the outer
- * type. Not valid for non-extension fields. For example, consider
- * this {@code .proto} file:
+ * For extensions defined nested within message types, gets the outer type. Not valid for
+ * non-extension fields. For example, consider this {@code .proto} file:
+ *
* <pre>
* message Foo {
* extensions 1000 to max;
@@ -1072,14 +1066,14 @@ public final class Descriptors {
* }
* }
* </pre>
- * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}.
- * However, {@code baz}'s extension scope is {@code null} while
- * {@code qux}'s extension scope is {@code Bar}.
+ *
+ * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}. However, {@code baz}'s
+ * extension scope is {@code null} while {@code qux}'s extension scope is {@code Bar}.
*/
public Descriptor getExtensionScope() {
if (!isExtension()) {
throw new UnsupportedOperationException(
- "This field is not an extension.");
+ String.format("This field is not an extension. (%s)", fullName));
}
return extensionScope;
}
@@ -1088,7 +1082,7 @@ public final class Descriptors {
public Descriptor getMessageType() {
if (getJavaType() != JavaType.MESSAGE) {
throw new UnsupportedOperationException(
- "This field is not of message type.");
+ String.format("This field is not of message type. (%s)", fullName));
}
return messageType;
}
@@ -1098,27 +1092,25 @@ public final class Descriptors {
public EnumDescriptor getEnumType() {
if (getJavaType() != JavaType.ENUM) {
throw new UnsupportedOperationException(
- "This field is not of enum type.");
+ String.format("This field is not of enum type. (%s)", fullName));
}
return enumType;
}
/**
- * Compare with another {@code FieldDescriptor}. This orders fields in
- * "canonical" order, which simply means ascending order by field number.
- * {@code other} must be a field of the same type -- i.e.
- * {@code getContainingType()} must return the same {@code Descriptor} for
- * both fields.
+ * Compare with another {@code FieldDescriptor}. This orders fields in "canonical" order, which
+ * simply means ascending order by field number. {@code other} must be a field of the same type
+ * -- i.e. {@code getContainingType()} must return the same {@code Descriptor} for both fields.
*
- * @return negative, zero, or positive if {@code this} is less than,
- * equal to, or greater than {@code other}, respectively.
+ * @return negative, zero, or positive if {@code this} is less than, equal to, or greater than
+ * {@code other}, respectively.
*/
@Override
public int compareTo(final FieldDescriptor other) {
if (other.containingType != containingType) {
throw new IllegalArgumentException(
- "FieldDescriptors can only be compared to other FieldDescriptors " +
- "for fields of the same message type.");
+ "FieldDescriptors can only be compared to other FieldDescriptors "
+ + "for fields of the same message type.");
}
return getNumber() - other.getNumber();
}
@@ -1145,24 +1137,24 @@ public final class Descriptors {
private Object defaultValue;
public enum Type {
- DOUBLE (JavaType.DOUBLE ),
- FLOAT (JavaType.FLOAT ),
- INT64 (JavaType.LONG ),
- UINT64 (JavaType.LONG ),
- INT32 (JavaType.INT ),
- FIXED64 (JavaType.LONG ),
- FIXED32 (JavaType.INT ),
- BOOL (JavaType.BOOLEAN ),
- STRING (JavaType.STRING ),
- GROUP (JavaType.MESSAGE ),
- MESSAGE (JavaType.MESSAGE ),
- BYTES (JavaType.BYTE_STRING),
- UINT32 (JavaType.INT ),
- ENUM (JavaType.ENUM ),
- SFIXED32(JavaType.INT ),
- SFIXED64(JavaType.LONG ),
- SINT32 (JavaType.INT ),
- SINT64 (JavaType.LONG );
+ DOUBLE(JavaType.DOUBLE),
+ FLOAT(JavaType.FLOAT),
+ INT64(JavaType.LONG),
+ UINT64(JavaType.LONG),
+ INT32(JavaType.INT),
+ FIXED64(JavaType.LONG),
+ FIXED32(JavaType.INT),
+ BOOL(JavaType.BOOLEAN),
+ STRING(JavaType.STRING),
+ GROUP(JavaType.MESSAGE),
+ MESSAGE(JavaType.MESSAGE),
+ BYTES(JavaType.BYTE_STRING),
+ UINT32(JavaType.INT),
+ ENUM(JavaType.ENUM),
+ SFIXED32(JavaType.INT),
+ SFIXED64(JavaType.LONG),
+ SINT32(JavaType.INT),
+ SINT64(JavaType.LONG);
Type(final JavaType javaType) {
this.javaType = javaType;
@@ -1173,7 +1165,10 @@ public final class Descriptors {
public FieldDescriptorProto.Type toProto() {
return FieldDescriptorProto.Type.forNumber(ordinal() + 1);
}
- public JavaType getJavaType() { return javaType; }
+
+ public JavaType getJavaType() {
+ return javaType;
+ }
public static Type valueOf(final FieldDescriptorProto.Type type) {
return values()[type.getNumber() - 1];
@@ -1183,9 +1178,8 @@ public final class Descriptors {
static {
// Refuse to init if someone added a new declared type.
if (Type.values().length != FieldDescriptorProto.Type.values().length) {
- throw new RuntimeException(""
- + "descriptor.proto has a new declared type but Descriptors.java "
- + "wasn't updated.");
+ throw new RuntimeException(
+ "descriptor.proto has a new declared type but Descriptors.java wasn't updated.");
}
}
@@ -1205,8 +1199,8 @@ public final class Descriptors {
}
/**
- * The default default value for fields of this type, if it's a primitive
- * type. This is meant for use inside this file only, hence is private.
+ * The default default value for fields of this type, if it's a primitive type. This is meant
+ * for use inside this file only, hence is private.
*/
private final Object defaultDefault;
}
@@ -1230,12 +1224,13 @@ public final class Descriptors {
return result.toString();
}
- private FieldDescriptor(final FieldDescriptorProto proto,
- final FileDescriptor file,
- final Descriptor parent,
- final int index,
- final boolean isExtension)
- throws DescriptorValidationException {
+ private FieldDescriptor(
+ final FieldDescriptorProto proto,
+ final FileDescriptor file,
+ final Descriptor parent,
+ final int index,
+ final boolean isExtension)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
@@ -1251,16 +1246,15 @@ public final class Descriptors {
}
if (getNumber() <= 0) {
- throw new DescriptorValidationException(this,
- "Field numbers must be positive integers.");
+ throw new DescriptorValidationException(this, "Field numbers must be positive integers.");
}
if (isExtension) {
if (!proto.hasExtendee()) {
- throw new DescriptorValidationException(this,
- "FieldDescriptorProto.extendee not set for extension field.");
+ throw new DescriptorValidationException(
+ this, "FieldDescriptorProto.extendee not set for extension field.");
}
- containingType = null; // Will be filled in when cross-linking
+ containingType = null; // Will be filled in when cross-linking
if (parent != null) {
extensionScope = parent;
} else {
@@ -1268,23 +1262,23 @@ public final class Descriptors {
}
if (proto.hasOneofIndex()) {
- throw new DescriptorValidationException(this,
- "FieldDescriptorProto.oneof_index set for extension field.");
+ throw new DescriptorValidationException(
+ this, "FieldDescriptorProto.oneof_index set for extension field.");
}
containingOneof = null;
} else {
if (proto.hasExtendee()) {
- throw new DescriptorValidationException(this,
- "FieldDescriptorProto.extendee set for non-extension field.");
+ throw new DescriptorValidationException(
+ this, "FieldDescriptorProto.extendee set for non-extension field.");
}
containingType = parent;
if (proto.hasOneofIndex()) {
- if (proto.getOneofIndex() < 0 ||
- proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) {
- throw new DescriptorValidationException(this,
- "FieldDescriptorProto.oneof_index is out of range for type "
- + parent.getName());
+ if (proto.getOneofIndex() < 0
+ || proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) {
+ throw new DescriptorValidationException(
+ this,
+ "FieldDescriptorProto.oneof_index is out of range for type " + parent.getName());
}
containingOneof = parent.getOneofs().get(proto.getOneofIndex());
containingOneof.fieldCount++;
@@ -1301,26 +1295,29 @@ public final class Descriptors {
private void crossLink() throws DescriptorValidationException {
if (proto.hasExtendee()) {
final GenericDescriptor extendee =
- file.pool.lookupSymbol(proto.getExtendee(), this,
- DescriptorPool.SearchFilter.TYPES_ONLY);
+ file.pool.lookupSymbol(
+ proto.getExtendee(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(extendee instanceof Descriptor)) {
- throw new DescriptorValidationException(this,
- '\"' + proto.getExtendee() + "\" is not a message type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getExtendee() + "\" is not a message type.");
}
- containingType = (Descriptor)extendee;
+ containingType = (Descriptor) extendee;
if (!getContainingType().isExtensionNumber(getNumber())) {
- throw new DescriptorValidationException(this,
- '\"' + getContainingType().getFullName() +
- "\" does not declare " + getNumber() +
- " as an extension number.");
+ throw new DescriptorValidationException(
+ this,
+ '\"'
+ + getContainingType().getFullName()
+ + "\" does not declare "
+ + getNumber()
+ + " as an extension number.");
}
}
if (proto.hasTypeName()) {
final GenericDescriptor typeDescriptor =
- file.pool.lookupSymbol(proto.getTypeName(), this,
- DescriptorPool.SearchFilter.TYPES_ONLY);
+ file.pool.lookupSymbol(
+ proto.getTypeName(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!proto.hasType()) {
// Choose field type based on symbol.
@@ -1329,53 +1326,49 @@ public final class Descriptors {
} else if (typeDescriptor instanceof EnumDescriptor) {
type = Type.ENUM;
} else {
- throw new DescriptorValidationException(this,
- '\"' + proto.getTypeName() + "\" is not a type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getTypeName() + "\" is not a type.");
}
}
if (getJavaType() == JavaType.MESSAGE) {
if (!(typeDescriptor instanceof Descriptor)) {
- throw new DescriptorValidationException(this,
- '\"' + proto.getTypeName() + "\" is not a message type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getTypeName() + "\" is not a message type.");
}
- messageType = (Descriptor)typeDescriptor;
+ messageType = (Descriptor) typeDescriptor;
if (proto.hasDefaultValue()) {
- throw new DescriptorValidationException(this,
- "Messages can't have default values.");
+ throw new DescriptorValidationException(this, "Messages can't have default values.");
}
} else if (getJavaType() == JavaType.ENUM) {
if (!(typeDescriptor instanceof EnumDescriptor)) {
- throw new DescriptorValidationException(this,
- '\"' + proto.getTypeName() + "\" is not an enum type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getTypeName() + "\" is not an enum type.");
}
- enumType = (EnumDescriptor)typeDescriptor;
+ enumType = (EnumDescriptor) typeDescriptor;
} else {
- throw new DescriptorValidationException(this,
- "Field with primitive type has type_name.");
+ throw new DescriptorValidationException(this, "Field with primitive type has type_name.");
}
} else {
- if (getJavaType() == JavaType.MESSAGE ||
- getJavaType() == JavaType.ENUM) {
- throw new DescriptorValidationException(this,
- "Field with message or enum type missing type_name.");
+ if (getJavaType() == JavaType.MESSAGE || getJavaType() == JavaType.ENUM) {
+ throw new DescriptorValidationException(
+ this, "Field with message or enum type missing type_name.");
}
}
// Only repeated primitive fields may be packed.
if (proto.getOptions().getPacked() && !isPackable()) {
- throw new DescriptorValidationException(this,
- "[packed = true] can only be specified for repeated primitive " +
- "fields.");
+ throw new DescriptorValidationException(
+ this, "[packed = true] can only be specified for repeated primitive fields.");
}
// We don't attempt to parse the default value until here because for
// enums we need the enum type's descriptor.
if (proto.hasDefaultValue()) {
if (isRepeated()) {
- throw new DescriptorValidationException(this,
- "Repeated fields cannot have default values.");
+ throw new DescriptorValidationException(
+ this, "Repeated fields cannot have default values.");
}
try {
@@ -1428,30 +1421,26 @@ public final class Descriptors {
break;
case BYTES:
try {
- defaultValue =
- TextFormat.unescapeBytes(proto.getDefaultValue());
+ defaultValue = TextFormat.unescapeBytes(proto.getDefaultValue());
} catch (TextFormat.InvalidEscapeSequenceException e) {
- throw new DescriptorValidationException(this,
- "Couldn't parse default value: " + e.getMessage(), e);
+ throw new DescriptorValidationException(
+ this, "Couldn't parse default value: " + e.getMessage(), e);
}
break;
case ENUM:
defaultValue = enumType.findValueByName(proto.getDefaultValue());
if (defaultValue == null) {
- throw new DescriptorValidationException(this,
- "Unknown enum default value: \"" +
- proto.getDefaultValue() + '\"');
+ throw new DescriptorValidationException(
+ this, "Unknown enum default value: \"" + proto.getDefaultValue() + '\"');
}
break;
case MESSAGE:
case GROUP:
- throw new DescriptorValidationException(this,
- "Message type had default value.");
+ throw new DescriptorValidationException(this, "Message type had default value.");
}
} catch (NumberFormatException e) {
- throw new DescriptorValidationException(this,
- "Could not parse default value: \"" +
- proto.getDefaultValue() + '\"', e);
+ throw new DescriptorValidationException(
+ this, "Could not parse default value: \"" + proto.getDefaultValue() + '\"', e);
}
} else {
// Determine the default default for this field.
@@ -1478,16 +1467,15 @@ public final class Descriptors {
file.pool.addFieldByNumber(this);
}
- if (containingType != null &&
- containingType.getOptions().getMessageSetWireFormat()) {
+ if (containingType != null && containingType.getOptions().getMessageSetWireFormat()) {
if (isExtension()) {
if (!isOptional() || getType() != Type.MESSAGE) {
- throw new DescriptorValidationException(this,
- "Extensions of MessageSets must be optional messages.");
+ throw new DescriptorValidationException(
+ this, "Extensions of MessageSets must be optional messages.");
}
} else {
- throw new DescriptorValidationException(this,
- "MessageSets cannot have fields, only extensions.");
+ throw new DescriptorValidationException(
+ this, "MessageSets cannot have fields, only extensions.");
}
}
}
@@ -1497,10 +1485,7 @@ public final class Descriptors {
this.proto = proto;
}
- /**
- * For internal use only. This is to satisfy the FieldDescriptorLite
- * interface.
- */
+ /** For internal use only. This is to satisfy the FieldDescriptorLite interface. */
@Override
public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) {
// FieldDescriptors are only used with non-lite messages so we can just
@@ -1517,9 +1502,12 @@ public final class Descriptors {
implements Internal.EnumLiteMap<EnumValueDescriptor> {
/**
* Get the index of this descriptor within its parent.
+ *
* @see Descriptors.Descriptor#getIndex()
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -1535,6 +1523,7 @@ public final class Descriptors {
/**
* Get the type's fully-qualified name.
+ *
* @see Descriptors.Descriptor#getFullName()
*/
@Override
@@ -1549,10 +1538,14 @@ public final class Descriptors {
}
/** If this is a nested type, get the outer descriptor, otherwise null. */
- public Descriptor getContainingType() { return containingType; }
+ public Descriptor getContainingType() {
+ return containingType;
+ }
/** Get the {@code EnumOptions}, defined in {@code descriptor.proto}. */
- public EnumOptions getOptions() { return proto.getOptions(); }
+ public EnumOptions getOptions() {
+ return proto.getOptions();
+ }
/** Get a list of defined values for this enum. */
public List<EnumValueDescriptor> getValues() {
@@ -1561,34 +1554,34 @@ public final class Descriptors {
/**
* Find an enum value by name.
+ *
* @param name The unqualified name of the value (e.g. "FOO").
* @return the value's descriptor, or {@code null} if not found.
*/
public EnumValueDescriptor findValueByName(final String name) {
- final GenericDescriptor result =
- file.pool.findSymbol(fullName + '.' + name);
+ final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result != null && result instanceof EnumValueDescriptor) {
- return (EnumValueDescriptor)result;
+ return (EnumValueDescriptor) result;
} else {
return null;
}
}
/**
- * Find an enum value by number. If multiple enum values have the same
- * number, this returns the first defined value with that number.
+ * Find an enum value by number. If multiple enum values have the same number, this returns the
+ * first defined value with that number.
+ *
* @param number The value's number.
* @return the value's descriptor, or {@code null} if not found.
*/
@Override
public EnumValueDescriptor findValueByNumber(final int number) {
- return file.pool.enumValuesByNumber.get(
- new DescriptorPool.DescriptorIntPair(this, number));
+ return file.pool.enumValuesByNumber.get(new DescriptorPool.DescriptorIntPair(this, number));
}
/**
- * Get the enum value for a number. If no enum value has this number,
- * construct an EnumValueDescriptor for it.
+ * Get the enum value for a number. If no enum value has this number, construct an
+ * EnumValueDescriptor for it.
*/
public EnumValueDescriptor findValueByNumberCreatingIfUnknown(final int number) {
EnumValueDescriptor result = findValueByNumber(number);
@@ -1653,11 +1646,12 @@ public final class Descriptors {
private final WeakHashMap<Integer, WeakReference<EnumValueDescriptor>> unknownValues =
new WeakHashMap<Integer, WeakReference<EnumValueDescriptor>>();
- private EnumDescriptor(final EnumDescriptorProto proto,
- final FileDescriptor file,
- final Descriptor parent,
- final int index)
- throws DescriptorValidationException {
+ private EnumDescriptor(
+ final EnumDescriptorProto proto,
+ final FileDescriptor file,
+ final Descriptor parent,
+ final int index)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
@@ -1667,14 +1661,12 @@ public final class Descriptors {
if (proto.getValueCount() == 0) {
// We cannot allow enums with no values because this would mean there
// would be no valid default value for fields of this type.
- throw new DescriptorValidationException(this,
- "Enums must contain at least one value.");
+ throw new DescriptorValidationException(this, "Enums must contain at least one value.");
}
values = new EnumValueDescriptor[proto.getValueCount()];
for (int i = 0; i < proto.getValueCount(); i++) {
- values[i] = new EnumValueDescriptor(
- proto.getValue(i), file, this, i);
+ values[i] = new EnumValueDescriptor(proto.getValue(i), file, this, i);
}
file.pool.addSymbol(this);
@@ -1693,18 +1685,20 @@ public final class Descriptors {
// =================================================================
/**
- * Describes one value within an enum type. Note that multiple defined
- * values may have the same number. In generated Java code, all values
- * with the same number after the first become aliases of the first.
- * However, they still have independent EnumValueDescriptors.
+ * Describes one value within an enum type. Note that multiple defined values may have the same
+ * number. In generated Java code, all values with the same number after the first become aliases
+ * of the first. However, they still have independent EnumValueDescriptors.
*/
public static final class EnumValueDescriptor extends GenericDescriptor
implements Internal.EnumLite {
/**
* Get the index of this descriptor within its parent.
+ *
* @see Descriptors.Descriptor#getIndex()
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -1725,10 +1719,13 @@ public final class Descriptors {
}
@Override
- public String toString() { return proto.getName(); }
+ public String toString() {
+ return proto.getName();
+ }
/**
* Get the value's fully-qualified name.
+ *
* @see Descriptors.Descriptor#getFullName()
*/
@Override
@@ -1743,12 +1740,14 @@ public final class Descriptors {
}
/** Get the value's enum type. */
- public EnumDescriptor getType() { return type; }
+ public EnumDescriptor getType() {
+ return type;
+ }
- /**
- * Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}.
- */
- public EnumValueOptions getOptions() { return proto.getOptions(); }
+ /** Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. */
+ public EnumValueOptions getOptions() {
+ return proto.getOptions();
+ }
private final int index;
private EnumValueDescriptorProto proto;
@@ -1756,11 +1755,12 @@ public final class Descriptors {
private final FileDescriptor file;
private final EnumDescriptor type;
- private EnumValueDescriptor(final EnumValueDescriptorProto proto,
- final FileDescriptor file,
- final EnumDescriptor parent,
- final int index)
- throws DescriptorValidationException {
+ private EnumValueDescriptor(
+ final EnumValueDescriptorProto proto,
+ final FileDescriptor file,
+ final EnumDescriptor parent,
+ final int index)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
this.file = file;
@@ -1775,12 +1775,10 @@ public final class Descriptors {
private Integer number;
// Create an unknown enum value.
private EnumValueDescriptor(
- final FileDescriptor file,
- final EnumDescriptor parent,
- final Integer number) {
+ final FileDescriptor file, final EnumDescriptor parent, final Integer number) {
String name = "UNKNOWN_ENUM_VALUE_" + parent.getName() + "_" + number;
- EnumValueDescriptorProto proto = EnumValueDescriptorProto
- .newBuilder().setName(name).setNumber(number).build();
+ EnumValueDescriptorProto proto =
+ EnumValueDescriptorProto.newBuilder().setName(name).setNumber(number).build();
this.index = -1;
this.proto = proto;
this.file = file;
@@ -1802,10 +1800,11 @@ public final class Descriptors {
/** Describes a service type. */
public static final class ServiceDescriptor extends GenericDescriptor {
/**
- * Get the index of this descriptor within its parent.
- * * @see Descriptors.Descriptor#getIndex()
+ * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex()
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -1821,6 +1820,7 @@ public final class Descriptors {
/**
* Get the type's fully-qualified name.
+ *
* @see Descriptors.Descriptor#getFullName()
*/
@Override
@@ -1835,7 +1835,9 @@ public final class Descriptors {
}
/** Get the {@code ServiceOptions}, defined in {@code descriptor.proto}. */
- public ServiceOptions getOptions() { return proto.getOptions(); }
+ public ServiceOptions getOptions() {
+ return proto.getOptions();
+ }
/** Get a list of methods for this service. */
public List<MethodDescriptor> getMethods() {
@@ -1844,14 +1846,14 @@ public final class Descriptors {
/**
* Find a method by name.
+ *
* @param name The unqualified name of the method (e.g. "Foo").
* @return the method's descriptor, or {@code null} if not found.
*/
public MethodDescriptor findMethodByName(final String name) {
- final GenericDescriptor result =
- file.pool.findSymbol(fullName + '.' + name);
+ final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result != null && result instanceof MethodDescriptor) {
- return (MethodDescriptor)result;
+ return (MethodDescriptor) result;
} else {
return null;
}
@@ -1863,10 +1865,9 @@ public final class Descriptors {
private final FileDescriptor file;
private MethodDescriptor[] methods;
- private ServiceDescriptor(final ServiceDescriptorProto proto,
- final FileDescriptor file,
- final int index)
- throws DescriptorValidationException {
+ private ServiceDescriptor(
+ final ServiceDescriptorProto proto, final FileDescriptor file, final int index)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
fullName = computeFullName(file, null, proto.getName());
@@ -1874,8 +1875,7 @@ public final class Descriptors {
methods = new MethodDescriptor[proto.getMethodCount()];
for (int i = 0; i < proto.getMethodCount(); i++) {
- methods[i] = new MethodDescriptor(
- proto.getMethod(i), file, this, i);
+ methods[i] = new MethodDescriptor(proto.getMethod(i), file, this, i);
}
file.pool.addSymbol(this);
@@ -1899,15 +1899,14 @@ public final class Descriptors {
// =================================================================
- /**
- * Describes one method within a service type.
- */
+ /** Describes one method within a service type. */
public static final class MethodDescriptor extends GenericDescriptor {
/**
- * Get the index of this descriptor within its parent.
- * * @see Descriptors.Descriptor#getIndex()
+ * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex()
*/
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
/** Convert the descriptor to its protocol message representation. */
@Override
@@ -1923,6 +1922,7 @@ public final class Descriptors {
/**
* Get the method's fully-qualified name.
+ *
* @see Descriptors.Descriptor#getFullName()
*/
@Override
@@ -1937,18 +1937,24 @@ public final class Descriptors {
}
/** Get the method's service type. */
- public ServiceDescriptor getService() { return service; }
+ public ServiceDescriptor getService() {
+ return service;
+ }
/** Get the method's input type. */
- public Descriptor getInputType() { return inputType; }
+ public Descriptor getInputType() {
+ return inputType;
+ }
/** Get the method's output type. */
- public Descriptor getOutputType() { return outputType; }
+ public Descriptor getOutputType() {
+ return outputType;
+ }
- /**
- * Get the {@code MethodOptions}, defined in {@code descriptor.proto}.
- */
- public MethodOptions getOptions() { return proto.getOptions(); }
+ /** Get the {@code MethodOptions}, defined in {@code descriptor.proto}. */
+ public MethodOptions getOptions() {
+ return proto.getOptions();
+ }
private final int index;
private MethodDescriptorProto proto;
@@ -1960,11 +1966,12 @@ public final class Descriptors {
private Descriptor inputType;
private Descriptor outputType;
- private MethodDescriptor(final MethodDescriptorProto proto,
- final FileDescriptor file,
- final ServiceDescriptor parent,
- final int index)
- throws DescriptorValidationException {
+ private MethodDescriptor(
+ final MethodDescriptorProto proto,
+ final FileDescriptor file,
+ final ServiceDescriptor parent,
+ final int index)
+ throws DescriptorValidationException {
this.index = index;
this.proto = proto;
this.file = file;
@@ -1977,22 +1984,22 @@ public final class Descriptors {
private void crossLink() throws DescriptorValidationException {
final GenericDescriptor input =
- file.pool.lookupSymbol(proto.getInputType(), this,
- DescriptorPool.SearchFilter.TYPES_ONLY);
+ file.pool.lookupSymbol(
+ proto.getInputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(input instanceof Descriptor)) {
- throw new DescriptorValidationException(this,
- '\"' + proto.getInputType() + "\" is not a message type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getInputType() + "\" is not a message type.");
}
- inputType = (Descriptor)input;
+ inputType = (Descriptor) input;
final GenericDescriptor output =
- file.pool.lookupSymbol(proto.getOutputType(), this,
- DescriptorPool.SearchFilter.TYPES_ONLY);
+ file.pool.lookupSymbol(
+ proto.getOutputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(output instanceof Descriptor)) {
- throw new DescriptorValidationException(this,
- '\"' + proto.getOutputType() + "\" is not a message type.");
+ throw new DescriptorValidationException(
+ this, '\"' + proto.getOutputType() + "\" is not a message type.");
}
- outputType = (Descriptor)output;
+ outputType = (Descriptor) output;
}
/** See {@link FileDescriptor#setProto}. */
@@ -2003,9 +2010,8 @@ public final class Descriptors {
// =================================================================
- private static String computeFullName(final FileDescriptor file,
- final Descriptor parent,
- final String name) {
+ private static String computeFullName(
+ final FileDescriptor file, final Descriptor parent, final String name) {
if (parent != null) {
return parent.getFullName() + '.' + name;
} else if (file.getPackage().length() > 0) {
@@ -2018,47 +2024,47 @@ public final class Descriptors {
// =================================================================
/**
- * All descriptors implement this to make it easier to implement tools like
- * {@code DescriptorPool}.<p>
+ * All descriptors implement this to make it easier to implement tools like {@code
+ * DescriptorPool}.
*
- * This class is public so that the methods it exposes can be called from
- * outside of this package. However, it should only be subclassed from
- * nested classes of Descriptors.
+ * <p>This class is public so that the methods it exposes can be called from outside of this
+ * package. However, it should only be subclassed from nested classes of Descriptors.
*/
public abstract static class GenericDescriptor {
public abstract Message toProto();
+
public abstract String getName();
+
public abstract String getFullName();
+
public abstract FileDescriptor getFile();
}
- /**
- * Thrown when building descriptors fails because the source DescriptorProtos
- * are not valid.
- */
+ /** Thrown when building descriptors fails because the source DescriptorProtos are not valid. */
public static class DescriptorValidationException extends Exception {
private static final long serialVersionUID = 5750205775490483148L;
/** Gets the full name of the descriptor where the error occurred. */
- public String getProblemSymbolName() { return name; }
+ public String getProblemSymbolName() {
+ return name;
+ }
- /**
- * Gets the protocol message representation of the invalid descriptor.
- */
- public Message getProblemProto() { return proto; }
+ /** Gets the protocol message representation of the invalid descriptor. */
+ public Message getProblemProto() {
+ return proto;
+ }
- /**
- * Gets a human-readable description of the error.
- */
- public String getDescription() { return description; }
+ /** Gets a human-readable description of the error. */
+ public String getDescription() {
+ return description;
+ }
private final String name;
private final Message proto;
private final String description;
private DescriptorValidationException(
- final GenericDescriptor problemDescriptor,
- final String description) {
+ final GenericDescriptor problemDescriptor, final String description) {
super(problemDescriptor.getFullName() + ": " + description);
// Note that problemDescriptor may be partially uninitialized, so we
@@ -2078,8 +2084,7 @@ public final class Descriptors {
}
private DescriptorValidationException(
- final FileDescriptor problemDescriptor,
- final String description) {
+ final FileDescriptor problemDescriptor, final String description) {
super(problemDescriptor.getName() + ": " + description);
// Note that problemDescriptor may be partially uninitialized, so we
@@ -2094,19 +2099,19 @@ public final class Descriptors {
// =================================================================
/**
- * A private helper class which contains lookup tables containing all the
- * descriptors defined in a particular file.
+ * A private helper class which contains lookup tables containing all the descriptors defined in a
+ * particular file.
*/
private static final class DescriptorPool {
- /** Defines what subclass of descriptors to search in the descriptor pool.
- */
+ /** Defines what subclass of descriptors to search in the descriptor pool. */
enum SearchFilter {
- TYPES_ONLY, AGGREGATES_ONLY, ALL_SYMBOLS
+ TYPES_ONLY,
+ AGGREGATES_ONLY,
+ ALL_SYMBOLS
}
- DescriptorPool(final FileDescriptor[] dependencies,
- boolean allowUnknownDependencies) {
+ DescriptorPool(final FileDescriptor[] dependencies, boolean allowUnknownDependencies) {
this.dependencies = new HashSet<FileDescriptor>();
this.allowUnknownDependencies = allowUnknownDependencies;
@@ -2127,7 +2132,7 @@ public final class Descriptors {
}
}
- /** Find and put public dependencies of the file into dependencies set.*/
+ /** Find and put public dependencies of the file into dependencies set. */
private void importPublicDependencies(final FileDescriptor file) {
for (FileDescriptor dependency : file.getPublicDependencies()) {
if (dependencies.add(dependency)) {
@@ -2140,27 +2145,27 @@ public final class Descriptors {
private boolean allowUnknownDependencies;
private final Map<String, GenericDescriptor> descriptorsByName =
- new HashMap<String, GenericDescriptor>();
+ new HashMap<String, GenericDescriptor>();
private final Map<DescriptorIntPair, FieldDescriptor> fieldsByNumber =
- new HashMap<DescriptorIntPair, FieldDescriptor>();
- private final Map<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber
- = new HashMap<DescriptorIntPair, EnumValueDescriptor>();
+ new HashMap<DescriptorIntPair, FieldDescriptor>();
+ private final Map<DescriptorIntPair, EnumValueDescriptor> enumValuesByNumber =
+ new HashMap<DescriptorIntPair, EnumValueDescriptor>();
/** Find a generic descriptor by fully-qualified name. */
GenericDescriptor findSymbol(final String fullName) {
return findSymbol(fullName, SearchFilter.ALL_SYMBOLS);
}
- /** Find a descriptor by fully-qualified name and given option to only
- * search valid field type descriptors.
+ /**
+ * Find a descriptor by fully-qualified name and given option to only search valid field type
+ * descriptors.
*/
- GenericDescriptor findSymbol(final String fullName,
- final SearchFilter filter) {
+ GenericDescriptor findSymbol(final String fullName, final SearchFilter filter) {
GenericDescriptor result = descriptorsByName.get(fullName);
if (result != null) {
- if ((filter==SearchFilter.ALL_SYMBOLS) ||
- ((filter==SearchFilter.TYPES_ONLY) && isType(result)) ||
- ((filter==SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
+ if ((filter == SearchFilter.ALL_SYMBOLS)
+ || ((filter == SearchFilter.TYPES_ONLY) && isType(result))
+ || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
return result;
}
}
@@ -2168,9 +2173,9 @@ public final class Descriptors {
for (final FileDescriptor dependency : dependencies) {
result = dependency.pool.descriptorsByName.get(fullName);
if (result != null) {
- if ((filter==SearchFilter.ALL_SYMBOLS) ||
- ((filter==SearchFilter.TYPES_ONLY) && isType(result)) ||
- ((filter==SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
+ if ((filter == SearchFilter.ALL_SYMBOLS)
+ || ((filter == SearchFilter.TYPES_ONLY) && isType(result))
+ || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
return result;
}
}
@@ -2181,28 +2186,27 @@ public final class Descriptors {
/** Checks if the descriptor is a valid type for a message field. */
boolean isType(GenericDescriptor descriptor) {
- return (descriptor instanceof Descriptor) ||
- (descriptor instanceof EnumDescriptor);
+ return (descriptor instanceof Descriptor) || (descriptor instanceof EnumDescriptor);
}
/** Checks if the descriptor is a valid namespace type. */
boolean isAggregate(GenericDescriptor descriptor) {
- return (descriptor instanceof Descriptor) ||
- (descriptor instanceof EnumDescriptor) ||
- (descriptor instanceof PackageDescriptor) ||
- (descriptor instanceof ServiceDescriptor);
+ return (descriptor instanceof Descriptor)
+ || (descriptor instanceof EnumDescriptor)
+ || (descriptor instanceof PackageDescriptor)
+ || (descriptor instanceof ServiceDescriptor);
}
/**
- * Look up a type descriptor by name, relative to some other descriptor.
- * The name may be fully-qualified (with a leading '.'),
- * partially-qualified, or unqualified. C++-like name lookup semantics
- * are used to search for the matching descriptor.
+ * Look up a type descriptor by name, relative to some other descriptor. The name may be
+ * fully-qualified (with a leading '.'), partially-qualified, or unqualified. C++-like name
+ * lookup semantics are used to search for the matching descriptor.
*/
- GenericDescriptor lookupSymbol(final String name,
- final GenericDescriptor relativeTo,
- final DescriptorPool.SearchFilter filter)
- throws DescriptorValidationException {
+ GenericDescriptor lookupSymbol(
+ final String name,
+ final GenericDescriptor relativeTo,
+ final DescriptorPool.SearchFilter filter)
+ throws DescriptorValidationException {
// TODO(kenton): This could be optimized in a number of ways.
GenericDescriptor result;
@@ -2235,8 +2239,7 @@ public final class Descriptors {
// We will search each parent scope of "relativeTo" looking for the
// symbol.
- final StringBuilder scopeToTry =
- new StringBuilder(relativeTo.getFullName());
+ final StringBuilder scopeToTry = new StringBuilder(relativeTo.getFullName());
while (true) {
// Chop off the last component of the scope.
@@ -2250,8 +2253,7 @@ public final class Descriptors {
// Append firstPart and try to find
scopeToTry.append(firstPart);
- result = findSymbol(scopeToTry.toString(),
- DescriptorPool.SearchFilter.AGGREGATES_ONLY);
+ result = findSymbol(scopeToTry.toString(), DescriptorPool.SearchFilter.AGGREGATES_ONLY);
if (result != null) {
if (firstPartLength != -1) {
@@ -2274,22 +2276,23 @@ public final class Descriptors {
if (result == null) {
if (allowUnknownDependencies && filter == SearchFilter.TYPES_ONLY) {
- logger.warning("The descriptor for message type \"" + name +
- "\" can not be found and a placeholder is created for it");
+ logger.warning(
+ "The descriptor for message type \""
+ + name
+ + "\" can not be found and a placeholder is created for it");
// We create a dummy message descriptor here regardless of the
// expected type. If the type should be message, this dummy
// descriptor will work well and if the type should be enum, a
// DescriptorValidationException will be thrown latter. In either
// case, the code works as expected: we allow unknown message types
- // but not unknwon enum types.
+ // but not unknown enum types.
result = new Descriptor(fullname);
// Add the placeholder file as a dependency so we can find the
// placeholder symbol when resolving other references.
this.dependencies.add(result.getFile());
return result;
} else {
- throw new DescriptorValidationException(relativeTo,
- '\"' + name + "\" is not defined.");
+ throw new DescriptorValidationException(relativeTo, '\"' + name + "\" is not defined.");
}
} else {
return result;
@@ -2297,11 +2300,10 @@ public final class Descriptors {
}
/**
- * Adds a symbol to the symbol table. If a symbol with the same name
- * already exists, throws an error.
+ * Adds a symbol to the symbol table. If a symbol with the same name already exists, throws an
+ * error.
*/
- void addSymbol(final GenericDescriptor descriptor)
- throws DescriptorValidationException {
+ void addSymbol(final GenericDescriptor descriptor) throws DescriptorValidationException {
validateSymbolName(descriptor);
final String fullName = descriptor.getFullName();
@@ -2313,47 +2315,56 @@ public final class Descriptors {
if (descriptor.getFile() == old.getFile()) {
if (dotpos == -1) {
- throw new DescriptorValidationException(descriptor,
- '\"' + fullName + "\" is already defined.");
+ throw new DescriptorValidationException(
+ descriptor, '\"' + fullName + "\" is already defined.");
} else {
- throw new DescriptorValidationException(descriptor,
- '\"' + fullName.substring(dotpos + 1) +
- "\" is already defined in \"" +
- fullName.substring(0, dotpos) + "\".");
+ throw new DescriptorValidationException(
+ descriptor,
+ '\"'
+ + fullName.substring(dotpos + 1)
+ + "\" is already defined in \""
+ + fullName.substring(0, dotpos)
+ + "\".");
}
} else {
- throw new DescriptorValidationException(descriptor,
- '\"' + fullName + "\" is already defined in file \"" +
- old.getFile().getName() + "\".");
+ throw new DescriptorValidationException(
+ descriptor,
+ '\"'
+ + fullName
+ + "\" is already defined in file \""
+ + old.getFile().getName()
+ + "\".");
}
}
}
/**
- * Represents a package in the symbol table. We use PackageDescriptors
- * just as placeholders so that someone cannot define, say, a message type
- * that has the same name as an existing package.
+ * Represents a package in the symbol table. We use PackageDescriptors just as placeholders so
+ * that someone cannot define, say, a message type that has the same name as an existing
+ * package.
*/
private static final class PackageDescriptor extends GenericDescriptor {
@Override
public Message toProto() {
return file.toProto();
}
+
@Override
public String getName() {
return name;
}
+
@Override
public String getFullName() {
return fullName;
}
+
@Override
public FileDescriptor getFile() {
return file;
}
- PackageDescriptor(final String name, final String fullName,
- final FileDescriptor file) {
+ PackageDescriptor(final String name, final String fullName, final FileDescriptor file) {
this.file = file;
this.fullName = fullName;
this.name = name;
@@ -2365,13 +2376,12 @@ public final class Descriptors {
}
/**
- * Adds a package to the symbol tables. If a package by the same name
- * already exists, that is fine, but if some other kind of symbol exists
- * under the same name, an exception is thrown. If the package has
- * multiple components, this also adds the parent package(s).
+ * Adds a package to the symbol tables. If a package by the same name already exists, that is
+ * fine, but if some other kind of symbol exists under the same name, an exception is thrown. If
+ * the package has multiple components, this also adds the parent package(s).
*/
void addPackage(final String fullName, final FileDescriptor file)
- throws DescriptorValidationException {
+ throws DescriptorValidationException {
final int dotpos = fullName.lastIndexOf('.');
final String name;
if (dotpos == -1) {
@@ -2382,14 +2392,18 @@ public final class Descriptors {
}
final GenericDescriptor old =
- descriptorsByName.put(fullName,
- new PackageDescriptor(name, fullName, file));
+ descriptorsByName.put(fullName, new PackageDescriptor(name, fullName, file));
if (old != null) {
descriptorsByName.put(fullName, old);
if (!(old instanceof PackageDescriptor)) {
- throw new DescriptorValidationException(file,
- '\"' + name + "\" is already defined (as something other than a "
- + "package) in file \"" + old.getFile().getName() + "\".");
+ throw new DescriptorValidationException(
+ file,
+ '\"'
+ + name
+ + "\" is already defined (as something other than a "
+ + "package) in file \""
+ + old.getFile().getName()
+ + "\".");
}
}
}
@@ -2408,43 +2422,46 @@ public final class Descriptors {
public int hashCode() {
return descriptor.hashCode() * ((1 << 16) - 1) + number;
}
+
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof DescriptorIntPair)) {
return false;
}
- final DescriptorIntPair other = (DescriptorIntPair)obj;
+ final DescriptorIntPair other = (DescriptorIntPair) obj;
return descriptor == other.descriptor && number == other.number;
}
}
/**
- * Adds a field to the fieldsByNumber table. Throws an exception if a
- * field with the same containing type and number already exists.
+ * Adds a field to the fieldsByNumber table. Throws an exception if a field with the same
+ * containing type and number already exists.
*/
- void addFieldByNumber(final FieldDescriptor field)
- throws DescriptorValidationException {
+ void addFieldByNumber(final FieldDescriptor field) throws DescriptorValidationException {
final DescriptorIntPair key =
- new DescriptorIntPair(field.getContainingType(), field.getNumber());
+ new DescriptorIntPair(field.getContainingType(), field.getNumber());
final FieldDescriptor old = fieldsByNumber.put(key, field);
if (old != null) {
fieldsByNumber.put(key, old);
- throw new DescriptorValidationException(field,
- "Field number " + field.getNumber() +
- " has already been used in \"" +
- field.getContainingType().getFullName() +
- "\" by field \"" + old.getName() + "\".");
+ throw new DescriptorValidationException(
+ field,
+ "Field number "
+ + field.getNumber()
+ + " has already been used in \""
+ + field.getContainingType().getFullName()
+ + "\" by field \""
+ + old.getName()
+ + "\".");
}
}
/**
- * Adds an enum value to the enumValuesByNumber table. If an enum value
- * with the same type and number already exists, does nothing. (This is
- * allowed; the first value define with the number takes precedence.)
+ * Adds an enum value to the enumValuesByNumber table. If an enum value with the same type and
+ * number already exists, does nothing. (This is allowed; the first value define with the number
+ * takes precedence.)
*/
void addEnumValueByNumber(final EnumValueDescriptor value) {
- final DescriptorIntPair key =
- new DescriptorIntPair(value.getType(), value.getNumber());
+ final DescriptorIntPair key = new DescriptorIntPair(value.getType(), value.getNumber());
final EnumValueDescriptor old = enumValuesByNumber.put(key, value);
if (old != null) {
enumValuesByNumber.put(key, old);
@@ -2454,11 +2471,11 @@ public final class Descriptors {
}
/**
- * Verifies that the descriptor's name is valid (i.e. it contains only
- * letters, digits, and underscores, and does not start with a digit).
+ * Verifies that the descriptor's name is valid (i.e. it contains only letters, digits, and
+ * underscores, and does not start with a digit).
*/
static void validateSymbolName(final GenericDescriptor descriptor)
- throws DescriptorValidationException {
+ throws DescriptorValidationException {
final String name = descriptor.getName();
if (name.length() == 0) {
throw new DescriptorValidationException(descriptor, "Missing name.");
@@ -2473,16 +2490,15 @@ public final class Descriptors {
}
// First character must be letter or _. Subsequent characters may
// be letters, numbers, or digits.
- if (Character.isLetter(c) || c == '_' ||
- (Character.isDigit(c) && i > 0)) {
+ if (Character.isLetter(c) || c == '_' || (Character.isDigit(c) && i > 0)) {
// Valid
} else {
valid = false;
}
}
if (!valid) {
- throw new DescriptorValidationException(descriptor,
- '\"' + name + "\" is not a valid identifier.");
+ throw new DescriptorValidationException(
+ descriptor, '\"' + name + "\" is not a valid identifier.");
}
}
}
@@ -2491,17 +2507,29 @@ public final class Descriptors {
/** Describes an oneof of a message type. */
public static final class OneofDescriptor {
/** Get the index of this descriptor within its parent. */
- public int getIndex() { return index; }
+ public int getIndex() {
+ return index;
+ }
- public String getName() { return proto.getName(); }
+ public String getName() {
+ return proto.getName();
+ }
- public FileDescriptor getFile() { return file; }
+ public FileDescriptor getFile() {
+ return file;
+ }
- public String getFullName() { return fullName; }
+ public String getFullName() {
+ return fullName;
+ }
- public Descriptor getContainingType() { return containingType; }
+ public Descriptor getContainingType() {
+ return containingType;
+ }
- public int getFieldCount() { return fieldCount; }
+ public int getFieldCount() {
+ return fieldCount;
+ }
public OneofOptions getOptions() {
return proto.getOptions();
@@ -2520,11 +2548,12 @@ public final class Descriptors {
this.proto = proto;
}
- private OneofDescriptor(final OneofDescriptorProto proto,
- final FileDescriptor file,
- final Descriptor parent,
- final int index)
- throws DescriptorValidationException {
+ private OneofDescriptor(
+ final OneofDescriptorProto proto,
+ final FileDescriptor file,
+ final Descriptor parent,
+ final int index)
+ throws DescriptorValidationException {
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;
diff --git a/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java
index 7ae94349..fefa636e 100644
--- a/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java
+++ b/java/core/src/main/java/com/google/protobuf/DiscardUnknownFieldsParser.java
@@ -30,9 +30,7 @@
package com.google.protobuf;
-/**
- * Parsers to discard unknown fields during parsing.
- */
+/** Parsers to discard unknown fields during parsing. */
public final class DiscardUnknownFieldsParser {
/**
@@ -40,11 +38,12 @@ public final class DiscardUnknownFieldsParser {
* 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);
- * }
+ * 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.
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 5b28b4a8..e7b8fa83 100644
--- a/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
@@ -46,6 +46,7 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
implements DoubleList, RandomAccess, PrimitiveNonBoxingCollection {
private static final DoubleArrayList EMPTY_LIST = new DoubleArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
@@ -54,9 +55,7 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
return EMPTY_LIST;
}
- /**
- * The backing store for the list.
- */
+ /** The backing store for the list. */
private double[] array;
/**
@@ -65,16 +64,13 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
*/
private int size;
- /**
- * Constructs a new mutable {@code DoubleArrayList} with default capacity.
- */
+ /** Constructs a new mutable {@code DoubleArrayList} with default capacity. */
DoubleArrayList() {
this(new double[DEFAULT_CAPACITY], 0);
}
/**
- * Constructs a new mutable {@code DoubleArrayList}
- * containing the same elements as {@code other}.
+ * Constructs a new mutable {@code DoubleArrayList} containing the same elements as {@code other}.
*/
private DoubleArrayList(double[] other, int size) {
array = other;
@@ -169,17 +165,13 @@ final class DoubleArrayList extends AbstractProtobufList<Double>
addDouble(index, element);
}
- /**
- * Like {@link #add(Double)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Double)} but more efficient in that it doesn't box the element. */
@Override
public void addDouble(double element) {
addDouble(size, element);
}
- /**
- * Like {@link #add(int, Double)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(int, Double)} but more efficient in that it doesn't box the element. */
private void addDouble(int index, double element) {
ensureIsMutable();
if (index < 0 || index > size) {
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 a6a774b7..63dda6b9 100644
--- a/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
+++ b/java/core/src/main/java/com/google/protobuf/DynamicMessage.java
@@ -43,8 +43,8 @@ import java.util.List;
import java.util.Map;
/**
- * An implementation of {@link Message} that can represent arbitrary types,
- * given a {@link Descriptors.Descriptor}.
+ * An implementation of {@link Message} that can represent arbitrary types, given a {@link
+ * Descriptors.Descriptor}.
*
* @author kenton@google.com Kenton Varda
*/
@@ -56,88 +56,83 @@ public final class DynamicMessage extends AbstractMessage {
private int memoizedSize = -1;
/**
- * Construct a {@code DynamicMessage} using the given {@code FieldSet}.
- * oneofCases stores the FieldDescriptor for each oneof to indicate
- * which field is set. Caller should make sure the array is immutable.
+ * Construct a {@code DynamicMessage} using the given {@code FieldSet}. oneofCases stores the
+ * FieldDescriptor for each oneof to indicate which field is set. Caller should make sure the
+ * array is immutable.
*
- * This constructor is package private and will be used in
- * {@code DynamicMutableMessage} to convert a mutable message to an immutable
- * message.
+ * <p>This constructor is package private and will be used in {@code DynamicMutableMessage} to
+ * convert a mutable message to an immutable message.
*/
- DynamicMessage(Descriptor type, FieldSet<FieldDescriptor> fields,
- FieldDescriptor[] oneofCases,
- UnknownFieldSet unknownFields) {
+ DynamicMessage(
+ Descriptor type,
+ FieldSet<FieldDescriptor> fields,
+ FieldDescriptor[] oneofCases,
+ UnknownFieldSet unknownFields) {
this.type = type;
this.fields = fields;
this.oneofCases = oneofCases;
this.unknownFields = unknownFields;
}
- /**
- * Get a {@code DynamicMessage} representing the default instance of the
- * given type.
- */
+ /** Get a {@code DynamicMessage} representing the default instance of the given type. */
public static DynamicMessage getDefaultInstance(Descriptor type) {
int oneofDeclCount = type.toProto().getOneofDeclCount();
FieldDescriptor[] oneofCases = new FieldDescriptor[oneofDeclCount];
- return new DynamicMessage(type, FieldSet.<FieldDescriptor>emptySet(),
- oneofCases,
- UnknownFieldSet.getDefaultInstance());
+ return new DynamicMessage(
+ type,
+ FieldSet.<FieldDescriptor>emptySet(),
+ oneofCases,
+ UnknownFieldSet.getDefaultInstance());
}
/** Parse a message of the given type from the given input stream. */
- public static DynamicMessage parseFrom(Descriptor type,
- CodedInputStream input)
- throws IOException {
+ public static DynamicMessage parseFrom(Descriptor type, CodedInputStream input)
+ throws IOException {
return newBuilder(type).mergeFrom(input).buildParsed();
}
/** Parse a message of the given type from the given input stream. */
public static DynamicMessage parseFrom(
- Descriptor type,
- CodedInputStream input,
- ExtensionRegistry extensionRegistry)
+ Descriptor type, CodedInputStream input, ExtensionRegistry extensionRegistry)
throws IOException {
return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed();
}
/** Parse {@code data} as a message of the given type and return it. */
public static DynamicMessage parseFrom(Descriptor type, ByteString data)
- throws InvalidProtocolBufferException {
+ throws InvalidProtocolBufferException {
return newBuilder(type).mergeFrom(data).buildParsed();
}
/** Parse {@code data} as a message of the given type and return it. */
- public static DynamicMessage parseFrom(Descriptor type, ByteString data,
- ExtensionRegistry extensionRegistry)
- throws InvalidProtocolBufferException {
+ public static DynamicMessage parseFrom(
+ Descriptor type, ByteString data, ExtensionRegistry extensionRegistry)
+ throws InvalidProtocolBufferException {
return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed();
}
/** Parse {@code data} as a message of the given type and return it. */
public static DynamicMessage parseFrom(Descriptor type, byte[] data)
- throws InvalidProtocolBufferException {
+ throws InvalidProtocolBufferException {
return newBuilder(type).mergeFrom(data).buildParsed();
}
/** Parse {@code data} as a message of the given type and return it. */
- public static DynamicMessage parseFrom(Descriptor type, byte[] data,
- ExtensionRegistry extensionRegistry)
- throws InvalidProtocolBufferException {
+ public static DynamicMessage parseFrom(
+ Descriptor type, byte[] data, ExtensionRegistry extensionRegistry)
+ throws InvalidProtocolBufferException {
return newBuilder(type).mergeFrom(data, extensionRegistry).buildParsed();
}
/** Parse a message of the given type from {@code input} and return it. */
- public static DynamicMessage parseFrom(Descriptor type, InputStream input)
- throws IOException {
+ public static DynamicMessage parseFrom(Descriptor type, InputStream input) throws IOException {
return newBuilder(type).mergeFrom(input).buildParsed();
}
/** Parse a message of the given type from {@code input} and return it. */
- public static DynamicMessage parseFrom(Descriptor type, InputStream input,
- ExtensionRegistry extensionRegistry)
- throws IOException {
+ public static DynamicMessage parseFrom(
+ Descriptor type, InputStream input, ExtensionRegistry extensionRegistry) throws IOException {
return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed();
}
@@ -147,8 +142,8 @@ public final class DynamicMessage extends AbstractMessage {
}
/**
- * Construct a {@link Message.Builder} for a message of the same type as
- * {@code prototype}, and initialize it with {@code prototype}'s contents.
+ * Construct a {@link Message.Builder} for a message of the same type as {@code prototype}, and
+ * initialize it with {@code prototype}'s contents.
*/
public static Builder newBuilder(Message prototype) {
return new Builder(prototype.getDescriptorForType()).mergeFrom(prototype);
@@ -227,8 +222,7 @@ public final class DynamicMessage extends AbstractMessage {
return unknownFields;
}
- static boolean isInitialized(Descriptor type,
- FieldSet<FieldDescriptor> fields) {
+ static boolean isInitialized(Descriptor type, FieldSet<FieldDescriptor> fields) {
// Check that all required fields are present.
for (final FieldDescriptor field : type.getFields()) {
if (field.isRequired()) {
@@ -298,8 +292,7 @@ public final class DynamicMessage extends AbstractMessage {
} catch (InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (IOException e) {
- throw new InvalidProtocolBufferException(e)
- .setUnfinishedMessage(builder.buildPartial());
+ throw new InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
@@ -309,24 +302,20 @@ public final class DynamicMessage extends AbstractMessage {
/** Verifies that the field is a field of this message. */
private void verifyContainingType(FieldDescriptor field) {
if (field.getContainingType() != type) {
- throw new IllegalArgumentException(
- "FieldDescriptor does not match message type.");
+ throw new IllegalArgumentException("FieldDescriptor does not match message type.");
}
}
/** Verifies that the oneof is an oneof of this message. */
private void verifyOneofContainingType(OneofDescriptor oneof) {
if (oneof.getContainingType() != type) {
- throw new IllegalArgumentException(
- "OneofDescriptor does not match message type.");
+ throw new IllegalArgumentException("OneofDescriptor does not match message type.");
}
}
// =================================================================
- /**
- * Builder for {@link DynamicMessage}s.
- */
+ /** Builder for {@link DynamicMessage}s. */
public static final class Builder extends AbstractMessage.Builder<Builder> {
private final Descriptor type;
private FieldSet<FieldDescriptor> fields;
@@ -380,7 +369,7 @@ public final class DynamicMessage extends AbstractMessage {
DynamicMessage otherDynamicMessage = (DynamicMessage) other;
if (otherDynamicMessage.type != type) {
throw new IllegalArgumentException(
- "mergeFrom(Message) can only merge messages of the same type.");
+ "mergeFrom(Message) can only merge messages of the same type.");
}
ensureIsMutable();
fields.mergeFrom(otherDynamicMessage.fields);
@@ -406,23 +395,28 @@ public final class DynamicMessage extends AbstractMessage {
public DynamicMessage build() {
if (!isInitialized()) {
throw newUninitializedMessageException(
- new DynamicMessage(type, fields,
- java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields));
+ new DynamicMessage(
+ type,
+ fields,
+ java.util.Arrays.copyOf(oneofCases, oneofCases.length),
+ unknownFields));
}
return buildPartial();
}
/**
- * Helper for DynamicMessage.parseFrom() methods to call. Throws
- * {@link InvalidProtocolBufferException} instead of
- * {@link UninitializedMessageException}.
+ * Helper for DynamicMessage.parseFrom() methods to call. Throws {@link
+ * InvalidProtocolBufferException} instead of {@link UninitializedMessageException}.
*/
private DynamicMessage buildParsed() throws InvalidProtocolBufferException {
if (!isInitialized()) {
throw newUninitializedMessageException(
- new DynamicMessage(type, fields,
- java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields))
- .asInvalidProtocolBufferException();
+ new DynamicMessage(
+ type,
+ fields,
+ java.util.Arrays.copyOf(oneofCases, oneofCases.length),
+ unknownFields))
+ .asInvalidProtocolBufferException();
}
return buildPartial();
}
@@ -431,8 +425,8 @@ public final class DynamicMessage extends AbstractMessage {
public DynamicMessage buildPartial() {
fields.makeImmutable();
DynamicMessage result =
- new DynamicMessage(type, fields,
- java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields);
+ new DynamicMessage(
+ type, fields, java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields);
return result;
}
@@ -441,7 +435,7 @@ public final class DynamicMessage extends AbstractMessage {
Builder result = new Builder(type);
result.fields.mergeFrom(fields);
result.mergeUnknownFields(unknownFields);
- System.arraycopy(oneofCases, 0, result.oneofCases, 0 , oneofCases.length);
+ System.arraycopy(oneofCases, 0, result.oneofCases, 0, oneofCases.length);
return result;
}
@@ -471,7 +465,7 @@ public final class DynamicMessage extends AbstractMessage {
if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalArgumentException(
- "newBuilderForField is only valid for fields with message type.");
+ "newBuilderForField is only valid for fields with message type.");
}
return new Builder(field.getMessageType());
@@ -608,50 +602,37 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder setUnknownFields(UnknownFieldSet unknownFields) {
- if (getDescriptorForType().getFile().getSyntax() == Descriptors.FileDescriptor.Syntax.PROTO3
- && CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
- return this;
- }
this.unknownFields = unknownFields;
return this;
}
@Override
public Builder mergeUnknownFields(UnknownFieldSet unknownFields) {
- if (getDescriptorForType().getFile().getSyntax() == Descriptors.FileDescriptor.Syntax.PROTO3
- && CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
- return this;
- }
this.unknownFields =
- UnknownFieldSet.newBuilder(this.unknownFields)
- .mergeFrom(unknownFields)
- .build();
+ UnknownFieldSet.newBuilder(this.unknownFields).mergeFrom(unknownFields).build();
return this;
}
/** Verifies that the field is a field of this message. */
private void verifyContainingType(FieldDescriptor field) {
if (field.getContainingType() != type) {
- throw new IllegalArgumentException(
- "FieldDescriptor does not match message type.");
+ throw new IllegalArgumentException("FieldDescriptor does not match message type.");
}
}
/** Verifies that the oneof is an oneof of this message. */
private void verifyOneofContainingType(OneofDescriptor oneof) {
if (oneof.getContainingType() != type) {
- throw new IllegalArgumentException(
- "OneofDescriptor does not match message type.");
+ throw new IllegalArgumentException("OneofDescriptor does not match message type.");
}
}
/** Verifies that the value is EnumValueDescriptor and matches Enum Type. */
- private void ensureSingularEnumValueDescriptor(
- FieldDescriptor field, Object value) {
+ private void ensureSingularEnumValueDescriptor(FieldDescriptor field, Object value) {
checkNotNull(value);
if (!(value instanceof EnumValueDescriptor)) {
throw new IllegalArgumentException(
- "DynamicMessage should use EnumValueDescriptor to set Enum Value.");
+ "DynamicMessage should use EnumValueDescriptor to set Enum Value.");
}
// TODO(xiaofeng): Re-enable this check after Orgstore is fixed to not
// set incorrect EnumValueDescriptors.
@@ -665,14 +646,13 @@ public final class DynamicMessage extends AbstractMessage {
}
/** Verifies the value for an enum field. */
- private void ensureEnumValueDescriptor(
- FieldDescriptor field, Object value) {
+ private void ensureEnumValueDescriptor(FieldDescriptor field, Object value) {
if (field.isRepeated()) {
for (Object item : (List) value) {
ensureSingularEnumValueDescriptor(field, item);
}
} else {
- ensureSingularEnumValueDescriptor(field, value);
+ ensureSingularEnumValueDescriptor(field, value);
}
}
@@ -686,14 +666,14 @@ public final class DynamicMessage extends AbstractMessage {
public com.google.protobuf.Message.Builder getFieldBuilder(FieldDescriptor field) {
// TODO(xiangl): need implementation for dynamic message
throw new UnsupportedOperationException(
- "getFieldBuilder() called on a dynamic message type.");
+ "getFieldBuilder() called on a dynamic message type.");
}
@Override
- public com.google.protobuf.Message.Builder getRepeatedFieldBuilder(FieldDescriptor field,
- int index) {
+ public com.google.protobuf.Message.Builder getRepeatedFieldBuilder(
+ FieldDescriptor field, int index) {
throw new UnsupportedOperationException(
- "getRepeatedFieldBuilder() called on a dynamic message type.");
+ "getRepeatedFieldBuilder() called on a dynamic message type.");
}
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java b/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java
index 3cd4c884..d55b278c 100644
--- a/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java
+++ b/java/core/src/main/java/com/google/protobuf/ExperimentalApi.java
@@ -41,26 +41,25 @@ import java.lang.annotation.Target;
* backward-compatibility.
*
* <p>Usage guidelines:
+ *
* <ol>
- * <li>This annotation is used only on public API. Internal interfaces should not use it.</li>
- * <li>This annotation should only be added to new APIs. Adding it to an existing API is
- * considered API-breaking.</li>
- * <li>Removing this annotation from an API gives it stable status.</li>
+ * <li>This annotation is used only on public API. Internal interfaces should not use it.
+ * <li>This annotation should only be added to new APIs. Adding it to an existing API is
+ * considered API-breaking.
+ * <li>Removing this annotation from an API gives it stable status.
* </ol>
*/
@Retention(RetentionPolicy.SOURCE)
@Target({
- ElementType.ANNOTATION_TYPE,
- ElementType.CONSTRUCTOR,
- ElementType.FIELD,
- ElementType.METHOD,
- ElementType.PACKAGE,
- ElementType.TYPE})
+ ElementType.ANNOTATION_TYPE,
+ ElementType.CONSTRUCTOR,
+ ElementType.FIELD,
+ ElementType.METHOD,
+ ElementType.PACKAGE,
+ ElementType.TYPE
+})
@Documented
public @interface ExperimentalApi {
- /**
- * Context information such as links to discussion thread, tracking issue etc.
- */
+ /** Context information such as links to discussion thread, tracking issue etc. */
String value() default "";
}
-
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 5df12e64..e5da634f 100644
--- a/java/core/src/main/java/com/google/protobuf/Extension.java
+++ b/java/core/src/main/java/com/google/protobuf/Extension.java
@@ -49,9 +49,7 @@ public abstract class Extension<ContainingType extends MessageLite, Type>
// All the methods below are extension implementation details.
- /**
- * The API type that the extension is used for.
- */
+ /** The API type that the extension is used for. */
protected enum ExtensionType {
IMMUTABLE,
MUTABLE,
@@ -60,24 +58,25 @@ public abstract class Extension<ContainingType extends MessageLite, Type>
protected abstract ExtensionType getExtensionType();
- /**
- * Type of a message extension.
- */
+ /** Type of a message extension. */
public enum MessageType {
PROTO1,
PROTO2,
}
/**
- * If the extension is a message extension (i.e., getLiteType() == MESSAGE),
- * returns the type of the message, otherwise undefined.
+ * If the extension is a message extension (i.e., getLiteType() == MESSAGE), returns the type of
+ * the message, otherwise undefined.
*/
public MessageType getMessageType() {
return MessageType.PROTO2;
}
protected abstract Object fromReflectionType(Object value);
+
protected abstract Object singularFromReflectionType(Object value);
+
protected abstract Object toReflectionType(Object value);
+
protected abstract Object singularToReflectionType(Object value);
}
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionLite.java b/java/core/src/main/java/com/google/protobuf/ExtensionLite.java
index f8f5bd2c..0fb5f49e 100644
--- a/java/core/src/main/java/com/google/protobuf/ExtensionLite.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionLite.java
@@ -32,9 +32,9 @@ package com.google.protobuf;
/**
* Lite interface that generated extensions implement.
- * <p>
- * Methods are for use by generated code only. You can hold a reference to
- * extensions using this type name.
+ *
+ * <p>Methods are for use by generated code only. You can hold a reference to extensions using this
+ * type name.
*/
public abstract class ExtensionLite<ContainingType extends MessageLite, Type> {
@@ -50,12 +50,9 @@ public abstract class ExtensionLite<ContainingType extends MessageLite, Type> {
/** Returns the default value of the extension field. */
public abstract Type getDefaultValue();
- /**
- * Returns the default instance of the extension field, if it's a message
- * extension.
- */
+ /** Returns the default instance of the extension field, if it's a message extension. */
public abstract MessageLite getMessageDefaultInstance();
-
+
/** Returns whether or not this extension is a Lite Extension. */
boolean isLite() {
return true;
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java
index a22a74a0..aeeaee53 100644
--- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java
@@ -40,11 +40,10 @@ import java.util.Map;
import java.util.Set;
/**
- * A table of known extensions, searchable by name or field number. When
- * parsing a protocol message that might have extensions, you must provide
- * an {@code ExtensionRegistry} in which you have registered any extensions
- * that you want to be able to parse. Otherwise, those extensions will just
- * be treated like unknown fields.
+ * A table of known extensions, searchable by name or field number. When parsing a protocol message
+ * that might have extensions, you must provide an {@code ExtensionRegistry} in which you have
+ * registered any extensions that you want to be able to parse. Otherwise, those extensions will
+ * just be treated like unknown fields.
*
* <p>For example, if you had the {@code .proto} file:
*
@@ -70,25 +69,22 @@ import java.util.Set;
*
* <p>Background:
*
- * <p>You might wonder why this is necessary. Two alternatives might come to
- * mind. First, you might imagine a system where generated extensions are
- * automatically registered when their containing classes are loaded. This
- * is a popular technique, but is bad design; among other things, it creates a
- * situation where behavior can change depending on what classes happen to be
- * loaded. It also introduces a security vulnerability, because an
- * unprivileged class could cause its code to be called unexpectedly from a
- * privileged class by registering itself as an extension of the right type.
+ * <p>You might wonder why this is necessary. Two alternatives might come to mind. First, you might
+ * imagine a system where generated extensions are automatically registered when their containing
+ * classes are loaded. This is a popular technique, but is bad design; among other things, it
+ * creates a situation where behavior can change depending on what classes happen to be loaded. It
+ * also introduces a security vulnerability, because an unprivileged class could cause its code to
+ * be called unexpectedly from a privileged class by registering itself as an extension of the right
+ * type.
*
- * <p>Another option you might consider is lazy parsing: do not parse an
- * extension until it is first requested, at which point the caller must
- * provide a type to use. This introduces a different set of problems. First,
- * it would require a mutex lock any time an extension was accessed, which
- * would be slow. Second, corrupt data would not be detected until first
- * access, at which point it would be much harder to deal with it. Third, it
- * could violate the expectation that message objects are immutable, since the
- * type provided could be any arbitrary message class. An unprivileged user
- * could take advantage of this to inject a mutable object into a message
- * belonging to privileged code and create mischief.
+ * <p>Another option you might consider is lazy parsing: do not parse an extension until it is first
+ * requested, at which point the caller must provide a type to use. This introduces a different set
+ * of problems. First, it would require a mutex lock any time an extension was accessed, which would
+ * be slow. Second, corrupt data would not be detected until first access, at which point it would
+ * be much harder to deal with it. Third, it could violate the expectation that message objects are
+ * immutable, since the type provided could be any arbitrary message class. An unprivileged user
+ * could take advantage of this to inject a mutable object into a message belonging to privileged
+ * code and create mischief.
*
* @author kenton@google.com Kenton Varda
*/
@@ -116,8 +112,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
public final FieldDescriptor descriptor;
/**
- * A default instance of the extension's type, if it has a message type.
- * Otherwise, {@code null}.
+ * A default instance of the extension's type, if it has a message type. Otherwise, {@code
+ * null}.
*/
public final Message defaultInstance;
@@ -125,48 +121,41 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
this.descriptor = descriptor;
defaultInstance = null;
}
- private ExtensionInfo(final FieldDescriptor descriptor,
- final Message defaultInstance) {
+
+ private ExtensionInfo(final FieldDescriptor descriptor, final Message defaultInstance) {
this.descriptor = descriptor;
this.defaultInstance = defaultInstance;
}
}
- /**
- * Deprecated. Use {@link #findImmutableExtensionByName(String)} instead.
- */
+ /** Deprecated. Use {@link #findImmutableExtensionByName(String)} instead. */
+ @Deprecated
public ExtensionInfo findExtensionByName(final String fullName) {
return findImmutableExtensionByName(fullName);
}
/**
- * Find an extension for immutable APIs by fully-qualified field name,
- * in the proto namespace. i.e. {@code result.descriptor.fullName()} will
- * match {@code fullName} if a match is found.
+ * Find an extension for immutable APIs by fully-qualified field name, in the proto namespace.
+ * i.e. {@code result.descriptor.fullName()} will match {@code fullName} if a match is found.
*
- * @return Information about the extension if found, or {@code null}
- * otherwise.
+ * @return Information about the extension if found, or {@code null} otherwise.
*/
public ExtensionInfo findImmutableExtensionByName(final String fullName) {
return immutableExtensionsByName.get(fullName);
}
/**
- * Find an extension for mutable APIs by fully-qualified field name,
- * in the proto namespace. i.e. {@code result.descriptor.fullName()} will
- * match {@code fullName} if a match is found.
+ * Find an extension for mutable APIs by fully-qualified field name, in the proto namespace. i.e.
+ * {@code result.descriptor.fullName()} will match {@code fullName} if a match is found.
*
- * @return Information about the extension if found, or {@code null}
- * otherwise.
+ * @return Information about the extension if found, or {@code null} otherwise.
*/
public ExtensionInfo findMutableExtensionByName(final String fullName) {
return mutableExtensionsByName.get(fullName);
}
- /**
- * Deprecated. Use {@link #findImmutableExtensionByNumber(
- * Descriptors.Descriptor, int)}
- */
+ /** Deprecated. Use {@link #findImmutableExtensionByNumber( Descriptors.Descriptor, int)} */
+ @Deprecated
public ExtensionInfo findExtensionByNumber(
final Descriptor containingType, final int fieldNumber) {
return findImmutableExtensionByNumber(containingType, fieldNumber);
@@ -175,34 +164,28 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
/**
* Find an extension by containing type and field number for immutable APIs.
*
- * @return Information about the extension if found, or {@code null}
- * otherwise.
+ * @return Information about the extension if found, or {@code null} otherwise.
*/
public ExtensionInfo findImmutableExtensionByNumber(
final Descriptor containingType, final int fieldNumber) {
- return immutableExtensionsByNumber.get(
- new DescriptorIntPair(containingType, fieldNumber));
+ return immutableExtensionsByNumber.get(new DescriptorIntPair(containingType, fieldNumber));
}
/**
* Find an extension by containing type and field number for mutable APIs.
*
- * @return Information about the extension if found, or {@code null}
- * otherwise.
+ * @return Information about the extension if found, or {@code null} otherwise.
*/
public ExtensionInfo findMutableExtensionByNumber(
final Descriptor containingType, final int fieldNumber) {
- return mutableExtensionsByNumber.get(
- new DescriptorIntPair(containingType, fieldNumber));
+ return mutableExtensionsByNumber.get(new DescriptorIntPair(containingType, fieldNumber));
}
/**
- * Find all extensions for mutable APIs by fully-qualified name of
- * extended class. Note that this method is more computationally expensive
- * than getting a single extension by name or number.
+ * Find all extensions for mutable APIs by fully-qualified name of extended class. Note that this
+ * method is more computationally expensive than getting a single extension by name or number.
*
- * @return Information about the extensions found, or {@code null} if there
- * are none.
+ * @return Information about the extensions found, or {@code null} if there are none.
*/
public Set<ExtensionInfo> getAllMutableExtensionsByExtendedType(final String fullName) {
HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
@@ -215,12 +198,11 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
}
/**
- * Find all extensions for immutable APIs by fully-qualified name of
- * extended class. Note that this method is more computationally expensive
- * than getting a single extension by name or number.
+ * Find all extensions for immutable APIs by fully-qualified name of extended class. Note that
+ * this method is more computationally expensive than getting a single extension by name or
+ * number.
*
- * @return Information about the extensions found, or {@code null} if there
- * are none.
+ * @return Information about the extensions found, or {@code null} if there are none.
*/
public Set<ExtensionInfo> getAllImmutableExtensionsByExtendedType(final String fullName) {
HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
@@ -234,8 +216,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
/** Add an extension from a generated file to the registry. */
public void add(final Extension<?, ?> extension) {
- if (extension.getExtensionType() != Extension.ExtensionType.IMMUTABLE &&
- extension.getExtensionType() != Extension.ExtensionType.MUTABLE) {
+ if (extension.getExtensionType() != Extension.ExtensionType.IMMUTABLE
+ && extension.getExtensionType() != Extension.ExtensionType.MUTABLE) {
// do not support other extension types. ignore
return;
}
@@ -248,15 +230,14 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
}
static ExtensionInfo newExtensionInfo(final Extension<?, ?> extension) {
- if (extension.getDescriptor().getJavaType() ==
- FieldDescriptor.JavaType.MESSAGE) {
+ if (extension.getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (extension.getMessageDefaultInstance() == null) {
throw new IllegalStateException(
- "Registered message-type extension had null default instance: " +
- extension.getDescriptor().getFullName());
+ "Registered message-type extension had null default instance: "
+ + extension.getDescriptor().getFullName());
}
- return new ExtensionInfo(extension.getDescriptor(),
- (Message) extension.getMessageDefaultInstance());
+ return new ExtensionInfo(
+ extension.getDescriptor(), (Message) extension.getMessageDefaultInstance());
} else {
return new ExtensionInfo(extension.getDescriptor(), null);
}
@@ -266,8 +247,8 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
public void add(final FieldDescriptor type) {
if (type.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalArgumentException(
- "ExtensionRegistry.add() must be provided a default instance when " +
- "adding an embedded message extension.");
+ "ExtensionRegistry.add() must be provided a default instance when "
+ + "adding an embedded message extension.");
}
ExtensionInfo info = new ExtensionInfo(type, null);
add(info, Extension.ExtensionType.IMMUTABLE);
@@ -278,11 +259,9 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
public void add(final FieldDescriptor type, final Message defaultInstance) {
if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalArgumentException(
- "ExtensionRegistry.add() provided a default instance for a " +
- "non-message extension.");
+ "ExtensionRegistry.add() provided a default instance for a non-message extension.");
}
- add(new ExtensionInfo(type, defaultInstance),
- Extension.ExtensionType.IMMUTABLE);
+ add(new ExtensionInfo(type, defaultInstance), Extension.ExtensionType.IMMUTABLE);
}
// =================================================================
@@ -291,22 +270,17 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
private ExtensionRegistry() {
this.immutableExtensionsByName = new HashMap<String, ExtensionInfo>();
this.mutableExtensionsByName = new HashMap<String, ExtensionInfo>();
- this.immutableExtensionsByNumber =
- new HashMap<DescriptorIntPair, ExtensionInfo>();
- this.mutableExtensionsByNumber =
- new HashMap<DescriptorIntPair, ExtensionInfo>();
+ this.immutableExtensionsByNumber = new HashMap<DescriptorIntPair, ExtensionInfo>();
+ this.mutableExtensionsByNumber = new HashMap<DescriptorIntPair, ExtensionInfo>();
}
private ExtensionRegistry(ExtensionRegistry other) {
super(other);
- this.immutableExtensionsByName =
- Collections.unmodifiableMap(other.immutableExtensionsByName);
- this.mutableExtensionsByName =
- Collections.unmodifiableMap(other.mutableExtensionsByName);
+ this.immutableExtensionsByName = Collections.unmodifiableMap(other.immutableExtensionsByName);
+ this.mutableExtensionsByName = Collections.unmodifiableMap(other.mutableExtensionsByName);
this.immutableExtensionsByNumber =
Collections.unmodifiableMap(other.immutableExtensionsByNumber);
- this.mutableExtensionsByNumber =
- Collections.unmodifiableMap(other.mutableExtensionsByNumber);
+ this.mutableExtensionsByNumber = Collections.unmodifiableMap(other.mutableExtensionsByNumber);
}
private final Map<String, ExtensionInfo> immutableExtensionsByName;
@@ -316,24 +290,19 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
ExtensionRegistry(boolean empty) {
super(EMPTY_REGISTRY_LITE);
- this.immutableExtensionsByName =
- Collections.<String, ExtensionInfo>emptyMap();
- this.mutableExtensionsByName =
- Collections.<String, ExtensionInfo>emptyMap();
- this.immutableExtensionsByNumber =
- Collections.<DescriptorIntPair, ExtensionInfo>emptyMap();
- this.mutableExtensionsByNumber =
- Collections.<DescriptorIntPair, ExtensionInfo>emptyMap();
+ this.immutableExtensionsByName = Collections.<String, ExtensionInfo>emptyMap();
+ this.mutableExtensionsByName = Collections.<String, ExtensionInfo>emptyMap();
+ this.immutableExtensionsByNumber = Collections.<DescriptorIntPair, ExtensionInfo>emptyMap();
+ this.mutableExtensionsByNumber = Collections.<DescriptorIntPair, ExtensionInfo>emptyMap();
}
+
static final ExtensionRegistry EMPTY_REGISTRY = new ExtensionRegistry(true);
- private void add(
- final ExtensionInfo extension,
- final Extension.ExtensionType extensionType) {
+ private void add(final ExtensionInfo extension, final Extension.ExtensionType extensionType) {
if (!extension.descriptor.isExtension()) {
throw new IllegalArgumentException(
- "ExtensionRegistry.add() was given a FieldDescriptor for a regular " +
- "(non-extension) field.");
+ "ExtensionRegistry.add() was given a FieldDescriptor for a regular "
+ + "(non-extension) field.");
}
Map<String, ExtensionInfo> extensionsByName;
@@ -354,15 +323,15 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
extensionsByName.put(extension.descriptor.getFullName(), extension);
extensionsByNumber.put(
- new DescriptorIntPair(extension.descriptor.getContainingType(),
- extension.descriptor.getNumber()),
- extension);
+ new DescriptorIntPair(
+ extension.descriptor.getContainingType(), extension.descriptor.getNumber()),
+ extension);
final FieldDescriptor field = extension.descriptor;
- if (field.getContainingType().getOptions().getMessageSetWireFormat() &&
- field.getType() == FieldDescriptor.Type.MESSAGE &&
- field.isOptional() &&
- field.getExtensionScope() == field.getMessageType()) {
+ if (field.getContainingType().getOptions().getMessageSetWireFormat()
+ && field.getType() == FieldDescriptor.Type.MESSAGE
+ && field.isOptional()
+ && field.getExtensionScope() == field.getMessageType()) {
// This is an extension of a MessageSet type defined within the extension
// type's own scope. For backwards-compatibility, allow it to be looked
// up by type name.
@@ -384,12 +353,13 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
public int hashCode() {
return descriptor.hashCode() * ((1 << 16) - 1) + number;
}
+
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof DescriptorIntPair)) {
return false;
}
- final DescriptorIntPair other = (DescriptorIntPair)obj;
+ final DescriptorIntPair other = (DescriptorIntPair) obj;
return descriptor == other.descriptor && number == other.number;
}
}
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 89f7ab9b..f070aae7 100644
--- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryFactory.java
@@ -35,16 +35,15 @@ 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}.
+ * <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}.
*/
final class ExtensionRegistryFactory {
static final String FULL_REGISTRY_CLASS_NAME = "com.google.protobuf.ExtensionRegistry";
/* Visible for Testing
- @Nullable */
+ @Nullable */
static final Class<?> EXTENSION_REGISTRY_CLASS = reflectExtensionRegistry();
/* @Nullable */
@@ -90,7 +89,7 @@ final class ExtensionRegistryFactory {
private static final ExtensionRegistryLite invokeSubclassFactory(String methodName)
throws Exception {
- return (ExtensionRegistryLite) EXTENSION_REGISTRY_CLASS
- .getDeclaredMethod(methodName).invoke(null);
+ return (ExtensionRegistryLite)
+ EXTENSION_REGISTRY_CLASS.getDeclaredMethod(methodName).invoke(null);
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java
index f3d48d3a..0ce5f549 100644
--- a/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java
+++ b/java/core/src/main/java/com/google/protobuf/ExtensionRegistryLite.java
@@ -36,22 +36,20 @@ import java.util.Map;
/**
* Equivalent to {@link ExtensionRegistry} but supports only "lite" types.
- * <p>
- * If all of your types are lite types, then you only need to use
- * {@code ExtensionRegistryLite}. Similarly, if all your types are regular
- * types, then you only need {@link ExtensionRegistry}. Typically it does not
- * make sense to mix the two, since if you have any regular types in your
- * program, you then require the full runtime and lose all the benefits of
- * the lite runtime, so you might as well make all your types be regular types.
- * However, in some cases (e.g. when depending on multiple third-party libraries
- * where one uses lite types and one uses regular), you may find yourself
- * wanting to mix the two. In this case things get more complicated.
- * <p>
- * There are three factors to consider: Whether the type being extended is
- * lite, whether the embedded type (in the case of a message-typed extension)
- * is lite, and whether the extension itself is lite. Since all three are
- * declared in different files, they could all be different. Here are all
- * the combinations and which type of registry to use:
+ *
+ * <p>If all of your types are lite types, then you only need to use {@code ExtensionRegistryLite}.
+ * Similarly, if all your types are regular types, then you only need {@link ExtensionRegistry}.
+ * Typically it does not make sense to mix the two, since if you have any regular types in your
+ * program, you then require the full runtime and lose all the benefits of the lite runtime, so you
+ * might as well make all your types be regular types. However, in some cases (e.g. when depending
+ * on multiple third-party libraries where one uses lite types and one uses regular), you may find
+ * yourself wanting to mix the two. In this case things get more complicated.
+ *
+ * <p>There are three factors to consider: Whether the type being extended is lite, whether the
+ * embedded type (in the case of a message-typed extension) is lite, and whether the extension
+ * itself is lite. Since all three are declared in different files, they could all be different.
+ * Here are all the combinations and which type of registry to use:
+ *
* <pre>
* Extended type Inner type Extension Use registry
* =======================================================================
@@ -60,13 +58,12 @@ import java.util.Map;
* regular regular regular ExtensionRegistry
* all other combinations not supported
* </pre>
- * <p>
- * Note that just as regular types are not allowed to contain lite-type fields,
- * they are also not allowed to contain lite-type extensions. This is because
- * regular types must be fully accessible via reflection, which in turn means
- * that all the inner messages must also support reflection. On the other hand,
- * since regular types implement the entire lite interface, there is no problem
- * with embedding regular types inside lite types.
+ *
+ * <p>Note that just as regular types are not allowed to contain lite-type fields, they are also not
+ * allowed to contain lite-type extensions. This is because regular types must be fully accessible
+ * via reflection, which in turn means that all the inner messages must also support reflection. On
+ * the other hand, since regular types implement the entire lite interface, there is no problem with
+ * embedding regular types inside lite types.
*
* @author kenton@google.com Kenton Varda
*/
@@ -114,8 +111,8 @@ public class ExtensionRegistryLite {
}
/**
- * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or
- * {@code ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
+ * Get the unmodifiable singleton empty instance of either ExtensionRegistryLite or {@code
+ * ExtensionRegistry} (if the full (non-Lite) proto libraries are available).
*/
public static ExtensionRegistryLite getEmptyRegistry() {
return ExtensionRegistryFactory.createEmpty();
@@ -130,32 +127,27 @@ public class ExtensionRegistryLite {
/**
* Find an extension by containing type and field number.
*
- * @return Information about the extension if found, or {@code null}
- * otherwise.
+ * @return Information about the extension if found, or {@code null} otherwise.
*/
@SuppressWarnings("unchecked")
public <ContainingType extends MessageLite>
- GeneratedMessageLite.GeneratedExtension<ContainingType, ?>
- findLiteExtensionByNumber(
- final ContainingType containingTypeDefaultInstance,
- final int fieldNumber) {
+ GeneratedMessageLite.GeneratedExtension<ContainingType, ?> findLiteExtensionByNumber(
+ final ContainingType containingTypeDefaultInstance, final int fieldNumber) {
return (GeneratedMessageLite.GeneratedExtension<ContainingType, ?>)
- extensionsByNumber.get(
- new ObjectIntPair(containingTypeDefaultInstance, fieldNumber));
+ extensionsByNumber.get(new ObjectIntPair(containingTypeDefaultInstance, fieldNumber));
}
/** Add an extension from a lite generated file to the registry. */
- public final void add(
- final GeneratedMessageLite.GeneratedExtension<?, ?> extension) {
+ public final void add(final GeneratedMessageLite.GeneratedExtension<?, ?> extension) {
extensionsByNumber.put(
- new ObjectIntPair(extension.getContainingTypeDefaultInstance(),
- extension.getNumber()),
- extension);
+ new ObjectIntPair(extension.getContainingTypeDefaultInstance(), extension.getNumber()),
+ extension);
}
/**
- * Add an extension from a lite generated file to the registry only if it is
- * a non-lite extension i.e. {@link GeneratedMessageLite.GeneratedExtension}. */
+ * Add an extension from a lite generated file to the registry only if it is a non-lite extension
+ * i.e. {@link GeneratedMessageLite.GeneratedExtension}.
+ */
public final void add(ExtensionLite<?, ?> extension) {
if (GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(extension.getClass())) {
add((GeneratedMessageLite.GeneratedExtension<?, ?>) extension);
@@ -178,23 +170,20 @@ public class ExtensionRegistryLite {
ExtensionRegistryLite() {
this.extensionsByNumber =
- new HashMap<ObjectIntPair,
- GeneratedMessageLite.GeneratedExtension<?, ?>>();
+ new HashMap<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>();
}
- static final ExtensionRegistryLite EMPTY_REGISTRY_LITE =
- new ExtensionRegistryLite(true);
+
+ static final ExtensionRegistryLite EMPTY_REGISTRY_LITE = new ExtensionRegistryLite(true);
ExtensionRegistryLite(ExtensionRegistryLite other) {
if (other == EMPTY_REGISTRY_LITE) {
this.extensionsByNumber = Collections.emptyMap();
} else {
- this.extensionsByNumber =
- Collections.unmodifiableMap(other.extensionsByNumber);
+ this.extensionsByNumber = Collections.unmodifiableMap(other.extensionsByNumber);
}
}
- private final Map<ObjectIntPair,
- GeneratedMessageLite.GeneratedExtension<?, ?>>
+ private final Map<ObjectIntPair, GeneratedMessageLite.GeneratedExtension<?, ?>>
extensionsByNumber;
ExtensionRegistryLite(boolean empty) {
@@ -215,12 +204,13 @@ public class ExtensionRegistryLite {
public int hashCode() {
return System.identityHashCode(object) * ((1 << 16) - 1) + number;
}
+
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof ObjectIntPair)) {
return false;
}
- final ObjectIntPair other = (ObjectIntPair)obj;
+ final ObjectIntPair other = (ObjectIntPair) obj;
return object == other.object && number == other.number;
}
}
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 c09daa32..40a37625 100644
--- a/java/core/src/main/java/com/google/protobuf/FieldSet.java
+++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java
@@ -41,32 +41,35 @@ import java.util.List;
import java.util.Map;
/**
- * A class which represents an arbitrary set of fields of some message type.
- * This is used to implement {@link DynamicMessage}, and also to represent
- * extensions in {@link GeneratedMessage}. This class is package-private,
- * since outside users should probably be using {@link DynamicMessage}.
+ * A class which represents an arbitrary set of fields of some message type. This is used to
+ * implement {@link DynamicMessage}, and also to represent extensions in {@link GeneratedMessage}.
+ * This class is package-private, since outside users should probably be using {@link
+ * DynamicMessage}.
*
* @author kenton@google.com Kenton Varda
*/
-final class FieldSet<FieldDescriptorType extends
- FieldSet.FieldDescriptorLite<FieldDescriptorType>> {
+final class FieldSet<
+ FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>> {
/**
- * Interface for a FieldDescriptor or lite extension descriptor. This
- * prevents FieldSet from depending on {@link Descriptors.FieldDescriptor}.
+ * Interface for a FieldDescriptor or lite extension descriptor. This prevents FieldSet from
+ * depending on {@link Descriptors.FieldDescriptor}.
*/
- public interface FieldDescriptorLite<T extends FieldDescriptorLite<T>>
- extends Comparable<T> {
+ public interface FieldDescriptorLite<T extends FieldDescriptorLite<T>> extends Comparable<T> {
int getNumber();
+
WireFormat.FieldType getLiteType();
+
WireFormat.JavaType getLiteJavaType();
+
boolean isRepeated();
+
boolean isPacked();
+
Internal.EnumLiteMap<?> getEnumType();
// If getLiteJavaType() == MESSAGE, this merges a message object of the
// type into a builder of the type. Returns {@code to}.
- MessageLite.Builder internalMergeFrom(
- MessageLite.Builder to, MessageLite from);
+ MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from);
}
private final SmallSortedMap<FieldDescriptorType, Object> fields;
@@ -78,27 +81,23 @@ final class FieldSet<FieldDescriptorType extends
this.fields = SmallSortedMap.newFieldMap(16);
}
- /**
- * Construct an empty FieldSet. This is only used to initialize
- * DEFAULT_INSTANCE.
- */
+ /** Construct an empty FieldSet. This is only used to initialize DEFAULT_INSTANCE. */
private FieldSet(final boolean dummy) {
this.fields = SmallSortedMap.newFieldMap(0);
makeImmutable();
}
/** Construct a new FieldSet. */
- public static <T extends FieldSet.FieldDescriptorLite<T>>
- FieldSet<T> newFieldSet() {
+ public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> newFieldSet() {
return new FieldSet<T>();
}
/** Get an immutable empty FieldSet. */
@SuppressWarnings("unchecked")
- public static <T extends FieldSet.FieldDescriptorLite<T>>
- FieldSet<T> emptySet() {
+ public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> emptySet() {
return DEFAULT_INSTANCE;
}
+
@SuppressWarnings("rawtypes")
private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true);
@@ -118,8 +117,8 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Returns whether the FieldSet is immutable. This is true if it is the
- * {@link #emptySet} or if {@link #makeImmutable} were called.
+ * Returns whether the FieldSet is immutable. This is true if it is the {@link #emptySet} or if
+ * {@link #makeImmutable} were called.
*
* @return whether the FieldSet is immutable.
*/
@@ -147,8 +146,8 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Clones the FieldSet. The returned FieldSet will be mutable even if the
- * original FieldSet was immutable.
+ * Clones the FieldSet. The returned FieldSet will be mutable even if the original FieldSet was
+ * immutable.
*
* @return the newly cloned FieldSet
*/
@@ -162,8 +161,7 @@ final class FieldSet<FieldDescriptorType extends
FieldDescriptorType descriptor = entry.getKey();
clone.setField(descriptor, entry.getValue());
}
- for (Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
FieldDescriptorType descriptor = entry.getKey();
clone.setField(descriptor, entry.getValue());
}
@@ -180,18 +178,14 @@ final class FieldSet<FieldDescriptorType extends
hasLazyField = false;
}
- /**
- * Get a simple map containing all the fields.
- */
+ /** Get a simple map containing all the fields. */
public Map<FieldDescriptorType, Object> getAllFields() {
if (hasLazyField) {
- SmallSortedMap<FieldDescriptorType, Object> result =
- SmallSortedMap.newFieldMap(16);
+ SmallSortedMap<FieldDescriptorType, Object> result = SmallSortedMap.newFieldMap(16);
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
cloneFieldEntry(result, fields.getArrayEntryAt(i));
}
- for (Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
cloneFieldEntry(result, entry);
}
if (fields.isImmutable()) {
@@ -202,8 +196,8 @@ final class FieldSet<FieldDescriptorType extends
return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields);
}
- private void cloneFieldEntry(Map<FieldDescriptorType, Object> map,
- Map.Entry<FieldDescriptorType, Object> entry) {
+ private void cloneFieldEntry(
+ Map<FieldDescriptorType, Object> map, Map.Entry<FieldDescriptorType, Object> entry) {
FieldDescriptorType key = entry.getKey();
Object value = entry.getValue();
if (value instanceof LazyField) {
@@ -214,37 +208,30 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Get an iterator to the field map. This iterator should not be leaked out
- * of the protobuf library as it is not protected from mutation when fields
- * is not immutable.
+ * Get an iterator to the field map. This iterator should not be leaked out of the protobuf
+ * library as it is not protected from mutation when fields is not immutable.
*/
public Iterator<Map.Entry<FieldDescriptorType, Object>> iterator() {
if (hasLazyField) {
- return new LazyIterator<FieldDescriptorType>(
- fields.entrySet().iterator());
+ return new LazyIterator<FieldDescriptorType>(fields.entrySet().iterator());
}
return fields.entrySet().iterator();
}
- /**
- * Useful for implementing
- * {@link Message#hasField(Descriptors.FieldDescriptor)}.
- */
+ /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */
public boolean hasField(final FieldDescriptorType descriptor) {
if (descriptor.isRepeated()) {
- throw new IllegalArgumentException(
- "hasField() can only be called on non-repeated fields.");
+ throw new IllegalArgumentException("hasField() can only be called on non-repeated fields.");
}
return fields.get(descriptor) != null;
}
/**
- * Useful for implementing
- * {@link Message#getField(Descriptors.FieldDescriptor)}. This method
- * returns {@code null} if the field is not set; in this case it is up
- * to the caller to fetch the field's default value.
+ * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method
+ * returns {@code null} if the field is not set; in this case it is up to the caller to fetch the
+ * field's default value.
*/
public Object getField(final FieldDescriptorType descriptor) {
Object o = fields.get(descriptor);
@@ -255,16 +242,14 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Useful for implementing
- * {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}.
+ * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
- public void setField(final FieldDescriptorType descriptor,
- Object value) {
+ public void setField(final FieldDescriptorType descriptor, Object value) {
if (descriptor.isRepeated()) {
if (!(value instanceof List)) {
throw new IllegalArgumentException(
- "Wrong object type used with protocol message reflection.");
+ "Wrong object type used with protocol message reflection.");
}
// Wrap the contents in a new list so that the caller cannot change
@@ -285,10 +270,7 @@ final class FieldSet<FieldDescriptorType extends
fields.put(descriptor, value);
}
- /**
- * Useful for implementing
- * {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}.
- */
+ /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */
public void clearField(final FieldDescriptorType descriptor) {
fields.remove(descriptor);
if (fields.isEmpty()) {
@@ -296,14 +278,11 @@ final class FieldSet<FieldDescriptorType extends
}
}
- /**
- * Useful for implementing
- * {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}.
- */
+ /** Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */
public int getRepeatedFieldCount(final FieldDescriptorType descriptor) {
if (!descriptor.isRepeated()) {
throw new IllegalArgumentException(
- "getRepeatedField() can only be called on repeated fields.");
+ "getRepeatedField() can only be called on repeated fields.");
}
final Object value = getField(descriptor);
@@ -314,15 +293,11 @@ final class FieldSet<FieldDescriptorType extends
}
}
- /**
- * Useful for implementing
- * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}.
- */
- public Object getRepeatedField(final FieldDescriptorType descriptor,
- final int index) {
+ /** Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. */
+ public Object getRepeatedField(final FieldDescriptorType descriptor, final int index) {
if (!descriptor.isRepeated()) {
throw new IllegalArgumentException(
- "getRepeatedField() can only be called on repeated fields.");
+ "getRepeatedField() can only be called on repeated fields.");
}
final Object value = getField(descriptor);
@@ -335,16 +310,15 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Useful for implementing
- * {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}.
+ * Useful for implementing {@link
+ * Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}.
*/
@SuppressWarnings("unchecked")
- public void setRepeatedField(final FieldDescriptorType descriptor,
- final int index,
- final Object value) {
+ public void setRepeatedField(
+ final FieldDescriptorType descriptor, final int index, final Object value) {
if (!descriptor.isRepeated()) {
throw new IllegalArgumentException(
- "getRepeatedField() can only be called on repeated fields.");
+ "getRepeatedField() can only be called on repeated fields.");
}
final Object list = getField(descriptor);
@@ -357,15 +331,14 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Useful for implementing
- * {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}.
+ * Useful for implementing {@link
+ * Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}.
*/
@SuppressWarnings("unchecked")
- public void addRepeatedField(final FieldDescriptorType descriptor,
- final Object value) {
+ public void addRepeatedField(final FieldDescriptorType descriptor, final Object value) {
if (!descriptor.isRepeated()) {
throw new IllegalArgumentException(
- "addRepeatedField() can only be called on repeated fields.");
+ "addRepeatedField() can only be called on repeated fields.");
}
verifyType(descriptor.getLiteType(), value);
@@ -383,36 +356,45 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Verifies that the given object is of the correct type to be a valid
- * value for the given field. (For repeated fields, this checks if the
- * object is the right type to be one element of the field.)
+ * Verifies that the given object is of the correct type to be a valid value for the given field.
+ * (For repeated fields, this checks if the object is the right type to be one element of the
+ * field.)
*
* @throws IllegalArgumentException The value is not of the right type.
*/
- private static void verifyType(final WireFormat.FieldType type,
- final Object value) {
+ private static void verifyType(final WireFormat.FieldType type, final Object value) {
checkNotNull(value);
boolean isValid = false;
switch (type.getJavaType()) {
- case INT: isValid = value instanceof Integer ; break;
- case LONG: isValid = value instanceof Long ; break;
- case FLOAT: isValid = value instanceof Float ; break;
- case DOUBLE: isValid = value instanceof Double ; break;
- case BOOLEAN: isValid = value instanceof Boolean ; break;
- case STRING: isValid = value instanceof String ; break;
+ case INT:
+ isValid = value instanceof Integer;
+ break;
+ case LONG:
+ isValid = value instanceof Long;
+ break;
+ case FLOAT:
+ isValid = value instanceof Float;
+ break;
+ case DOUBLE:
+ isValid = value instanceof Double;
+ break;
+ case BOOLEAN:
+ isValid = value instanceof Boolean;
+ break;
+ case STRING:
+ isValid = value instanceof String;
+ break;
case BYTE_STRING:
isValid = value instanceof ByteString || value instanceof byte[];
break;
case ENUM:
// TODO(kenton): Caller must do type checking here, I guess.
- isValid =
- (value instanceof Integer || value instanceof Internal.EnumLite);
+ isValid = (value instanceof Integer || value instanceof Internal.EnumLite);
break;
case MESSAGE:
// TODO(kenton): Caller must do type checking here, I guess.
- isValid =
- (value instanceof MessageLite) || (value instanceof LazyField);
+ isValid = (value instanceof MessageLite) || (value instanceof LazyField);
break;
}
@@ -425,7 +407,7 @@ final class FieldSet<FieldDescriptorType extends
// isn't a big deal, though, since it would only really apply when using
// reflection and generally people don't chain reflection setters.
throw new IllegalArgumentException(
- "Wrong object type used with protocol message reflection.");
+ "Wrong object type used with protocol message reflection.");
}
}
@@ -433,10 +415,9 @@ final class FieldSet<FieldDescriptorType extends
// Parsing and serialization
/**
- * See {@link Message#isInitialized()}. Note: Since {@code FieldSet}
- * itself does not have any way of knowing about required fields that
- * aren't actually present in the set, it is up to the caller to check
- * that all required fields are present.
+ * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any way
+ * of knowing about required fields that aren't actually present in the set, it is up to the
+ * caller to check that all required fields are present.
*/
public boolean isInitialized() {
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
@@ -444,8 +425,7 @@ final class FieldSet<FieldDescriptorType extends
return false;
}
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
if (!isInitialized(entry)) {
return false;
}
@@ -454,13 +434,11 @@ final class FieldSet<FieldDescriptorType extends
}
@SuppressWarnings("unchecked")
- private boolean isInitialized(
- final Map.Entry<FieldDescriptorType, Object> entry) {
+ private boolean isInitialized(final Map.Entry<FieldDescriptorType, Object> entry) {
final FieldDescriptorType descriptor = entry.getKey();
if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) {
if (descriptor.isRepeated()) {
- for (final MessageLite element:
- (List<MessageLite>) entry.getValue()) {
+ for (final MessageLite element : (List<MessageLite>) entry.getValue()) {
if (!element.isInitialized()) {
return false;
}
@@ -485,11 +463,9 @@ final class FieldSet<FieldDescriptorType extends
/**
* Given a field type, return the wire type.
*
- * @returns One of the {@code WIRETYPE_} constants defined in
- * {@link WireFormat}.
+ * @return One of the {@code WIRETYPE_} constants defined in {@link WireFormat}.
*/
- static int getWireFormatForFieldType(final WireFormat.FieldType type,
- boolean isPacked) {
+ static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) {
if (isPacked) {
return WireFormat.WIRETYPE_LENGTH_DELIMITED;
} else {
@@ -497,16 +473,12 @@ final class FieldSet<FieldDescriptorType extends
}
}
- /**
- * Like {@link Message.Builder#mergeFrom(Message)}, but merges from another
- * {@link FieldSet}.
- */
+ /** Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. */
public void mergeFrom(final FieldSet<FieldDescriptorType> other) {
for (int i = 0; i < other.fields.getNumArrayEntries(); i++) {
mergeFromField(other.fields.getArrayEntryAt(i));
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- other.fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : other.fields.getOverflowEntries()) {
mergeFromField(entry);
}
}
@@ -523,8 +495,7 @@ final class FieldSet<FieldDescriptorType extends
}
@SuppressWarnings({"unchecked", "rawtypes"})
- private void mergeFromField(
- final Map.Entry<FieldDescriptorType, Object> entry) {
+ private void mergeFromField(final Map.Entry<FieldDescriptorType, Object> entry) {
final FieldDescriptorType descriptor = entry.getKey();
Object otherValue = entry.getValue();
if (otherValue instanceof LazyField) {
@@ -546,9 +517,10 @@ final class FieldSet<FieldDescriptorType extends
fields.put(descriptor, cloneIfMutable(otherValue));
} else {
// Merge the messages.
- value = descriptor.internalMergeFrom(
- ((MessageLite) value).toBuilder(), (MessageLite) otherValue)
- .build();
+ value =
+ descriptor
+ .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue)
+ .build();
fields.put(descriptor, value);
}
@@ -561,72 +533,59 @@ final class FieldSet<FieldDescriptorType extends
// other class. Probably WireFormat.
/**
- * Read a field of any primitive type for immutable messages from a
- * CodedInputStream. Enums, groups, and embedded messages are not handled by
- * this method.
+ * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums,
+ * groups, and embedded messages are not handled by this method.
*
* @param input The stream from which to read.
* @param type Declared type of the field.
* @param checkUtf8 When true, check that the input is valid utf8.
- * @return An object representing the field's value, of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @return An object representing the field's value, of the exact type which would be returned by
+ * {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
public static Object readPrimitiveField(
- CodedInputStream input,
- final WireFormat.FieldType type,
- boolean checkUtf8) throws IOException {
+ CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8)
+ throws IOException {
if (checkUtf8) {
- return WireFormat.readPrimitiveField(input, type,
- WireFormat.Utf8Validation.STRICT);
+ return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.STRICT);
} else {
- return WireFormat.readPrimitiveField(input, type,
- WireFormat.Utf8Validation.LOOSE);
+ return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.LOOSE);
}
}
/** See {@link Message#writeTo(CodedOutputStream)}. */
- public void writeTo(final CodedOutputStream output)
- throws IOException {
+ public void writeTo(final CodedOutputStream output) throws IOException {
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
- final Map.Entry<FieldDescriptorType, Object> entry =
- fields.getArrayEntryAt(i);
+ final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i);
writeField(entry.getKey(), entry.getValue(), output);
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
writeField(entry.getKey(), entry.getValue(), output);
}
}
- /**
- * Like {@link #writeTo} but uses MessageSet wire format.
- */
- public void writeMessageSetTo(final CodedOutputStream output)
- throws IOException {
+ /** Like {@link #writeTo} but uses MessageSet wire format. */
+ public void writeMessageSetTo(final CodedOutputStream output) throws IOException {
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
writeMessageSetTo(fields.getArrayEntryAt(i), output);
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
writeMessageSetTo(entry, output);
}
}
private void writeMessageSetTo(
- final Map.Entry<FieldDescriptorType, Object> entry,
- final CodedOutputStream output) throws IOException {
+ final Map.Entry<FieldDescriptorType, Object> entry, final CodedOutputStream output)
+ throws IOException {
final FieldDescriptorType descriptor = entry.getKey();
- if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE &&
- !descriptor.isRepeated() && !descriptor.isPacked()) {
+ if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE
+ && !descriptor.isRepeated()
+ && !descriptor.isPacked()) {
Object value = entry.getValue();
if (value instanceof LazyField) {
value = ((LazyField) value).getValue();
}
- output.writeMessageSetExtension(entry.getKey().getNumber(),
- (MessageLite) value);
+ output.writeMessageSetExtension(entry.getKey().getNumber(), (MessageLite) value);
} else {
writeField(descriptor, entry.getValue(), output);
}
@@ -636,18 +595,17 @@ final class FieldSet<FieldDescriptorType extends
* Write a single tag-value pair to the stream.
*
* @param output The output stream.
- * @param type The field's type.
+ * @param type The field's type.
* @param number The field's number.
- * @param value Object representing the field's value. Must be of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @param value Object representing the field's value. Must be of the exact type which would be
+ * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
static void writeElement(
final CodedOutputStream output,
final WireFormat.FieldType type,
final int number,
- final Object value) throws IOException {
+ final Object value)
+ throws IOException {
// Special case for groups, which need a start and end tag; other fields
// can just use writeTag() and writeFieldNoTag().
if (type == WireFormat.FieldType.GROUP) {
@@ -663,26 +621,43 @@ final class FieldSet<FieldDescriptorType extends
*
* @param output The output stream.
* @param type The field's type.
- * @param value Object representing the field's value. Must be of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @param value Object representing the field's value. Must be of the exact type which would be
+ * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
static void writeElementNoTag(
- final CodedOutputStream output,
- final WireFormat.FieldType type,
- final Object value) throws IOException {
+ final CodedOutputStream output, final WireFormat.FieldType type, final Object value)
+ throws IOException {
switch (type) {
- case DOUBLE : output.writeDoubleNoTag ((Double ) value); break;
- case FLOAT : output.writeFloatNoTag ((Float ) value); break;
- case INT64 : output.writeInt64NoTag ((Long ) value); break;
- case UINT64 : output.writeUInt64NoTag ((Long ) value); break;
- case INT32 : output.writeInt32NoTag ((Integer ) value); break;
- case FIXED64 : output.writeFixed64NoTag ((Long ) value); break;
- case FIXED32 : output.writeFixed32NoTag ((Integer ) value); break;
- case BOOL : output.writeBoolNoTag ((Boolean ) value); break;
- case GROUP : output.writeGroupNoTag ((MessageLite) value); break;
- case MESSAGE : output.writeMessageNoTag ((MessageLite) value); break;
+ case DOUBLE:
+ output.writeDoubleNoTag((Double) value);
+ break;
+ case FLOAT:
+ output.writeFloatNoTag((Float) value);
+ break;
+ case INT64:
+ output.writeInt64NoTag((Long) value);
+ break;
+ case UINT64:
+ output.writeUInt64NoTag((Long) value);
+ break;
+ case INT32:
+ output.writeInt32NoTag((Integer) value);
+ break;
+ case FIXED64:
+ output.writeFixed64NoTag((Long) value);
+ break;
+ case FIXED32:
+ output.writeFixed32NoTag((Integer) value);
+ break;
+ case BOOL:
+ output.writeBoolNoTag((Boolean) value);
+ break;
+ case GROUP:
+ output.writeGroupNoTag((MessageLite) value);
+ break;
+ case MESSAGE:
+ output.writeMessageNoTag((MessageLite) value);
+ break;
case STRING:
if (value instanceof ByteString) {
output.writeBytesNoTag((ByteString) value);
@@ -697,11 +672,21 @@ final class FieldSet<FieldDescriptorType extends
output.writeByteArrayNoTag((byte[]) value);
}
break;
- case UINT32 : output.writeUInt32NoTag ((Integer ) value); break;
- case SFIXED32: output.writeSFixed32NoTag((Integer ) value); break;
- case SFIXED64: output.writeSFixed64NoTag((Long ) value); break;
- case SINT32 : output.writeSInt32NoTag ((Integer ) value); break;
- case SINT64 : output.writeSInt64NoTag ((Long ) value); break;
+ case UINT32:
+ output.writeUInt32NoTag((Integer) value);
+ break;
+ case SFIXED32:
+ output.writeSFixed32NoTag((Integer) value);
+ break;
+ case SFIXED64:
+ output.writeSFixed64NoTag((Long) value);
+ break;
+ case SINT32:
+ output.writeSInt32NoTag((Integer) value);
+ break;
+ case SINT64:
+ output.writeSInt64NoTag((Long) value);
+ break;
case ENUM:
if (value instanceof Internal.EnumLite) {
@@ -714,14 +699,13 @@ final class FieldSet<FieldDescriptorType extends
}
/** Write a single field. */
- public static void writeField(final FieldDescriptorLite<?> descriptor,
- final Object value,
- final CodedOutputStream output)
- throws IOException {
+ public static void writeField(
+ final FieldDescriptorLite<?> descriptor, final Object value, final CodedOutputStream output)
+ throws IOException {
WireFormat.FieldType type = descriptor.getLiteType();
int number = descriptor.getNumber();
if (descriptor.isRepeated()) {
- final List<?> valueList = (List<?>)value;
+ final List<?> valueList = (List<?>) value;
if (descriptor.isPacked()) {
output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED);
// Compute the total data size so the length can be written.
@@ -749,44 +733,39 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * See {@link Message#getSerializedSize()}. It's up to the caller to cache
- * the resulting size if desired.
+ * See {@link Message#getSerializedSize()}. It's up to the caller to cache the resulting size if
+ * desired.
*/
public int getSerializedSize() {
int size = 0;
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
- final Map.Entry<FieldDescriptorType, Object> entry =
- fields.getArrayEntryAt(i);
+ final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i);
size += computeFieldSize(entry.getKey(), entry.getValue());
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
size += computeFieldSize(entry.getKey(), entry.getValue());
}
return size;
}
- /**
- * Like {@link #getSerializedSize} but uses MessageSet wire format.
- */
+ /** Like {@link #getSerializedSize} but uses MessageSet wire format. */
public int getMessageSetSerializedSize() {
int size = 0;
for (int i = 0; i < fields.getNumArrayEntries(); i++) {
size += getMessageSetSerializedSize(fields.getArrayEntryAt(i));
}
- for (final Map.Entry<FieldDescriptorType, Object> entry :
- fields.getOverflowEntries()) {
+ for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) {
size += getMessageSetSerializedSize(entry);
}
return size;
}
- private int getMessageSetSerializedSize(
- final Map.Entry<FieldDescriptorType, Object> entry) {
+ private int getMessageSetSerializedSize(final Map.Entry<FieldDescriptorType, Object> entry) {
final FieldDescriptorType descriptor = entry.getKey();
Object value = entry.getValue();
if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE
- && !descriptor.isRepeated() && !descriptor.isPacked()) {
+ && !descriptor.isRepeated()
+ && !descriptor.isPacked()) {
if (value instanceof LazyField) {
return CodedOutputStream.computeLazyFieldMessageSetExtensionSize(
entry.getKey().getNumber(), (LazyField) value);
@@ -800,15 +779,13 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Compute the number of bytes that would be needed to encode a
- * single tag/value pair of arbitrary type.
+ * Compute the number of bytes that would be needed to encode a single tag/value pair of arbitrary
+ * type.
*
- * @param type The field's type.
+ * @param type The field's type.
* @param number The field's number.
- * @param value Object representing the field's value. Must be of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @param value Object representing the field's value. Must be of the exact type which would be
+ * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
static int computeElementSize(
final WireFormat.FieldType type, final int number, final Object value) {
@@ -822,46 +799,57 @@ final class FieldSet<FieldDescriptorType extends
}
/**
- * Compute the number of bytes that would be needed to encode a
- * particular value of arbitrary type, excluding tag.
+ * Compute the number of bytes that would be needed to encode a particular value of arbitrary
+ * type, excluding tag.
*
- * @param type The field's type.
- * @param value Object representing the field's value. Must be of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @param type The field's type.
+ * @param value Object representing the field's value. Must be of the exact type which would be
+ * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
- static int computeElementSizeNoTag(
- final WireFormat.FieldType type, final Object value) {
+ static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) {
switch (type) {
- // Note: Minor violation of 80-char limit rule here because this would
- // actually be harder to read if we wrapped the lines.
- case DOUBLE : return CodedOutputStream.computeDoubleSizeNoTag ((Double )value);
- case FLOAT : return CodedOutputStream.computeFloatSizeNoTag ((Float )value);
- case INT64 : return CodedOutputStream.computeInt64SizeNoTag ((Long )value);
- case UINT64 : return CodedOutputStream.computeUInt64SizeNoTag ((Long )value);
- case INT32 : return CodedOutputStream.computeInt32SizeNoTag ((Integer )value);
- case FIXED64 : return CodedOutputStream.computeFixed64SizeNoTag ((Long )value);
- case FIXED32 : return CodedOutputStream.computeFixed32SizeNoTag ((Integer )value);
- case BOOL : return CodedOutputStream.computeBoolSizeNoTag ((Boolean )value);
- case GROUP : return CodedOutputStream.computeGroupSizeNoTag ((MessageLite)value);
- case BYTES :
+ // Note: Minor violation of 80-char limit rule here because this would
+ // actually be harder to read if we wrapped the lines.
+ case DOUBLE:
+ return CodedOutputStream.computeDoubleSizeNoTag((Double) value);
+ case FLOAT:
+ return CodedOutputStream.computeFloatSizeNoTag((Float) value);
+ case INT64:
+ return CodedOutputStream.computeInt64SizeNoTag((Long) value);
+ case UINT64:
+ return CodedOutputStream.computeUInt64SizeNoTag((Long) value);
+ case INT32:
+ return CodedOutputStream.computeInt32SizeNoTag((Integer) value);
+ case FIXED64:
+ return CodedOutputStream.computeFixed64SizeNoTag((Long) value);
+ case FIXED32:
+ return CodedOutputStream.computeFixed32SizeNoTag((Integer) value);
+ case BOOL:
+ return CodedOutputStream.computeBoolSizeNoTag((Boolean) value);
+ case GROUP:
+ return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value);
+ case BYTES:
if (value instanceof ByteString) {
return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
} else {
return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value);
}
- case STRING :
+ case STRING:
if (value instanceof ByteString) {
return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
} else {
return CodedOutputStream.computeStringSizeNoTag((String) value);
}
- case UINT32 : return CodedOutputStream.computeUInt32SizeNoTag ((Integer )value);
- case SFIXED32: return CodedOutputStream.computeSFixed32SizeNoTag((Integer )value);
- case SFIXED64: return CodedOutputStream.computeSFixed64SizeNoTag((Long )value);
- case SINT32 : return CodedOutputStream.computeSInt32SizeNoTag ((Integer )value);
- case SINT64 : return CodedOutputStream.computeSInt64SizeNoTag ((Long )value);
+ case UINT32:
+ return CodedOutputStream.computeUInt32SizeNoTag((Integer) value);
+ case SFIXED32:
+ return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value);
+ case SFIXED64:
+ return CodedOutputStream.computeSFixed64SizeNoTag((Long) value);
+ case SINT32:
+ return CodedOutputStream.computeSInt32SizeNoTag((Integer) value);
+ case SINT64:
+ return CodedOutputStream.computeSInt64SizeNoTag((Long) value);
case MESSAGE:
if (value instanceof LazyField) {
@@ -872,36 +860,31 @@ final class FieldSet<FieldDescriptorType extends
case ENUM:
if (value instanceof Internal.EnumLite) {
- return CodedOutputStream.computeEnumSizeNoTag(
- ((Internal.EnumLite) value).getNumber());
+ return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber());
} else {
return CodedOutputStream.computeEnumSizeNoTag((Integer) value);
}
}
- throw new RuntimeException(
- "There is no way to get here, but the compiler thinks otherwise.");
+ throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
}
- /**
- * Compute the number of bytes needed to encode a particular field.
- */
- public static int computeFieldSize(final FieldDescriptorLite<?> descriptor,
- final Object value) {
+ /** Compute the number of bytes needed to encode a particular field. */
+ public static int computeFieldSize(final FieldDescriptorLite<?> descriptor, final Object value) {
WireFormat.FieldType type = descriptor.getLiteType();
int number = descriptor.getNumber();
if (descriptor.isRepeated()) {
if (descriptor.isPacked()) {
int dataSize = 0;
- for (final Object element : (List<?>)value) {
+ for (final Object element : (List<?>) value) {
dataSize += computeElementSizeNoTag(type, element);
}
- return dataSize +
- CodedOutputStream.computeTagSize(number) +
- CodedOutputStream.computeRawVarint32Size(dataSize);
+ return dataSize
+ + CodedOutputStream.computeTagSize(number)
+ + CodedOutputStream.computeRawVarint32Size(dataSize);
} else {
int size = 0;
- for (final Object element : (List<?>)value) {
+ for (final Object element : (List<?>) value) {
size += computeElementSize(type, number, element);
}
return size;
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 7c080af3..85e09bec 100644
--- a/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/FloatArrayList.java
@@ -46,6 +46,7 @@ final class FloatArrayList extends AbstractProtobufList<Float>
implements FloatList, RandomAccess, PrimitiveNonBoxingCollection {
private static final FloatArrayList EMPTY_LIST = new FloatArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
@@ -54,9 +55,7 @@ final class FloatArrayList extends AbstractProtobufList<Float>
return EMPTY_LIST;
}
- /**
- * The backing store for the list.
- */
+ /** The backing store for the list. */
private float[] array;
/**
@@ -65,16 +64,13 @@ final class FloatArrayList extends AbstractProtobufList<Float>
*/
private int size;
- /**
- * Constructs a new mutable {@code FloatArrayList} with default capacity.
- */
+ /** Constructs a new mutable {@code FloatArrayList} with default capacity. */
FloatArrayList() {
this(new float[DEFAULT_CAPACITY], 0);
}
/**
- * Constructs a new mutable {@code FloatArrayList}
- * containing the same elements as {@code other}.
+ * Constructs a new mutable {@code FloatArrayList} containing the same elements as {@code other}.
*/
private FloatArrayList(float[] other, int size) {
array = other;
@@ -168,17 +164,13 @@ final class FloatArrayList extends AbstractProtobufList<Float>
addFloat(index, element);
}
- /**
- * Like {@link #add(Float)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Float)} but more efficient in that it doesn't box the element. */
@Override
public void addFloat(float element) {
addFloat(size, element);
}
- /**
- * Like {@link #add(int, Float)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(int, Float)} but more efficient in that it doesn't box the element. */
private void addFloat(int index, float element) {
ensureIsMutable();
if (index < 0 || index > size) {
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 df01547e..0034c58c 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageLite.java
@@ -33,7 +33,6 @@ package com.google.protobuf;
import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream;
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;
@@ -59,9 +58,9 @@ import java.util.concurrent.ConcurrentHashMap;
* @author kenton@google.com Kenton Varda
*/
public abstract class GeneratedMessageLite<
- MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
- BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
- extends AbstractMessageLite<MessageType, BuilderType> {
+ 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
@@ -72,7 +71,7 @@ public abstract class GeneratedMessageLite<
/** For use by generated code only. Lazily initialized to reduce allocations. */
protected UnknownFieldSetLite unknownFields = UnknownFieldSetLite.getDefaultInstance();
- /** For use by generated code only. */
+ /** For use by generated code only. */
protected int memoizedSerializedSize = -1;
@Override
@@ -98,11 +97,11 @@ public abstract class GeneratedMessageLite<
* binary size down. The first line of the {@code toString()} representation includes a commented
* version of {@code super.toString()} to act as an indicator that this should not be relied on
* for comparisons.
- * <p>
- * NOTE: This method relies on the field getter methods not being stripped or renamed by proguard.
- * If they are, the fields will not be included in the returned string representation.
- * <p>
- * NOTE: This implementation is liable to change in the future, and should not be relied on in
+ *
+ * <p>NOTE: This method relies on the field getter methods not being stripped or renamed by
+ * proguard. If they are, the fields will not be included in the returned string representation.
+ *
+ * <p>NOTE: This implementation is liable to change in the future, and should not be relied on in
* code.
*/
@Override
@@ -210,25 +209,19 @@ public abstract class GeneratedMessageLite<
return unknownFields.mergeFieldFrom(tag, input);
}
- /**
- * Called by subclasses to parse an unknown field. For use by generated code only.
- */
+ /** Called by subclasses to parse an unknown field. For use by generated code only. */
protected void mergeVarintField(int tag, int value) {
ensureUnknownFieldsInitialized();
unknownFields.mergeVarintField(tag, value);
}
- /**
- * Called by subclasses to parse an unknown field. For use by generated code only.
- */
+ /** Called by subclasses to parse an unknown field. For use by generated code only. */
protected void mergeLengthDelimitedField(int fieldNumber, ByteString value) {
ensureUnknownFieldsInitialized();
unknownFields.mergeLengthDelimitedField(fieldNumber, value);
}
- /**
- * Called by subclasses to complete parsing. For use by generated code only.
- */
+ /** Called by subclasses to complete parsing. For use by generated code only. */
protected void makeImmutable() {
// BEGIN REGULAR
dynamicMethod(MethodToInvoke.MAKE_IMMUTABLE);
@@ -240,16 +233,16 @@ public abstract class GeneratedMessageLite<
}
protected final <
- MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
- BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
- BuilderType createBuilder() {
+ 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) {
+ MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
+ BuilderType extends GeneratedMessageLite.Builder<MessageType, BuilderType>>
+ BuilderType createBuilder(MessageType prototype) {
return ((BuilderType) createBuilder()).mergeFrom(prototype);
}
@@ -269,8 +262,8 @@ public abstract class GeneratedMessageLite<
/**
* Defines which method path to invoke in {@link GeneratedMessageLite
* #dynamicMethod(MethodToInvoke, Object...)}.
- * <p>
- * For use by generated code only.
+ *
+ * <p>For use by generated code only.
*/
public static enum MethodToInvoke {
// BEGIN REGULAR
@@ -322,16 +315,12 @@ public abstract class GeneratedMessageLite<
*/
protected abstract Object dynamicMethod(MethodToInvoke method, Object arg0, Object arg1);
- /**
- * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding.
- */
+ /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */
protected Object dynamicMethod(MethodToInvoke method, Object arg0) {
return dynamicMethod(method, arg0, null);
}
- /**
- * Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding.
- */
+ /** Same as {@link #dynamicMethod(MethodToInvoke, Object, Object)} with {@code null} padding. */
protected Object dynamicMethod(MethodToInvoke method) {
return dynamicMethod(method, null, null);
}
@@ -366,9 +355,9 @@ public abstract class GeneratedMessageLite<
@SuppressWarnings("unchecked")
public abstract static class Builder<
- MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
- BuilderType extends Builder<MessageType, BuilderType>>
- extends AbstractMessageLite.Builder<MessageType, BuilderType> {
+ MessageType extends GeneratedMessageLite<MessageType, BuilderType>,
+ BuilderType extends Builder<MessageType, BuilderType>>
+ extends AbstractMessageLite.Builder<MessageType, BuilderType> {
private final MessageType defaultInstance;
protected MessageType instance;
@@ -382,8 +371,8 @@ public abstract class GeneratedMessageLite<
}
/**
- * Called before any method that would mutate the builder to ensure that it correctly copies
- * any state before the write happens to preserve immutability guarantees.
+ * Called before any method that would mutate the builder to ensure that it correctly copies any
+ * state before the write happens to preserve immutability guarantees.
*/
protected void copyOnWrite() {
if (isBuilt) {
@@ -397,7 +386,7 @@ public abstract class GeneratedMessageLite<
@Override
public final boolean isInitialized() {
- return GeneratedMessageLite.isInitialized(instance, false /* shouldMemoize */);
+ return GeneratedMessageLite.isInitialized(instance, /* shouldMemoize= */ false);
}
@Override
@@ -409,8 +398,7 @@ public abstract class GeneratedMessageLite<
@Override
public BuilderType clone() {
- BuilderType builder =
- (BuilderType) getDefaultInstanceForType().newBuilderForType();
+ BuilderType builder = (BuilderType) getDefaultInstanceForType().newBuilderForType();
builder.mergeFrom(buildPartial());
return builder;
}
@@ -512,39 +500,31 @@ public abstract class GeneratedMessageLite<
// =================================================================
// Extensions-related stuff
- /**
- * Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}.
- */
+ /** Lite equivalent of {@link com.google.protobuf.GeneratedMessage.ExtendableMessageOrBuilder}. */
public interface ExtendableMessageOrBuilder<
- MessageType extends ExtendableMessage<MessageType, BuilderType>,
- BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
- extends MessageLiteOrBuilder {
+ MessageType extends ExtendableMessage<MessageType, BuilderType>,
+ BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
+ extends MessageLiteOrBuilder {
/** Check if a singular extension is present. */
- <Type> boolean hasExtension(
- ExtensionLite<MessageType, Type> extension);
+ <Type> boolean hasExtension(ExtensionLite<MessageType, Type> extension);
/** Get the number of elements in a repeated extension. */
- <Type> int getExtensionCount(
- ExtensionLite<MessageType, List<Type>> extension);
+ <Type> int getExtensionCount(ExtensionLite<MessageType, List<Type>> extension);
/** Get the value of an extension. */
<Type> Type getExtension(ExtensionLite<MessageType, Type> extension);
/** Get one element of a repeated extension. */
- <Type> Type getExtension(
- ExtensionLite<MessageType, List<Type>> extension,
- int index);
+ <Type> Type getExtension(ExtensionLite<MessageType, List<Type>> extension, int index);
}
- /**
- * Lite equivalent of {@link GeneratedMessage.ExtendableMessage}.
- */
+ /** Lite equivalent of {@link GeneratedMessage.ExtendableMessage}. */
public abstract static class ExtendableMessage<
- MessageType extends ExtendableMessage<MessageType, BuilderType>,
- BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
- extends GeneratedMessageLite<MessageType, BuilderType>
- implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
+ MessageType extends ExtendableMessage<MessageType, BuilderType>,
+ BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
+ extends GeneratedMessageLite<MessageType, BuilderType>
+ implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
/** Represents the set of extensions on this message. For use by generated code only. */
protected FieldSet<ExtensionDescriptor> extensions = FieldSet.emptySet();
@@ -582,8 +562,8 @@ public abstract class GeneratedMessageLite<
// TODO(dweis): How much bytecode would be saved by not requiring the generated code to
// provide the default instance?
- GeneratedExtension<MessageType, ?> extension = extensionRegistry.findLiteExtensionByNumber(
- defaultInstance, fieldNumber);
+ GeneratedExtension<MessageType, ?> extension =
+ extensionRegistry.findLiteExtensionByNumber(defaultInstance, fieldNumber);
return parseExtension(input, extensionRegistry, extension, tag, fieldNumber);
}
@@ -599,22 +579,22 @@ public abstract class GeneratedMessageLite<
boolean unknown = false;
boolean packed = false;
if (extension == null) {
- unknown = true; // Unknown field.
- } else if (wireType == FieldSet.getWireFormatForFieldType(
- extension.descriptor.getLiteType(),
- false /* isPacked */)) {
- packed = false; // Normal, unpacked value.
- } else if (extension.descriptor.isRepeated &&
- extension.descriptor.type.isPackable() &&
- wireType == FieldSet.getWireFormatForFieldType(
- extension.descriptor.getLiteType(),
- true /* isPacked */)) {
- packed = true; // Packed value.
+ unknown = true; // Unknown field.
+ } else if (wireType
+ == FieldSet.getWireFormatForFieldType(
+ extension.descriptor.getLiteType(), /* isPacked= */ false)) {
+ packed = false; // Normal, unpacked value.
+ } else if (extension.descriptor.isRepeated
+ && extension.descriptor.type.isPackable()
+ && wireType
+ == FieldSet.getWireFormatForFieldType(
+ extension.descriptor.getLiteType(), /* isPacked= */ true)) {
+ packed = true; // Packed value.
} else {
- unknown = true; // Wrong wire type.
+ unknown = true; // Wrong wire type.
}
- if (unknown) { // Unknown field or wrong wire type. Skip.
+ if (unknown) { // Unknown field or wrong wire type. Skip.
return parseUnknownField(tag, input);
}
@@ -626,22 +606,20 @@ public abstract class GeneratedMessageLite<
if (extension.descriptor.getLiteType() == WireFormat.FieldType.ENUM) {
while (input.getBytesUntilLimit() > 0) {
int rawValue = input.readEnum();
- Object value =
- extension.descriptor.getEnumType().findValueByNumber(rawValue);
+ Object value = extension.descriptor.getEnumType().findValueByNumber(rawValue);
if (value == null) {
// If the number isn't recognized as a valid value for this
// enum, drop it (don't even add it to unknownFields).
return true;
}
- extensions.addRepeatedField(extension.descriptor,
- extension.singularToFieldSetType(value));
+ extensions.addRepeatedField(
+ extension.descriptor, extension.singularToFieldSetType(value));
}
} else {
while (input.getBytesUntilLimit() > 0) {
Object value =
- FieldSet.readPrimitiveField(input,
- extension.descriptor.getLiteType(),
- /*checkUtf8=*/ false);
+ FieldSet.readPrimitiveField(
+ input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false);
extensions.addRepeatedField(extension.descriptor, value);
}
}
@@ -649,33 +627,29 @@ public abstract class GeneratedMessageLite<
} else {
Object value;
switch (extension.descriptor.getLiteJavaType()) {
- case MESSAGE: {
- MessageLite.Builder subBuilder = null;
- if (!extension.descriptor.isRepeated()) {
- MessageLite existingValue =
- (MessageLite) extensions.getField(extension.descriptor);
- if (existingValue != null) {
- subBuilder = existingValue.toBuilder();
+ case MESSAGE:
+ {
+ MessageLite.Builder subBuilder = null;
+ if (!extension.descriptor.isRepeated()) {
+ MessageLite existingValue = (MessageLite) extensions.getField(extension.descriptor);
+ if (existingValue != null) {
+ subBuilder = existingValue.toBuilder();
+ }
}
+ if (subBuilder == null) {
+ subBuilder = extension.getMessageDefaultInstance().newBuilderForType();
+ }
+ if (extension.descriptor.getLiteType() == WireFormat.FieldType.GROUP) {
+ input.readGroup(extension.getNumber(), subBuilder, extensionRegistry);
+ } else {
+ input.readMessage(subBuilder, extensionRegistry);
+ }
+ value = subBuilder.build();
+ break;
}
- if (subBuilder == null) {
- subBuilder = extension.getMessageDefaultInstance()
- .newBuilderForType();
- }
- if (extension.descriptor.getLiteType() ==
- WireFormat.FieldType.GROUP) {
- input.readGroup(extension.getNumber(),
- subBuilder, extensionRegistry);
- } else {
- input.readMessage(subBuilder, extensionRegistry);
- }
- value = subBuilder.build();
- break;
- }
case ENUM:
int rawValue = input.readEnum();
- value = extension.descriptor.getEnumType()
- .findValueByNumber(rawValue);
+ value = extension.descriptor.getEnumType().findValueByNumber(rawValue);
// If the number isn't recognized as a valid value for this enum,
// write it to unknown fields object.
if (value == null) {
@@ -684,23 +658,22 @@ public abstract class GeneratedMessageLite<
}
break;
default:
- value = FieldSet.readPrimitiveField(input,
- extension.descriptor.getLiteType(),
- /*checkUtf8=*/ false);
+ value =
+ FieldSet.readPrimitiveField(
+ input, extension.descriptor.getLiteType(), /*checkUtf8=*/ false);
break;
}
if (extension.descriptor.isRepeated()) {
- extensions.addRepeatedField(extension.descriptor,
- extension.singularToFieldSetType(value));
+ extensions.addRepeatedField(
+ extension.descriptor, extension.singularToFieldSetType(value));
} else {
- extensions.setField(extension.descriptor,
- extension.singularToFieldSetType(value));
+ extensions.setField(extension.descriptor, extension.singularToFieldSetType(value));
}
}
return true;
}
-
+
/**
* Parse an unknown field or an extension. For use by generated code only.
*
@@ -733,7 +706,7 @@ public abstract class GeneratedMessageLite<
/**
* Merges the message set from the input stream; requires message set wire format.
- *
+ *
* @param defaultInstance the default instance of the containing message we are parsing in
* @param input the stream to parse from
* @param extensionRegistry the registry to use when parsing
@@ -837,8 +810,8 @@ public abstract class GeneratedMessageLite<
subBuilder.mergeFrom(rawBytes, extensionRegistry);
MessageLite value = subBuilder.build();
- ensureExtensionsAreMutable().setField(
- extension.descriptor, extension.singularToFieldSetType(value));
+ ensureExtensionsAreMutable()
+ .setField(extension.descriptor, extension.singularToFieldSetType(value));
}
private FieldSet<ExtensionDescriptor> ensureExtensionsAreMutable() {
@@ -848,22 +821,19 @@ public abstract class GeneratedMessageLite<
return extensions;
}
- private void verifyExtensionContainingType(
- final GeneratedExtension<MessageType, ?> extension) {
- if (extension.getContainingTypeDefaultInstance() !=
- getDefaultInstanceForType()) {
+ private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension) {
+ if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) {
// This can only happen if someone uses unchecked operations.
throw new IllegalArgumentException(
- "This extension is for a different message type. Please make " +
- "sure that you are not suppressing any generics type warnings.");
+ "This extension is for a different message type. Please make "
+ + "sure that you are not suppressing any generics type warnings.");
}
}
/** Check if a singular extension is present. */
@Override
public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extension) {
- GeneratedExtension<MessageType, Type> extensionLite =
- checkIsLite(extension);
+ GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
return extensions.hasField(extensionLite.descriptor);
@@ -873,8 +843,7 @@ public abstract class GeneratedMessageLite<
@Override
public final <Type> int getExtensionCount(
final ExtensionLite<MessageType, List<Type>> extension) {
- GeneratedExtension<MessageType, List<Type>> extensionLite =
- checkIsLite(extension);
+ GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
return extensions.getRepeatedFieldCount(extensionLite.descriptor);
@@ -884,8 +853,7 @@ public abstract class GeneratedMessageLite<
@Override
@SuppressWarnings("unchecked")
public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extension) {
- GeneratedExtension<MessageType, Type> extensionLite =
- checkIsLite(extension);
+ GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
final Object value = extensions.getField(extensionLite.descriptor);
@@ -901,12 +869,12 @@ public abstract class GeneratedMessageLite<
@SuppressWarnings("unchecked")
public final <Type> Type getExtension(
final ExtensionLite<MessageType, List<Type>> extension, final int index) {
- GeneratedExtension<MessageType, List<Type>> extensionLite =
- checkIsLite(extension);
+ GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
- return (Type) extensionLite.singularFromFieldSetType(
- extensions.getRepeatedField(extensionLite.descriptor, index));
+ return (Type)
+ extensionLite.singularFromFieldSetType(
+ extensions.getRepeatedField(extensionLite.descriptor, index));
}
/** Called by subclasses to check if all extensions are initialized. */
@@ -922,19 +890,16 @@ public abstract class GeneratedMessageLite<
// END REGULAR
}
-
/**
- * Used by subclasses to serialize extensions. Extension ranges may be
- * interleaved with field numbers, but we must write them in canonical
- * (sorted by field number) order. ExtensionWriter helps us write
- * individual ranges of extensions at once.
+ * Used by subclasses to serialize extensions. Extension ranges may be interleaved with field
+ * numbers, but we must write them in canonical (sorted by field number) order. ExtensionWriter
+ * helps us write individual ranges of extensions at once.
*/
protected class ExtensionWriter {
// Imagine how much simpler this code would be if Java iterators had
// a way to get the next element without advancing the iterator.
- private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter =
- extensions.iterator();
+ private final Iterator<Map.Entry<ExtensionDescriptor, Object>> iter = extensions.iterator();
private Map.Entry<ExtensionDescriptor, Object> next;
private final boolean messageSetWireFormat;
@@ -945,15 +910,13 @@ public abstract class GeneratedMessageLite<
this.messageSetWireFormat = messageSetWireFormat;
}
- public void writeUntil(final int end, final CodedOutputStream output)
- throws IOException {
+ public void writeUntil(final int end, final CodedOutputStream output) throws IOException {
while (next != null && next.getKey().getNumber() < end) {
ExtensionDescriptor extension = next.getKey();
- if (messageSetWireFormat && extension.getLiteJavaType() ==
- WireFormat.JavaType.MESSAGE &&
- !extension.isRepeated()) {
- output.writeMessageSetExtension(extension.getNumber(),
- (MessageLite) next.getValue());
+ if (messageSetWireFormat
+ && extension.getLiteJavaType() == WireFormat.JavaType.MESSAGE
+ && !extension.isRepeated()) {
+ output.writeMessageSetExtension(extension.getNumber(), (MessageLite) next.getValue());
} else {
FieldSet.writeField(extension, next.getValue(), output);
}
@@ -969,6 +932,7 @@ public abstract class GeneratedMessageLite<
protected ExtensionWriter newExtensionWriter() {
return new ExtensionWriter(false);
}
+
protected ExtensionWriter newMessageSetExtensionWriter() {
return new ExtensionWriter(true);
}
@@ -977,18 +941,17 @@ public abstract class GeneratedMessageLite<
protected int extensionsSerializedSize() {
return extensions.getSerializedSize();
}
+
protected int extensionsSerializedSizeAsMessageSet() {
return extensions.getMessageSetSerializedSize();
}
}
- /**
- * Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}.
- */
+ /** Lite equivalent of {@link GeneratedMessage.ExtendableBuilder}. */
@SuppressWarnings("unchecked")
public abstract static class ExtendableBuilder<
- MessageType extends ExtendableMessage<MessageType, BuilderType>,
- BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
+ MessageType extends ExtendableMessage<MessageType, BuilderType>,
+ BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
extends Builder<MessageType, BuilderType>
implements ExtendableMessageOrBuilder<MessageType, BuilderType> {
protected ExtendableBuilder(MessageType defaultInstance) {
@@ -1030,14 +993,12 @@ public abstract class GeneratedMessageLite<
return super.buildPartial();
}
- private void verifyExtensionContainingType(
- final GeneratedExtension<MessageType, ?> extension) {
- if (extension.getContainingTypeDefaultInstance() !=
- getDefaultInstanceForType()) {
+ private void verifyExtensionContainingType(final GeneratedExtension<MessageType, ?> extension) {
+ if (extension.getContainingTypeDefaultInstance() != getDefaultInstanceForType()) {
// This can only happen if someone uses unchecked operations.
throw new IllegalArgumentException(
- "This extension is for a different message type. Please make " +
- "sure that you are not suppressing any generics type warnings.");
+ "This extension is for a different message type. Please make "
+ + "sure that you are not suppressing any generics type warnings.");
}
}
@@ -1071,10 +1032,8 @@ public abstract class GeneratedMessageLite<
/** Set the value of an extension. */
public final <Type> BuilderType setExtension(
- final ExtensionLite<MessageType, Type> extension,
- final Type value) {
- GeneratedExtension<MessageType, Type> extensionLite =
- checkIsLite(extension);
+ final ExtensionLite<MessageType, Type> extension, final Type value) {
+ GeneratedExtension<MessageType, Type> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
copyOnWrite();
@@ -1085,10 +1044,8 @@ public abstract class GeneratedMessageLite<
/** Set the value of one element of a repeated extension. */
public final <Type> BuilderType setExtension(
- final ExtensionLite<MessageType, List<Type>> extension,
- final int index, final Type value) {
- GeneratedExtension<MessageType, List<Type>> extensionLite =
- checkIsLite(extension);
+ final ExtensionLite<MessageType, List<Type>> extension, final int index, final Type value) {
+ GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
copyOnWrite();
@@ -1100,10 +1057,8 @@ public abstract class GeneratedMessageLite<
/** Append a value to a repeated extension. */
public final <Type> BuilderType addExtension(
- final ExtensionLite<MessageType, List<Type>> extension,
- final Type value) {
- GeneratedExtension<MessageType, List<Type>> extensionLite =
- checkIsLite(extension);
+ final ExtensionLite<MessageType, List<Type>> extension, final Type value) {
+ GeneratedExtension<MessageType, List<Type>> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
copyOnWrite();
@@ -1113,8 +1068,7 @@ public abstract class GeneratedMessageLite<
}
/** Clear an extension. */
- public final <Type> BuilderType clearExtension(
- final ExtensionLite<MessageType, ?> extension) {
+ public final <Type> BuilderType clearExtension(final ExtensionLite<MessageType, ?> extension) {
GeneratedExtension<MessageType, ?> extensionLite = checkIsLite(extension);
verifyExtensionContainingType(extensionLite);
@@ -1128,50 +1082,45 @@ public abstract class GeneratedMessageLite<
/** For use by generated code only. */
public static <ContainingType extends MessageLite, Type>
- GeneratedExtension<ContainingType, Type>
- newSingularGeneratedExtension(
- final ContainingType containingTypeDefaultInstance,
- final Type defaultValue,
- final MessageLite messageDefaultInstance,
- final Internal.EnumLiteMap<?> enumTypeMap,
- final int number,
- final WireFormat.FieldType type,
- final Class singularType) {
+ GeneratedExtension<ContainingType, Type> newSingularGeneratedExtension(
+ final ContainingType containingTypeDefaultInstance,
+ final Type defaultValue,
+ final MessageLite messageDefaultInstance,
+ final Internal.EnumLiteMap<?> enumTypeMap,
+ final int number,
+ final WireFormat.FieldType type,
+ final Class singularType) {
return new GeneratedExtension<ContainingType, Type>(
containingTypeDefaultInstance,
defaultValue,
messageDefaultInstance,
- new ExtensionDescriptor(enumTypeMap, number, type,
- false /* isRepeated */,
- false /* isPacked */),
+ new ExtensionDescriptor(
+ enumTypeMap, number, type, /* isRepeated= */ false, /* isPacked= */ false),
singularType);
}
/** For use by generated code only. */
public static <ContainingType extends MessageLite, Type>
- GeneratedExtension<ContainingType, Type>
- newRepeatedGeneratedExtension(
- final ContainingType containingTypeDefaultInstance,
- final MessageLite messageDefaultInstance,
- final Internal.EnumLiteMap<?> enumTypeMap,
- final int number,
- final WireFormat.FieldType type,
- final boolean isPacked,
- final Class singularType) {
- @SuppressWarnings("unchecked") // Subclasses ensure Type is a List
+ GeneratedExtension<ContainingType, Type> newRepeatedGeneratedExtension(
+ final ContainingType containingTypeDefaultInstance,
+ final MessageLite messageDefaultInstance,
+ final Internal.EnumLiteMap<?> enumTypeMap,
+ final int number,
+ final WireFormat.FieldType type,
+ final boolean isPacked,
+ final Class singularType) {
+ @SuppressWarnings("unchecked") // Subclasses ensure Type is a List
Type emptyList = (Type) Collections.emptyList();
return new GeneratedExtension<ContainingType, Type>(
containingTypeDefaultInstance,
emptyList,
messageDefaultInstance,
- new ExtensionDescriptor(
- enumTypeMap, number, type, true /* isRepeated */, isPacked),
+ new ExtensionDescriptor(enumTypeMap, number, type, /* isRepeated= */ true, isPacked),
singularType);
}
static final class ExtensionDescriptor
- implements FieldSet.FieldDescriptorLite<
- ExtensionDescriptor> {
+ implements FieldSet.FieldDescriptorLite<ExtensionDescriptor> {
ExtensionDescriptor(
final Internal.EnumLiteMap<?> enumTypeMap,
final int number,
@@ -1243,8 +1192,8 @@ public abstract class GeneratedMessageLite<
return clazz.getMethod(name, params);
} catch (NoSuchMethodException e) {
throw new RuntimeException(
- "Generated message class \"" + clazz.getName() +
- "\" missing method \"" + name + "\".", e);
+ "Generated message class \"" + clazz.getName() + "\" missing method \"" + name + "\".",
+ e);
}
}
@@ -1254,8 +1203,7 @@ public abstract class GeneratedMessageLite<
return method.invoke(object, params);
} catch (IllegalAccessException e) {
throw new RuntimeException(
- "Couldn't use Java reflection to implement protocol message " +
- "reflection.", e);
+ "Couldn't use Java reflection to implement protocol message reflection.", e);
} catch (InvocationTargetException e) {
final Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
@@ -1264,7 +1212,7 @@ public abstract class GeneratedMessageLite<
throw (Error) cause;
} else {
throw new RuntimeException(
- "Unexpected exception thrown by generated accessor method.", cause);
+ "Unexpected exception thrown by generated accessor method.", cause);
}
}
}
@@ -1273,20 +1221,18 @@ public abstract class GeneratedMessageLite<
/**
* Lite equivalent to {@link GeneratedMessage.GeneratedExtension}.
*
- * Users should ignore the contents of this class and only use objects of
- * this type as parameters to extension accessors and ExtensionRegistry.add().
+ * <p>Users should ignore the contents of this class and only use objects of this type as
+ * parameters to extension accessors and ExtensionRegistry.add().
*/
- public static class GeneratedExtension<
- ContainingType extends MessageLite, Type>
- extends ExtensionLite<ContainingType, Type> {
+ public static class GeneratedExtension<ContainingType extends MessageLite, Type>
+ extends ExtensionLite<ContainingType, Type> {
/**
* Create a new instance with the given parameters.
*
- * The last parameter {@code singularType} is only needed for enum types.
- * We store integer values for enum types in a {@link ExtendableMessage}
- * and use Java reflection to convert an integer value back into a concrete
- * enum object.
+ * <p>The last parameter {@code singularType} is only needed for enum types. We store integer
+ * values for enum types in a {@link ExtendableMessage} and use Java reflection to convert an
+ * integer value back into a concrete enum object.
*/
GeneratedExtension(
final ContainingType containingTypeDefaultInstance,
@@ -1297,13 +1243,11 @@ public abstract class GeneratedMessageLite<
// Defensive checks to verify the correct initialization order of
// GeneratedExtensions and their related GeneratedMessages.
if (containingTypeDefaultInstance == null) {
- throw new IllegalArgumentException(
- "Null containingTypeDefaultInstance");
+ throw new IllegalArgumentException("Null containingTypeDefaultInstance");
}
- if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE &&
- messageDefaultInstance == null) {
- throw new IllegalArgumentException(
- "Null messageDefaultInstance");
+ if (descriptor.getLiteType() == WireFormat.FieldType.MESSAGE
+ && messageDefaultInstance == null) {
+ throw new IllegalArgumentException("Null messageDefaultInstance");
}
this.containingTypeDefaultInstance = containingTypeDefaultInstance;
this.defaultValue = defaultValue;
@@ -1316,9 +1260,7 @@ public abstract class GeneratedMessageLite<
final MessageLite messageDefaultInstance;
final ExtensionDescriptor descriptor;
- /**
- * Default instance of the type being extended, used to identify that type.
- */
+ /** Default instance of the type being extended, used to identify that type. */
public ContainingType getContainingTypeDefaultInstance() {
return containingTypeDefaultInstance;
}
@@ -1329,10 +1271,9 @@ public abstract class GeneratedMessageLite<
return descriptor.getNumber();
}
-
/**
- * If the extension is an embedded message or group, returns the default
- * instance of the message.
+ * If the extension is an embedded message or group, returns the default instance of the
+ * message.
*/
@Override
public MessageLite getMessageDefaultInstance() {
@@ -1406,8 +1347,8 @@ public abstract class GeneratedMessageLite<
}
/**
- * A serialized (serializable) form of the generated message. Stores the
- * message as a class name and a byte array.
+ * A serialized (serializable) form of the generated message. Stores the message as a class name
+ * and a byte array.
*/
protected static final class SerializedForm implements Serializable {
@@ -1417,34 +1358,38 @@ public abstract class GeneratedMessageLite<
private static final long serialVersionUID = 0L;
+ // since v3.6.1
+ private final Class<?> messageClass;
+ // only included for backwards compatibility before messageClass was added
private final String messageClassName;
private final byte[] asBytes;
/**
* Creates the serialized form by calling {@link com.google.protobuf.MessageLite#toByteArray}.
+ *
* @param regularForm the message to serialize
*/
SerializedForm(MessageLite regularForm) {
- messageClassName = regularForm.getClass().getName();
+ messageClass = regularForm.getClass();
+ messageClassName = messageClass.getName();
asBytes = regularForm.toByteArray();
}
/**
- * When read from an ObjectInputStream, this method converts this object
- * back to the regular form. Part of Java's serialization magic.
+ * When read from an ObjectInputStream, this method converts this object back to the regular
+ * form. Part of Java's serialization magic.
+ *
* @return a GeneratedMessage of the type that was serialized
*/
@SuppressWarnings("unchecked")
protected Object readResolve() throws ObjectStreamException {
try {
- Class<?> messageClass = Class.forName(messageClassName);
+ Class<?> messageClass = resolveMessageClass();
java.lang.reflect.Field defaultInstanceField =
messageClass.getDeclaredField("DEFAULT_INSTANCE");
defaultInstanceField.setAccessible(true);
MessageLite defaultInstance = (MessageLite) defaultInstanceField.get(null);
- return defaultInstance.newBuilderForType()
- .mergeFrom(asBytes)
- .buildPartial();
+ return defaultInstance.newBuilderForType().mergeFrom(asBytes).buildPartial();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to find proto buffer class: " + messageClassName, e);
} catch (NoSuchFieldException e) {
@@ -1464,7 +1409,7 @@ public abstract class GeneratedMessageLite<
@Deprecated
private Object readResolveFallback() throws ObjectStreamException {
try {
- Class<?> messageClass = Class.forName(messageClassName);
+ Class<?> messageClass = resolveMessageClass();
java.lang.reflect.Field defaultInstanceField =
messageClass.getDeclaredField("defaultInstance");
defaultInstanceField.setAccessible(true);
@@ -1484,18 +1429,18 @@ public abstract class GeneratedMessageLite<
throw new RuntimeException("Unable to understand proto buffer", e);
}
}
+
+ private Class<?> resolveMessageClass() throws ClassNotFoundException {
+ return messageClass != null ? messageClass : Class.forName(messageClassName);
+ }
}
- /**
- * Checks that the {@link Extension} is Lite and returns it as a
- * {@link GeneratedExtension}.
- */
+ /** Checks that the {@link Extension} is Lite and returns it as a {@link GeneratedExtension}. */
private static <
- MessageType extends ExtendableMessage<MessageType, BuilderType>,
- BuilderType extends ExtendableBuilder<MessageType, BuilderType>,
- T>
- GeneratedExtension<MessageType, T> checkIsLite(
- ExtensionLite<MessageType, T> extension) {
+ MessageType extends ExtendableMessage<MessageType, BuilderType>,
+ BuilderType extends ExtendableBuilder<MessageType, BuilderType>,
+ T>
+ GeneratedExtension<MessageType, T> checkIsLite(ExtensionLite<MessageType, T> extension) {
if (!extension.isLite()) {
throw new IllegalArgumentException("Expected a lite extension.");
}
@@ -1505,8 +1450,8 @@ public abstract class GeneratedMessageLite<
/**
* A static helper method for checking if a message is initialized, optionally memoizing.
- * <p>
- * For use by generated code only.
+ *
+ * <p>For use by generated code only.
*/
protected static final <T extends GeneratedMessageLite<T, ?>> boolean isInitialized(
T message, boolean shouldMemoize) {
@@ -1594,13 +1539,13 @@ public abstract class GeneratedMessageLite<
/**
* A {@link Parser} implementation that delegates to the default instance.
- * <p>
- * For use by generated code only.
+ *
+ * <p>For use by generated code only.
*/
protected static class DefaultInstanceBasedParser<T extends GeneratedMessageLite<T, ?>>
extends AbstractParser<T> {
- private T defaultInstance;
+ private final T defaultInstance;
public DefaultInstanceBasedParser(T defaultInstance) {
this.defaultInstance = defaultInstance;
@@ -1625,7 +1570,7 @@ public abstract class GeneratedMessageLite<
// TODO(dweis): Should this verify that the last tag was 0?
static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
T instance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
- throws InvalidProtocolBufferException {
+ throws InvalidProtocolBufferException {
@SuppressWarnings("unchecked") // Guaranteed by protoc
T result = (T) instance.dynamicMethod(MethodToInvoke.NEW_MUTABLE_INSTANCE);
try {
@@ -1682,9 +1627,7 @@ public abstract class GeneratedMessageLite<
}
protected static <T extends GeneratedMessageLite<T, ?>> T parsePartialFrom(
- T defaultInstance,
- CodedInputStream input)
- throws InvalidProtocolBufferException {
+ T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException {
return parsePartialFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
}
@@ -1697,7 +1640,8 @@ public abstract class GeneratedMessageLite<
private static <T extends GeneratedMessageLite<T, ?>> T checkMessageInitialized(T message)
throws InvalidProtocolBufferException {
if (message != null && !message.isInitialized()) {
- throw message.newUninitializedMessageException()
+ throw message
+ .newUninitializedMessageException()
.asInvalidProtocolBufferException()
.setUnfinishedMessage(message);
}
@@ -1720,8 +1664,7 @@ public abstract class GeneratedMessageLite<
// Validates last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
- T defaultInstance, ByteString data)
- throws InvalidProtocolBufferException {
+ T defaultInstance, ByteString data) throws InvalidProtocolBufferException {
return checkMessageInitialized(
parseFrom(defaultInstance, data, ExtensionRegistryLite.getEmptyRegistry()));
}
@@ -1775,8 +1718,7 @@ public abstract class GeneratedMessageLite<
// Validates last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
- T defaultInstance, byte[] data)
- throws InvalidProtocolBufferException {
+ T defaultInstance, byte[] data) throws InvalidProtocolBufferException {
return checkMessageInitialized(parsePartialFrom(defaultInstance, data));
}
@@ -1789,10 +1731,11 @@ public abstract class GeneratedMessageLite<
// Does not validate last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
- T defaultInstance, InputStream input)
- throws InvalidProtocolBufferException {
+ T defaultInstance, InputStream input) throws InvalidProtocolBufferException {
return checkMessageInitialized(
- parsePartialFrom(defaultInstance, CodedInputStream.newInstance(input),
+ parsePartialFrom(
+ defaultInstance,
+ CodedInputStream.newInstance(input),
ExtensionRegistryLite.getEmptyRegistry()));
}
@@ -1806,8 +1749,7 @@ public abstract class GeneratedMessageLite<
// Does not validate last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
- T defaultInstance, CodedInputStream input)
- throws InvalidProtocolBufferException {
+ T defaultInstance, CodedInputStream input) throws InvalidProtocolBufferException {
return parseFrom(defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry());
}
@@ -1815,17 +1757,15 @@ public abstract class GeneratedMessageLite<
protected static <T extends GeneratedMessageLite<T, ?>> T parseFrom(
T defaultInstance, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
- return checkMessageInitialized(
- parsePartialFrom(defaultInstance, input, extensionRegistry));
+ return checkMessageInitialized(parsePartialFrom(defaultInstance, input, extensionRegistry));
}
// Validates last tag.
protected static <T extends GeneratedMessageLite<T, ?>> T parseDelimitedFrom(
- T defaultInstance, InputStream input)
- throws InvalidProtocolBufferException {
+ T defaultInstance, InputStream input) throws InvalidProtocolBufferException {
return checkMessageInitialized(
- parsePartialDelimitedFrom(defaultInstance, input,
- ExtensionRegistryLite.getEmptyRegistry()));
+ parsePartialDelimitedFrom(
+ defaultInstance, input, ExtensionRegistryLite.getEmptyRegistry()));
}
// Validates last tag.
@@ -1837,9 +1777,7 @@ public abstract class GeneratedMessageLite<
}
private static <T extends GeneratedMessageLite<T, ?>> T parsePartialDelimitedFrom(
- T defaultInstance,
- InputStream input,
- ExtensionRegistryLite extensionRegistry)
+ T defaultInstance, InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
int size;
try {
@@ -1871,44 +1809,62 @@ public abstract class GeneratedMessageLite<
*/
protected interface Visitor {
boolean visitBoolean(boolean minePresent, boolean mine, boolean otherPresent, boolean other);
+
int visitInt(boolean minePresent, int mine, boolean otherPresent, int other);
+
double visitDouble(boolean minePresent, double mine, boolean otherPresent, double other);
+
float visitFloat(boolean minePresent, float mine, boolean otherPresent, float other);
+
long visitLong(boolean minePresent, long mine, boolean otherPresent, long other);
+
String visitString(boolean minePresent, String mine, boolean otherPresent, String other);
+
ByteString visitByteString(
boolean minePresent, ByteString mine, boolean otherPresent, ByteString other);
Object visitOneofBoolean(boolean minePresent, Object mine, Object other);
+
Object visitOneofInt(boolean minePresent, Object mine, Object other);
+
Object visitOneofDouble(boolean minePresent, Object mine, Object other);
+
Object visitOneofFloat(boolean minePresent, Object mine, Object other);
+
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 visitOneofMessage(boolean minePresent, Object mine, Object other);
+
void visitOneofNotSet(boolean minePresent);
- /**
- * Message fields use null sentinals.
- */
+ /** Message fields use null sentinals. */
<T extends MessageLite> T visitMessage(T mine, T other);
<T> ProtobufList<T> visitList(ProtobufList<T> mine, ProtobufList<T> other);
+
BooleanList visitBooleanList(BooleanList mine, BooleanList other);
+
IntList visitIntList(IntList mine, IntList other);
+
DoubleList visitDoubleList(DoubleList mine, DoubleList other);
+
FloatList visitFloatList(FloatList mine, FloatList other);
+
LongList visitLongList(LongList mine, LongList other);
+
FieldSet<ExtensionDescriptor> visitExtensions(
FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other);
+
UnknownFieldSetLite visitUnknownFields(UnknownFieldSetLite mine, UnknownFieldSetLite other);
+
<K, V> MapFieldLite<K, V> visitMap(MapFieldLite<K, V> mine, MapFieldLite<K, V> other);
}
- /**
- * Implements equals. Throws a {@link NotEqualsException} when not equal.
- */
+ /** Implements equals. Throws a {@link NotEqualsException} when not equal. */
static class EqualsVisitor implements Visitor {
static final class NotEqualsException extends RuntimeException {}
@@ -2115,8 +2071,7 @@ public abstract class GeneratedMessageLite<
@Override
public FieldSet<ExtensionDescriptor> visitExtensions(
- FieldSet<ExtensionDescriptor> mine,
- FieldSet<ExtensionDescriptor> other) {
+ FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other) {
if (!mine.equals(other)) {
throw NOT_EQUALS;
}
@@ -2125,8 +2080,7 @@ public abstract class GeneratedMessageLite<
@Override
public UnknownFieldSetLite visitUnknownFields(
- UnknownFieldSetLite mine,
- UnknownFieldSetLite other) {
+ UnknownFieldSetLite mine, UnknownFieldSetLite other) {
if (!mine.equals(other)) {
throw NOT_EQUALS;
}
@@ -2142,9 +2096,7 @@ public abstract class GeneratedMessageLite<
}
}
- /**
- * Implements hashCode by accumulating state.
- */
+ /** Implements hashCode by accumulating state. */
static class HashCodeVisitor implements Visitor {
// The caller must ensure that the visitor is invoked parameterized with this and this such that
@@ -2307,16 +2259,14 @@ public abstract class GeneratedMessageLite<
@Override
public FieldSet<ExtensionDescriptor> visitExtensions(
- FieldSet<ExtensionDescriptor> mine,
- FieldSet<ExtensionDescriptor> other) {
+ FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other) {
hashCode = (53 * hashCode) + mine.hashCode();
return mine;
}
@Override
public UnknownFieldSetLite visitUnknownFields(
- UnknownFieldSetLite mine,
- UnknownFieldSetLite other) {
+ UnknownFieldSetLite mine, UnknownFieldSetLite other) {
hashCode = (53 * hashCode) + mine.hashCode();
return mine;
}
@@ -2328,9 +2278,7 @@ public abstract class GeneratedMessageLite<
}
}
- /**
- * Implements field merging semantics over the visitor interface.
- */
+ /** Implements field merging semantics over the visitor interface. */
protected static class MergeFromVisitor implements Visitor {
public static final MergeFromVisitor INSTANCE = new MergeFromVisitor();
@@ -2520,8 +2468,7 @@ public abstract class GeneratedMessageLite<
@Override
public FieldSet<ExtensionDescriptor> visitExtensions(
- FieldSet<ExtensionDescriptor> mine,
- FieldSet<ExtensionDescriptor> other) {
+ FieldSet<ExtensionDescriptor> mine, FieldSet<ExtensionDescriptor> other) {
if (mine.isImmutable()) {
mine = mine.clone();
}
@@ -2531,10 +2478,10 @@ public abstract class GeneratedMessageLite<
@Override
public UnknownFieldSetLite visitUnknownFields(
- UnknownFieldSetLite mine,
- UnknownFieldSetLite other) {
+ UnknownFieldSetLite mine, UnknownFieldSetLite other) {
return other == UnknownFieldSetLite.getDefaultInstance()
- ? mine : UnknownFieldSetLite.mutableCopyOf(mine, other);
+ ? mine
+ : UnknownFieldSetLite.mutableCopyOf(mine, other);
}
@Override
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 4acd8f2f..53af544f 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
@@ -38,6 +38,11 @@ import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
+import com.google.protobuf.Internal.BooleanList;
+import com.google.protobuf.Internal.DoubleList;
+import com.google.protobuf.Internal.FloatList;
+import com.google.protobuf.Internal.IntList;
+import com.google.protobuf.Internal.LongList;
// In opensource protobuf, we have versioned this GeneratedMessageV3 class to GeneratedMessageV3V3 and
// in the future may have GeneratedMessageV3V4 etc. This allows us to change some aspects of this
// class without breaking binary compatibility with old generated code that still subclasses
@@ -293,16 +298,17 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return unknownFields.mergeFieldFrom(tag, input);
}
+ /**
+ * Delegates to parseUnknownField. This method is obsolete, but we must retain it for
+ * compatibility with older generated code.
+ */
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);
+ return parseUnknownField(input, unknownFields, extensionRegistry, tag);
}
protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input)
@@ -363,6 +369,76 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations();
}
+ protected static IntList emptyIntList() {
+ return IntArrayList.emptyList();
+ }
+
+ protected static IntList newIntList() {
+ return new IntArrayList();
+ }
+
+ protected static IntList mutableCopy(IntList list) {
+ int size = list.size();
+ return list.mutableCopyWithCapacity(
+ size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
+ }
+
+ protected static LongList emptyLongList() {
+ return LongArrayList.emptyList();
+ }
+
+ protected static LongList newLongList() {
+ return new LongArrayList();
+ }
+
+ protected static LongList mutableCopy(LongList list) {
+ int size = list.size();
+ return list.mutableCopyWithCapacity(
+ size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
+ }
+
+ protected static FloatList emptyFloatList() {
+ return FloatArrayList.emptyList();
+ }
+
+ protected static FloatList newFloatList() {
+ return new FloatArrayList();
+ }
+
+ protected static FloatList mutableCopy(FloatList list) {
+ int size = list.size();
+ return list.mutableCopyWithCapacity(
+ size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
+ }
+
+ protected static DoubleList emptyDoubleList() {
+ return DoubleArrayList.emptyList();
+ }
+
+ protected static DoubleList newDoubleList() {
+ return new DoubleArrayList();
+ }
+
+ protected static DoubleList mutableCopy(DoubleList list) {
+ int size = list.size();
+ return list.mutableCopyWithCapacity(
+ size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
+ }
+
+ protected static BooleanList emptyBooleanList() {
+ return BooleanArrayList.emptyList();
+ }
+
+ protected static BooleanList newBooleanList() {
+ return new BooleanArrayList();
+ }
+
+ protected static BooleanList mutableCopy(BooleanList list) {
+ int size = list.size();
+ return list.mutableCopyWithCapacity(
+ size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
+ }
+
@Override
public void writeTo(final CodedOutputStream output) throws IOException {
MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false);
@@ -641,13 +717,12 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
return (BuilderType) this;
}
+ /**
+ * Delegates to setUnknownFields. This method is obsolete, but we must retain it for
+ * compatibility with older generated code.
+ */
protected BuilderType setUnknownFieldsProto3(final UnknownFieldSet unknownFields) {
- if (CodedInputStream.getProto3DiscardUnknownFieldsDefault()) {
- return (BuilderType) this;
- }
- this.unknownFields = unknownFields;
- onChanged();
- return (BuilderType) this;
+ return setUnknownFields(unknownFields);
}
@Override
@@ -1009,19 +1084,17 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
getDescriptorForType(), new MessageReflection.ExtensionAdapter(extensions), tag);
}
+ /**
+ * Delegates to parseUnknownField. This method is obsolete, but we must retain it for
+ * compatibility with older generated code.
+ */
@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);
+ return parseUnknownField(input, unknownFields, extensionRegistry, tag);
}
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 aacd71e1..c9b12c42 100644
--- a/java/core/src/main/java/com/google/protobuf/IntArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/IntArrayList.java
@@ -46,6 +46,7 @@ final class IntArrayList extends AbstractProtobufList<Integer>
implements IntList, RandomAccess, PrimitiveNonBoxingCollection {
private static final IntArrayList EMPTY_LIST = new IntArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
@@ -54,9 +55,7 @@ final class IntArrayList extends AbstractProtobufList<Integer>
return EMPTY_LIST;
}
- /**
- * The backing store for the list.
- */
+ /** The backing store for the list. */
private int[] array;
/**
@@ -65,16 +64,13 @@ final class IntArrayList extends AbstractProtobufList<Integer>
*/
private int size;
- /**
- * Constructs a new mutable {@code IntArrayList} with default capacity.
- */
+ /** Constructs a new mutable {@code IntArrayList} with default capacity. */
IntArrayList() {
this(new int[DEFAULT_CAPACITY], 0);
}
/**
- * Constructs a new mutable {@code IntArrayList}
- * containing the same elements as {@code other}.
+ * Constructs a new mutable {@code IntArrayList} containing the same elements as {@code other}.
*/
private IntArrayList(int[] other, int size) {
array = other;
@@ -168,17 +164,13 @@ final class IntArrayList extends AbstractProtobufList<Integer>
addInt(index, element);
}
- /**
- * Like {@link #add(Integer)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Integer)} but more efficient in that it doesn't box the element. */
@Override
public void addInt(int element) {
addInt(size, element);
}
- /**
- * Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element. */
private void addInt(int index, int element) {
ensureIsMutable();
if (index < 0 || index > size) {
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 848cad03..713ccb58 100644
--- a/java/core/src/main/java/com/google/protobuf/Internal.java
+++ b/java/core/src/main/java/com/google/protobuf/Internal.java
@@ -45,10 +45,9 @@ import java.util.RandomAccess;
import java.util.Set;
/**
- * The classes contained within are used internally by the Protocol Buffer
- * library and generated message implementations. They are public only because
- * those generated messages do not reside in the {@code protobuf} package.
- * Others should not use this class directly.
+ * The classes contained within are used internally by the Protocol Buffer library and generated
+ * message implementations. They are public only because those generated messages do not reside in
+ * the {@code protobuf} package. Others should not use this class directly.
*
* @author kenton@google.com (Kenton Varda)
*/
@@ -59,9 +58,7 @@ public final class Internal {
static final Charset UTF_8 = Charset.forName("UTF-8");
static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
- /**
- * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}.
- */
+ /** Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. */
static <T> T checkNotNull(T obj) {
if (obj == null) {
throw new NullPointerException();
@@ -69,9 +66,7 @@ public final class Internal {
return obj;
}
- /**
- * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}.
- */
+ /** 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);
@@ -80,73 +75,63 @@ public final class Internal {
}
/**
- * Helper called by generated code to construct default values for string
- * fields.
- * <p>
- * The protocol compiler does not actually contain a UTF-8 decoder -- it
- * just pushes UTF-8-encoded text around without touching it. The one place
- * where this presents a problem is when generating Java string literals.
- * Unicode characters in the string literal would normally need to be encoded
- * using a Unicode escape sequence, which would require decoding them.
- * To get around this, protoc instead embeds the UTF-8 bytes into the
- * generated code and leaves it to the runtime library to decode them.
- * <p>
- * It gets worse, though. If protoc just generated a byte array, like:
- * new byte[] {0x12, 0x34, 0x56, 0x78}
- * Java actually generates *code* which allocates an array and then fills
- * in each value. This is much less efficient than just embedding the bytes
- * directly into the bytecode. To get around this, we need another
- * work-around. String literals are embedded directly, so protoc actually
- * generates a string literal corresponding to the bytes. The easiest way
- * to do this is to use the ISO-8859-1 character set, which corresponds to
- * the first 256 characters of the Unicode range. Protoc can then use
- * good old CEscape to generate the string.
- * <p>
- * So we have a string literal which represents a set of bytes which
- * represents another string. This function -- stringDefaultValue --
- * converts from the generated string to the string we actually want. The
- * generated code calls this automatically.
+ * Helper called by generated code to construct default values for string fields.
+ *
+ * <p>The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes
+ * UTF-8-encoded text around without touching it. The one place where this presents a problem is
+ * when generating Java string literals. Unicode characters in the string literal would normally
+ * need to be encoded using a Unicode escape sequence, which would require decoding them. To get
+ * around this, protoc instead embeds the UTF-8 bytes into the generated code and leaves it to the
+ * runtime library to decode them.
+ *
+ * <p>It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34,
+ * 0x56, 0x78} Java actually generates *code* which allocates an array and then fills in each
+ * value. This is much less efficient than just embedding the bytes directly into the bytecode. To
+ * get around this, we need another work-around. String literals are embedded directly, so protoc
+ * actually generates a string literal corresponding to the bytes. The easiest way to do this is
+ * to use the ISO-8859-1 character set, which corresponds to the first 256 characters of the
+ * Unicode range. Protoc can then use good old CEscape to generate the string.
+ *
+ * <p>So we have a string literal which represents a set of bytes which represents another string.
+ * This function -- stringDefaultValue -- converts from the generated string to the string we
+ * actually want. The generated code calls this automatically.
*/
public static String stringDefaultValue(String bytes) {
return new String(bytes.getBytes(ISO_8859_1), UTF_8);
}
/**
- * Helper called by generated code to construct default values for bytes
- * fields.
- * <p>
- * This is a lot like {@link #stringDefaultValue}, but for bytes fields.
- * In this case we only need the second of the two hacks -- allowing us to
- * embed raw bytes as a string literal with ISO-8859-1 encoding.
+ * Helper called by generated code to construct default values for bytes fields.
+ *
+ * <p>This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only
+ * need the second of the two hacks -- allowing us to embed raw bytes as a string literal with
+ * ISO-8859-1 encoding.
*/
public static ByteString bytesDefaultValue(String bytes) {
return ByteString.copyFrom(bytes.getBytes(ISO_8859_1));
}
/**
- * Helper called by generated code to construct default values for bytes
- * fields.
- * <p>
- * This is like {@link #bytesDefaultValue}, but returns a byte array.
+ * Helper called by generated code to construct default values for bytes fields.
+ *
+ * <p>This is like {@link #bytesDefaultValue}, but returns a byte array.
*/
public static byte[] byteArrayDefaultValue(String bytes) {
return bytes.getBytes(ISO_8859_1);
}
/**
- * Helper called by generated code to construct default values for bytes
- * fields.
- * <p>
- * This is like {@link #bytesDefaultValue}, but returns a ByteBuffer.
+ * Helper called by generated code to construct default values for bytes fields.
+ *
+ * <p>This is like {@link #bytesDefaultValue}, but returns a ByteBuffer.
*/
public static ByteBuffer byteBufferDefaultValue(String bytes) {
return ByteBuffer.wrap(byteArrayDefaultValue(bytes));
}
/**
- * Create a new ByteBuffer and copy all the content of {@code source}
- * ByteBuffer to the new ByteBuffer. The new ByteBuffer's limit and
- * capacity will be source.capacity(), and its position will be 0.
- * Note that the state of {@code source} ByteBuffer won't be changed.
+ * Create a new ByteBuffer and copy all the content of {@code source} ByteBuffer to the new
+ * ByteBuffer. The new ByteBuffer's limit and capacity will be source.capacity(), and its position
+ * will be 0. Note that the state of {@code source} ByteBuffer won't be changed.
*/
public static ByteBuffer copyByteBuffer(ByteBuffer source) {
// Make a duplicate of the source ByteBuffer and read data from the
@@ -162,29 +147,27 @@ public final class Internal {
}
/**
- * Helper called by generated code to determine if a byte array is a valid
- * UTF-8 encoded string such that the original bytes can be converted to
- * a String object and then back to a byte array round tripping the bytes
- * without loss. More precisely, returns {@code true} whenever:
- * <pre> {@code
+ * Helper called by generated code to determine if a byte array is a valid UTF-8 encoded string
+ * such that the original bytes can be converted to a String object and then back to a byte array
+ * round tripping the bytes without loss. More precisely, returns {@code true} whenever:
+ *
+ * <pre>{@code
* Arrays.equals(byteString.toByteArray(),
* new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8"))
* }</pre>
*
- * <p>This method rejects "overlong" byte sequences, as well as
- * 3-byte sequences that would map to a surrogate character, in
- * accordance with the restricted definition of UTF-8 introduced in
- * Unicode 3.1. Note that the UTF-8 decoder included in Oracle's
- * JDK has been modified to also reject "overlong" byte sequences,
- * but currently (2011) still accepts 3-byte surrogate character
+ * <p>This method rejects "overlong" byte sequences, as well as 3-byte sequences that would map to
+ * a surrogate character, in accordance with the restricted definition of UTF-8 introduced in
+ * Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has been modified to also
+ * reject "overlong" byte sequences, but currently (2011) still accepts 3-byte surrogate character
* byte sequences.
*
* <p>See the Unicode Standard,<br>
* Table 3-6. <em>UTF-8 Bit Distribution</em>,<br>
* Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>.
*
- * <p>As of 2011-02, this method simply returns the result of {@link
- * ByteString#isValidUtf8()}. Calling that method directly is preferred.
+ * <p>As of 2011-02, this method simply returns the result of {@link ByteString#isValidUtf8()}.
+ * Calling that method directly is preferred.
*
* @param byteString the string to check
* @return whether the byte array is round trippable
@@ -193,49 +176,49 @@ public final class Internal {
return byteString.isValidUtf8();
}
- /**
- * Like {@link #isValidUtf8(ByteString)} but for byte arrays.
- */
+ /** Like {@link #isValidUtf8(ByteString)} but for byte arrays. */
public static boolean isValidUtf8(byte[] byteArray) {
return Utf8.isValidUtf8(byteArray);
}
- /**
- * Helper method to get the UTF-8 bytes of a string.
- */
+ /** Helper method to get the UTF-8 bytes of a string. */
public static byte[] toByteArray(String value) {
return value.getBytes(UTF_8);
}
- /**
- * Helper method to convert a byte array to a string using UTF-8 encoding.
- */
+ /** Helper method to convert a byte array to a string using UTF-8 encoding. */
public static String toStringUtf8(byte[] bytes) {
return new String(bytes, UTF_8);
}
/**
- * Interface for an enum value or value descriptor, to be used in FieldSet.
- * The lite library stores enum values directly in FieldSets but the full
- * library stores EnumValueDescriptors in order to better support reflection.
+ * Interface for an enum value or value descriptor, to be used in FieldSet. The lite library
+ * stores enum values directly in FieldSets but the full library stores EnumValueDescriptors in
+ * order to better support reflection.
*/
public interface EnumLite {
int getNumber();
}
/**
- * Interface for an object which maps integers to {@link EnumLite}s.
- * {@link Descriptors.EnumDescriptor} implements this interface by mapping
- * numbers to {@link Descriptors.EnumValueDescriptor}s. Additionally,
- * every generated enum type has a static method internalGetValueMap() which
- * returns an implementation of this type that maps numbers to enum values.
+ * Interface for an object which maps integers to {@link EnumLite}s. {@link
+ * Descriptors.EnumDescriptor} implements this interface by mapping numbers to {@link
+ * Descriptors.EnumValueDescriptor}s. Additionally, every generated enum type has a static method
+ * internalGetValueMap() which returns an implementation of this type that maps numbers to enum
+ * values.
*/
public interface EnumLiteMap<T extends EnumLite> {
T findValueByNumber(int number);
}
+ /** Interface for an object which verifies integers are in range. */
+ public interface EnumVerifier {
+ boolean isInRange(int number);
+ }
+
/**
* Helper method for implementing {@link Message#hashCode()} for longs.
+ *
* @see Long#hashCode()
*/
public static int hashLong(long n) {
@@ -243,8 +226,8 @@ public final class Internal {
}
/**
- * Helper method for implementing {@link Message#hashCode()} for
- * booleans.
+ * Helper method for implementing {@link Message#hashCode()} for booleans.
+ *
* @see Boolean#hashCode()
*/
public static int hashBoolean(boolean b) {
@@ -253,19 +236,16 @@ public final class Internal {
/**
* Helper method for implementing {@link Message#hashCode()} for enums.
- * <p>
- * This is needed because {@link java.lang.Enum#hashCode()} is final, but we
- * need to use the field number as the hash code to ensure compatibility
- * between statically and dynamically generated enum objects.
+ *
+ * <p>This is needed because {@link java.lang.Enum#hashCode()} is final, but we need to use the
+ * field number as the hash code to ensure compatibility between statically and dynamically
+ * generated enum objects.
*/
public static int hashEnum(EnumLite e) {
return e.getNumber();
}
- /**
- * Helper method for implementing {@link Message#hashCode()} for
- * enum lists.
- */
+ /** Helper method for implementing {@link Message#hashCode()} for enum lists. */
public static int hashEnumList(List<? extends EnumLite> list) {
int hash = 1;
for (EnumLite e : list) {
@@ -274,9 +254,7 @@ public final class Internal {
return hash;
}
- /**
- * Helper method for implementing {@link Message#equals(Object)} for bytes field.
- */
+ /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */
public static boolean equals(List<byte[]> a, List<byte[]> b) {
if (a.size() != b.size()) return false;
for (int i = 0; i < a.size(); ++i) {
@@ -287,9 +265,7 @@ public final class Internal {
return true;
}
- /**
- * Helper method for implementing {@link Message#hashCode()} for bytes field.
- */
+ /** Helper method for implementing {@link Message#hashCode()} for bytes field. */
public static int hashCode(List<byte[]> list) {
int hash = 1;
for (byte[] bytes : list) {
@@ -298,9 +274,7 @@ public final class Internal {
return hash;
}
- /**
- * Helper method for implementing {@link Message#hashCode()} for bytes field.
- */
+ /** Helper method for implementing {@link Message#hashCode()} for bytes field. */
public static int hashCode(byte[] bytes) {
// The hash code for a byte array should be the same as the hash code for a
// ByteString with the same content. This is to ensure that the generated
@@ -308,10 +282,8 @@ public final class Internal {
// based hashCode() method.
return Internal.hashCode(bytes, 0, bytes.length);
}
-
- /**
- * Helper method for implementing {@link LiteralByteString#hashCode()}.
- */
+
+ /** Helper method for implementing {@link LiteralByteString#hashCode()}. */
static int hashCode(byte[] bytes, int offset, int length) {
// The hash code for a byte array should be the same as the hash code for a
// ByteString with the same content. This is to ensure that the generated
@@ -321,20 +293,15 @@ public final class Internal {
return h == 0 ? 1 : h;
}
- /**
- * Helper method for continuously hashing bytes.
- */
+ /** Helper method for continuously hashing bytes. */
static int partialHash(int h, byte[] bytes, int offset, int length) {
for (int i = offset; i < offset + length; i++) {
h = h * 31 + bytes[i];
}
return h;
}
-
- /**
- * Helper method for implementing {@link Message#equals(Object)} for bytes
- * field.
- */
+
+ /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */
public static boolean equalsByteBuffer(ByteBuffer a, ByteBuffer b) {
if (a.capacity() != b.capacity()) {
return false;
@@ -344,12 +311,8 @@ public final class Internal {
return a.duplicate().clear().equals(b.duplicate().clear());
}
- /**
- * Helper method for implementing {@link Message#equals(Object)} for bytes
- * field.
- */
- public static boolean equalsByteBuffer(
- List<ByteBuffer> a, List<ByteBuffer> b) {
+ /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */
+ public static boolean equalsByteBuffer(List<ByteBuffer> a, List<ByteBuffer> b) {
if (a.size() != b.size()) {
return false;
}
@@ -361,10 +324,7 @@ public final class Internal {
return true;
}
- /**
- * Helper method for implementing {@link Message#hashCode()} for bytes
- * field.
- */
+ /** Helper method for implementing {@link Message#hashCode()} for bytes field. */
public static int hashCodeByteBuffer(List<ByteBuffer> list) {
int hash = 1;
for (ByteBuffer bytes : list) {
@@ -375,10 +335,7 @@ public final class Internal {
private static final int DEFAULT_BUFFER_SIZE = 4096;
- /**
- * Helper method for implementing {@link Message#hashCode()} for bytes
- * field.
- */
+ /** Helper method for implementing {@link Message#hashCode()} for bytes field. */
public static int hashCodeByteBuffer(ByteBuffer bytes) {
if (bytes.hasArray()) {
// Fast path.
@@ -387,15 +344,15 @@ public final class Internal {
} else {
// Read the data into a temporary byte array before calculating the
// hash value.
- final int bufferSize = bytes.capacity() > DEFAULT_BUFFER_SIZE
- ? DEFAULT_BUFFER_SIZE : bytes.capacity();
+ final int bufferSize =
+ bytes.capacity() > DEFAULT_BUFFER_SIZE ? DEFAULT_BUFFER_SIZE : bytes.capacity();
final byte[] buffer = new byte[bufferSize];
final ByteBuffer duplicated = bytes.duplicate();
duplicated.clear();
int h = bytes.capacity();
while (duplicated.remaining() > 0) {
- final int length = duplicated.remaining() <= bufferSize ?
- duplicated.remaining() : bufferSize;
+ final int length =
+ duplicated.remaining() <= bufferSize ? duplicated.remaining() : bufferSize;
duplicated.get(buffer, 0, length);
h = partialHash(h, buffer, 0, length);
}
@@ -409,8 +366,7 @@ public final class Internal {
Method method = clazz.getMethod("getDefaultInstance");
return (T) method.invoke(method);
} catch (Exception e) {
- throw new RuntimeException(
- "Failed to get default instance for " + clazz, e);
+ throw new RuntimeException("Failed to get default instance for " + clazz, e);
}
}
@@ -418,11 +374,8 @@ public final class Internal {
/** An empty byte array constant used in generated code. */
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
- /**
- * An empty byte array constant used in generated code.
- */
- public static final ByteBuffer EMPTY_BYTE_BUFFER =
- ByteBuffer.wrap(EMPTY_BYTE_ARRAY);
+ /** An empty byte array constant used in generated code. */
+ public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(EMPTY_BYTE_ARRAY);
/** An empty coded input stream constant used in generated code. */
public static final CodedInputStream EMPTY_CODED_INPUT_STREAM =
@@ -437,12 +390,10 @@ public final class Internal {
/**
* Provides an immutable view of {@code List<T>} around a {@code List<F>}.
*
- * Protobuf internal. Used in protobuf generated code only.
+ * <p>Protobuf internal. Used in protobuf generated code only.
*/
public static class ListAdapter<F, T> extends AbstractList<T> {
- /**
- * Convert individual elements of the List from F to T.
- */
+ /** Convert individual elements of the List from F to T. */
public interface Converter<F, T> {
T convert(F from);
}
@@ -466,16 +417,12 @@ public final class Internal {
}
}
- /**
- * Wrap around a {@code Map<K, RealValue>} and provide a {@code Map<K, V>}
- * interface.
- */
+ /** Wrap around a {@code Map<K, RealValue>} and provide a {@code Map<K, V>} interface. */
public static class MapAdapter<K, V, RealValue> extends AbstractMap<K, V> {
- /**
- * An interface used to convert between two types.
- */
+ /** An interface used to convert between two types. */
public interface Converter<A, B> {
B doForward(A object);
+
A doBackward(B object);
}
@@ -498,8 +445,7 @@ public final class Internal {
private final Map<K, RealValue> realMap;
private final Converter<RealValue, V> valueConverter;
- public MapAdapter(Map<K, RealValue> realMap,
- Converter<RealValue, V> valueConverter) {
+ public MapAdapter(Map<K, RealValue> realMap, Converter<RealValue, V> valueConverter) {
this.realMap = realMap;
this.valueConverter = valueConverter;
}
@@ -530,6 +476,7 @@ public final class Internal {
private class SetAdapter extends AbstractSet<Map.Entry<K, V>> {
private final Set<Map.Entry<K, RealValue>> realSet;
+
public SetAdapter(Set<Map.Entry<K, RealValue>> realSet) {
this.realSet = realSet;
}
@@ -548,8 +495,7 @@ public final class Internal {
private class IteratorAdapter implements Iterator<Map.Entry<K, V>> {
private final Iterator<Map.Entry<K, RealValue>> realIterator;
- public IteratorAdapter(
- Iterator<Map.Entry<K, RealValue>> realIterator) {
+ public IteratorAdapter(Iterator<Map.Entry<K, RealValue>> realIterator) {
this.realIterator = realIterator;
}
@@ -588,8 +534,7 @@ public final class Internal {
@Override
public V setValue(V value) {
- RealValue oldValue = realEntry.setValue(
- valueConverter.doBackward(value));
+ RealValue oldValue = realEntry.setValue(valueConverter.doBackward(value));
if (oldValue == null) {
return null;
}
@@ -601,14 +546,14 @@ public final class Internal {
/**
* Extends {@link List} to add the capability to make the list immutable and inspect if it is
* modifiable.
- * <p>
- * All implementations must support efficient random access.
+ *
+ * <p>All implementations must support efficient random access.
*/
public static interface ProtobufList<E> extends List<E>, RandomAccess {
/**
- * Makes this list immutable. All subsequent modifications will throw an
- * {@link UnsupportedOperationException}.
+ * Makes this list immutable. All subsequent modifications will throw an {@link
+ * UnsupportedOperationException}.
*/
void makeImmutable();
@@ -617,9 +562,7 @@ public final class Internal {
*/
boolean isModifiable();
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
ProtobufList<E> mutableCopyWithCapacity(int capacity);
}
@@ -629,24 +572,16 @@ public final class Internal {
*/
public static interface IntList extends ProtobufList<Integer> {
- /**
- * Like {@link #get(int)} but more efficient in that it doesn't box the returned value.
- */
+ /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */
int getInt(int index);
- /**
- * Like {@link #add(Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */
void addInt(int element);
- /**
- * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
int setInt(int index, int element);
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
@Override
IntList mutableCopyWithCapacity(int capacity);
}
@@ -657,52 +592,36 @@ public final class Internal {
*/
public static interface BooleanList extends ProtobufList<Boolean> {
- /**
- * Like {@link #get(int)} but more efficient in that it doesn't box the returned value.
- */
+ /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */
boolean getBoolean(int index);
- /**
- * Like {@link #add(Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */
void addBoolean(boolean element);
- /**
- * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
boolean setBoolean(int index, boolean element);
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
@Override
BooleanList mutableCopyWithCapacity(int capacity);
}
/**
- * A {@link java.util.List} implementation that avoids boxing the elements into Longs if
- * possible. Does not support null elements.
+ * A {@link java.util.List} implementation that avoids boxing the elements into Longs if possible.
+ * Does not support null elements.
*/
public static interface LongList extends ProtobufList<Long> {
- /**
- * Like {@link #get(int)} but more efficient in that it doesn't box the returned value.
- */
+ /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */
long getLong(int index);
- /**
- * Like {@link #add(Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */
void addLong(long element);
- /**
- * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
long setLong(int index, long element);
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
@Override
LongList mutableCopyWithCapacity(int capacity);
}
@@ -713,24 +632,16 @@ public final class Internal {
*/
public static interface DoubleList extends ProtobufList<Double> {
- /**
- * Like {@link #get(int)} but more efficient in that it doesn't box the returned value.
- */
+ /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */
double getDouble(int index);
- /**
- * Like {@link #add(Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */
void addDouble(double element);
- /**
- * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
double setDouble(int index, double element);
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
@Override
DoubleList mutableCopyWithCapacity(int capacity);
}
@@ -741,24 +652,16 @@ public final class Internal {
*/
public static interface FloatList extends ProtobufList<Float> {
- /**
- * Like {@link #get(int)} but more efficient in that it doesn't box the returned value.
- */
+ /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */
float getFloat(int index);
- /**
- * Like {@link #add(Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */
void addFloat(float element);
- /**
- * Like {@link #set(int, Object)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */
float setFloat(int index, float element);
- /**
- * Returns a mutable clone of this list with the specified capacity.
- */
+ /** Returns a mutable clone of this list with the specified capacity. */
@Override
FloatList mutableCopyWithCapacity(int capacity);
}
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 510c6aac..22f31bbc 100644
--- a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
+++ b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
@@ -33,8 +33,8 @@ package com.google.protobuf;
import java.io.IOException;
/**
- * Thrown when a protocol message being parsed is invalid in some way,
- * e.g. it contains a malformed varint or a negative byte length.
+ * Thrown when a protocol message being parsed is invalid in some way, e.g. it contains a malformed
+ * varint or a negative byte length.
*
* @author kenton@google.com Kenton Varda
*/
@@ -55,28 +55,26 @@ public class InvalidProtocolBufferException extends IOException {
}
/**
- * Attaches an unfinished message to the exception to support best-effort
- * parsing in {@code Parser} interface.
+ * Attaches an unfinished message to the exception to support best-effort parsing in {@code
+ * Parser} interface.
*
* @return this
*/
- public InvalidProtocolBufferException setUnfinishedMessage(
- MessageLite unfinishedMessage) {
+ public InvalidProtocolBufferException setUnfinishedMessage(MessageLite unfinishedMessage) {
this.unfinishedMessage = unfinishedMessage;
return this;
}
/**
- * Returns the unfinished message attached to the exception, or null if
- * no message is attached.
+ * Returns the unfinished message attached to the exception, or null if no message is attached.
*/
public MessageLite getUnfinishedMessage() {
return unfinishedMessage;
}
/**
- * Unwraps the underlying {@link IOException} if this exception was caused by an I/O
- * problem. Otherwise, returns {@code this}.
+ * Unwraps the underlying {@link IOException} if this exception was caused by an I/O problem.
+ * Otherwise, returns {@code this}.
*/
public IOException unwrapIOException() {
return getCause() instanceof IOException ? (IOException) getCause() : this;
@@ -84,41 +82,36 @@ public class InvalidProtocolBufferException extends IOException {
static InvalidProtocolBufferException truncatedMessage() {
return new InvalidProtocolBufferException(
- "While parsing a protocol message, the input ended unexpectedly " +
- "in the middle of a field. This could mean either that the " +
- "input has been truncated or that an embedded message " +
- "misreported its own length.");
+ "While parsing a protocol message, the input ended unexpectedly "
+ + "in the middle of a field. This could mean either that the "
+ + "input has been truncated or that an embedded message "
+ + "misreported its own length.");
}
static InvalidProtocolBufferException negativeSize() {
return new InvalidProtocolBufferException(
- "CodedInputStream encountered an embedded string or message " +
- "which claimed to have negative size.");
+ "CodedInputStream encountered an embedded string or message "
+ + "which claimed to have negative size.");
}
static InvalidProtocolBufferException malformedVarint() {
- return new InvalidProtocolBufferException(
- "CodedInputStream encountered a malformed varint.");
+ return new InvalidProtocolBufferException("CodedInputStream encountered a malformed varint.");
}
static InvalidProtocolBufferException invalidTag() {
- return new InvalidProtocolBufferException(
- "Protocol message contained an invalid tag (zero).");
+ return new InvalidProtocolBufferException("Protocol message contained an invalid tag (zero).");
}
static InvalidProtocolBufferException invalidEndTag() {
return new InvalidProtocolBufferException(
- "Protocol message end-group tag did not match expected tag.");
+ "Protocol message end-group tag did not match expected tag.");
}
static InvalidWireTypeException invalidWireType() {
- return new InvalidWireTypeException(
- "Protocol message tag had invalid wire type.");
+ return new InvalidWireTypeException("Protocol message tag had invalid wire type.");
}
- /**
- * Exception indicating that and unexpected wire type was encountered for a field.
- */
+ /** Exception indicating that and unexpected wire type was encountered for a field. */
@ExperimentalApi
public static class InvalidWireTypeException extends InvalidProtocolBufferException {
private static final long serialVersionUID = 3283890091615336259L;
@@ -130,14 +123,14 @@ public class InvalidProtocolBufferException extends IOException {
static InvalidProtocolBufferException recursionLimitExceeded() {
return new InvalidProtocolBufferException(
- "Protocol message had too many levels of nesting. May be malicious. " +
- "Use CodedInputStream.setRecursionLimit() to increase the depth limit.");
+ "Protocol message had too many levels of nesting. May be malicious. "
+ + "Use CodedInputStream.setRecursionLimit() to increase the depth limit.");
}
static InvalidProtocolBufferException sizeLimitExceeded() {
return new InvalidProtocolBufferException(
- "Protocol message was too large. May be malicious. " +
- "Use CodedInputStream.setSizeLimit() to increase the size limit.");
+ "Protocol message was too large. May be malicious. "
+ + "Use CodedInputStream.setSizeLimit() to increase the size limit.");
}
static InvalidProtocolBufferException parseFailure() {
diff --git a/java/core/src/main/java/com/google/protobuf/LazyField.java b/java/core/src/main/java/com/google/protobuf/LazyField.java
index 98e13ca1..891171d7 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyField.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyField.java
@@ -34,12 +34,12 @@ import java.util.Iterator;
import java.util.Map.Entry;
/**
- * LazyField encapsulates the logic of lazily parsing message fields. It stores
- * the message in a ByteString initially and then parse it on-demand.
+ * LazyField encapsulates the logic of lazily parsing message fields. It stores the message in a
+ * ByteString initially and then parse it on-demand.
*
- * Most of key methods are implemented in {@link LazyFieldLite} but this class
- * can contain default instance of the message to provide {@code hashCode()},
- * {@code euqals()} and {@code toString()}.
+ * <p>Most of key methods are implemented in {@link LazyFieldLite} but this class can contain
+ * default instance of the message to provide {@code hashCode()}, {@code euqals()} and {@code
+ * toString()}.
*
* @author xiangl@google.com (Xiang Li)
*/
@@ -51,8 +51,8 @@ public class LazyField extends LazyFieldLite {
*/
private final MessageLite defaultInstance;
- public LazyField(MessageLite defaultInstance,
- ExtensionRegistryLite extensionRegistry, ByteString bytes) {
+ public LazyField(
+ MessageLite defaultInstance, ExtensionRegistryLite extensionRegistry, ByteString bytes) {
super(extensionRegistry, bytes);
this.defaultInstance = defaultInstance;
@@ -85,8 +85,8 @@ public class LazyField extends LazyFieldLite {
// ====================================================
/**
- * LazyEntry and LazyIterator are used to encapsulate the LazyField, when
- * users iterate all fields from FieldSet.
+ * LazyEntry and LazyIterator are used to encapsulate the LazyField, when users iterate all fields
+ * from FieldSet.
*/
static class LazyEntry<K> implements Entry<K, Object> {
private Entry<K, LazyField> entry;
@@ -118,7 +118,7 @@ public class LazyField extends LazyFieldLite {
if (!(value instanceof MessageLite)) {
throw new IllegalArgumentException(
"LazyField now only used for MessageSet, "
- + "and the value of MessageSet must be an instance of MessageLite");
+ + "and the value of MessageSet must be an instance of MessageLite");
}
return entry.getValue().setValue((MessageLite) value);
}
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 49ecfc0b..5651e131 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyFieldLite.java
@@ -33,23 +33,23 @@ package com.google.protobuf;
import java.io.IOException;
/**
- * LazyFieldLite encapsulates the logic of lazily parsing message fields. It stores
- * the message in a ByteString initially and then parses it on-demand.
+ * LazyFieldLite encapsulates the logic of lazily parsing message fields. It stores the message in a
+ * ByteString initially and then parses it on-demand.
*
- * LazyFieldLite is thread-compatible: concurrent reads are safe once the proto that this
+ * <p>LazyFieldLite is thread-compatible: concurrent reads are safe once the proto that this
* LazyFieldLite is a part of is no longer being mutated by its Builder. However, explicit
* synchronization is needed under read/write situations.
*
- * When a LazyFieldLite is used in the context of a MessageLite object, its behavior is considered
- * to be immutable and none of the setter methods in its API are expected to be invoked. All of the
- * getters are expected to be thread-safe. When used in the context of a MessageLite.Builder,
- * setters can be invoked, but there is no guarantee of thread safety.
- *
- * TODO(yatin,dweis): Consider splitting this class's functionality and put the mutable methods
+ * <p>When a LazyFieldLite is used in the context of a MessageLite object, its behavior is
+ * considered to be immutable and none of the setter methods in its API are expected to be invoked.
+ * All of the getters are expected to be thread-safe. When used in the context of a
+ * MessageLite.Builder, setters can be invoked, but there is no guarantee of thread safety.
+ *
+ * <p>TODO(yatin,dweis): Consider splitting this class's functionality and put the mutable methods
* into a separate builder class to allow us to give stronger compile-time guarantees.
*
- * This class is internal implementation detail of the protobuf library, so you don't need to use it
- * directly.
+ * <p>This class is internal implementation detail of the protobuf library, so you don't need to use
+ * it directly.
*
* @author xiangl@google.com (Xiang Li)
*/
@@ -57,23 +57,27 @@ public class LazyFieldLite {
private static final ExtensionRegistryLite EMPTY_REGISTRY =
ExtensionRegistryLite.getEmptyRegistry();
- /**
+ /*
* The value associated with the LazyFieldLite object is stored in one or more of the following
* three fields (delayedBytes, value, memoizedBytes). They should together be interpreted as
* follows.
+ *
* 1) delayedBytes can be non-null, while value and memoizedBytes is null. The object will be in
- * this state while the value for the object has not yet been parsed.
+ * this state while the value for the object has not yet been parsed.
+ *
* 2) Both delayedBytes and value are non-null. The object transitions to this state as soon as
- * some caller needs to access the value (by invoking getValue()).
+ * some caller needs to access the value (by invoking getValue()).
+ *
* 3) memoizedBytes is merely an optimization for calls to LazyFieldLite.toByteString() to avoid
- * recomputing the ByteString representation on each call. Instead, when the value is parsed
- * from delayedBytes, we will also assign the contents of delayedBytes to memoizedBytes (since
- * that is the ByteString representation of value).
+ * recomputing the ByteString representation on each call. Instead, when the value is parsed from
+ * delayedBytes, we will also assign the contents of delayedBytes to memoizedBytes (since that is
+ * the ByteString representation of value).
+ *
* 4) Finally, if the LazyFieldLite was created directly with a parsed MessageLite value, then
- * delayedBytes will be null, and memoizedBytes will be initialized only upon the first call to
- * LazyFieldLite.toByteString().
+ * delayedBytes will be null, and memoizedBytes will be initialized only upon the first call to
+ * LazyFieldLite.toByteString().
*
- * Given the above conditions, any caller that needs a serialized representation of this object
+ * <p>Given the above conditions, any caller that needs a serialized representation of this object
* must first check if the memoizedBytes or delayedBytes ByteString is non-null and use it
* directly; if both of those are null, it can look at the parsed value field. Similarly, any
* caller that needs a parsed value must first check if the value field is already non-null, if
@@ -84,16 +88,16 @@ public class LazyFieldLite {
* A delayed-parsed version of the contents of this field. When this field is non-null, then the
* "value" field is allowed to be null until the time that the value needs to be read.
*
- * When delayedBytes is non-null then {@code extensionRegistry} is required to also be non-null.
- * {@code value} and {@code memoizedBytes} will be initialized lazily.
+ * <p>When delayedBytes is non-null then {@code extensionRegistry} is required to also be
+ * non-null. {@code value} and {@code memoizedBytes} will be initialized lazily.
*/
private ByteString delayedBytes;
/**
* An {@code ExtensionRegistryLite} for parsing bytes. It is non-null on a best-effort basis. It
- * is only guaranteed to be non-null if this message was initialized using bytes and an
- * {@code ExtensionRegistry}. If it directly had a value set then it will be null, unless it has
- * been merged with another {@code LazyFieldLite} that had an {@code ExtensionRegistry}.
+ * is only guaranteed to be non-null if this message was initialized using bytes and an {@code
+ * ExtensionRegistry}. If it directly had a value set then it will be null, unless it has been
+ * merged with another {@code LazyFieldLite} that had an {@code ExtensionRegistry}.
*/
private ExtensionRegistryLite extensionRegistry;
@@ -105,25 +109,20 @@ public class LazyFieldLite {
/**
* The memoized bytes for {@code value}. This is an optimization for the toByteString() method to
- * not have to recompute its return-value on each invocation.
- * TODO(yatin): Figure out whether this optimization is actually necessary.
+ * not have to recompute its return-value on each invocation. TODO(yatin): Figure out whether this
+ * optimization is actually necessary.
*/
private volatile ByteString memoizedBytes;
- /**
- * Constructs a LazyFieldLite with bytes that will be parsed lazily.
- */
+ /** Constructs a LazyFieldLite with bytes that will be parsed lazily. */
public LazyFieldLite(ExtensionRegistryLite extensionRegistry, ByteString bytes) {
checkArguments(extensionRegistry, bytes);
this.extensionRegistry = extensionRegistry;
this.delayedBytes = bytes;
}
- /**
- * Constructs a LazyFieldLite with no contents, and no ability to parse extensions.
- */
- public LazyFieldLite() {
- }
+ /** Constructs a LazyFieldLite with no contents, and no ability to parse extensions. */
+ public LazyFieldLite() {}
/**
* Constructs a LazyFieldLite instance with a value. The LazyFieldLite may not be able to parse
@@ -140,13 +139,13 @@ public class LazyFieldLite {
if (this == o) {
return true;
}
-
+
if (!(o instanceof LazyFieldLite)) {
return false;
}
LazyFieldLite other = (LazyFieldLite) o;
-
+
// Lazy fields do not work well with equals... If both are delayedBytes, we do not have a
// mechanism to deserialize them so we rely on bytes equality. Otherwise we coerce into an
// actual message (if necessary) and call equals on the message itself. This implies that two
@@ -163,7 +162,7 @@ public class LazyFieldLite {
return getValue(value2.getDefaultInstanceForType()).equals(value2);
}
}
-
+
@Override
public int hashCode() {
// We can't provide a memoizable hash code for lazy fields. The byte strings may have different
@@ -171,7 +170,7 @@ public class LazyFieldLite {
// a message here if we were not already holding a value.
return 1;
}
-
+
/**
* Determines whether this LazyFieldLite instance represents the default instance of this type.
*/
@@ -183,8 +182,8 @@ public class LazyFieldLite {
/**
* Clears the value state of this instance.
*
- * <p>LazyField is not thread-safe for write access. Synchronizations are needed
- * under read/write situations.
+ * <p>LazyField is not thread-safe for write access. Synchronizations are needed under read/write
+ * situations.
*/
public void clear() {
// Don't clear the ExtensionRegistry. It might prove useful later on when merging in another
@@ -198,8 +197,8 @@ public class LazyFieldLite {
/**
* Overrides the contents of this LazyField.
*
- * <p>LazyField is not thread-safe for write access. Synchronizations are needed
- * under read/write situations.
+ * <p>LazyField is not thread-safe for write access. Synchronizations are needed under read/write
+ * situations.
*/
public void set(LazyFieldLite other) {
this.delayedBytes = other.delayedBytes;
@@ -218,7 +217,7 @@ public class LazyFieldLite {
* Returns message instance. It may do some thread-safe delayed parsing of bytes.
*
* @param defaultInstance its message's default instance. It's also used to get parser for the
- * message type.
+ * message type.
*/
public MessageLite getValue(MessageLite defaultInstance) {
ensureInitialized(defaultInstance);
@@ -228,8 +227,8 @@ public class LazyFieldLite {
/**
* Sets the value of the instance and returns the old value without delay parsing anything.
*
- * <p>LazyField is not thread-safe for write access. Synchronizations are needed
- * under read/write situations.
+ * <p>LazyField is not thread-safe for write access. Synchronizations are needed under read/write
+ * situations.
*/
public MessageLite setValue(MessageLite value) {
MessageLite originalValue = this.value;
@@ -244,8 +243,8 @@ public class LazyFieldLite {
* contain data. If the other field has an {@code ExtensionRegistry} but this does not, then this
* field will copy over that {@code ExtensionRegistry}.
*
- * <p>LazyField is not thread-safe for write access. Synchronizations are needed
- * under read/write situations.
+ * <p>LazyField is not thread-safe for write access. Synchronizations are needed under read/write
+ * situations.
*/
public void merge(LazyFieldLite other) {
if (other.containsDefaultInstance()) {
@@ -287,12 +286,12 @@ public class LazyFieldLite {
// At this point we have two fully parsed messages.
setValue(this.value.toBuilder().mergeFrom(other.value).build());
}
-
+
/**
* Merges another instance's contents from a stream.
*
- * <p>LazyField is not thread-safe for write access. Synchronizations are needed
- * under read/write situations.
+ * <p>LazyField is not thread-safe for write access. Synchronizations are needed under read/write
+ * situations.
*/
public void mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException {
@@ -339,9 +338,7 @@ public class LazyFieldLite {
}
}
- /**
- * Sets this field with bytes to delay-parse.
- */
+ /** Sets this field with bytes to delay-parse. */
public void setByteString(ByteString bytes, ExtensionRegistryLite extensionRegistry) {
checkArguments(extensionRegistry, bytes);
this.delayedBytes = bytes;
@@ -351,9 +348,8 @@ public class LazyFieldLite {
}
/**
- * Due to the optional field can be duplicated at the end of serialized
- * bytes, which will make the serialized size changed after LazyField
- * parsed. Be careful when using this method.
+ * Due to the optional field can be duplicated at the end of serialized bytes, which will make the
+ * serialized size changed after LazyField parsed. Be careful when using this method.
*/
public int getSerializedSize() {
// We *must* return delayed bytes size if it was ever set because the dependent messages may
@@ -369,9 +365,7 @@ public class LazyFieldLite {
}
}
- /**
- * Returns a BytesString for this field in a thread-safe way.
- */
+ /** Returns a BytesString for this field in a thread-safe way. */
public ByteString toByteString() {
if (memoizedBytes != null) {
return memoizedBytes;
@@ -395,9 +389,7 @@ public class LazyFieldLite {
}
- /**
- * Might lazily parse the bytes that were previously passed in. Is thread-safe.
- */
+ /** Might lazily parse the bytes that were previously passed in. Is thread-safe. */
protected void ensureInitialized(MessageLite defaultInstance) {
if (value != null) {
return;
@@ -409,8 +401,8 @@ public class LazyFieldLite {
try {
if (delayedBytes != null) {
// The extensionRegistry shouldn't be null here since we have delayedBytes.
- MessageLite parsedValue = defaultInstance.getParserForType()
- .parseFrom(delayedBytes, extensionRegistry);
+ MessageLite parsedValue =
+ defaultInstance.getParserForType().parseFrom(delayedBytes, extensionRegistry);
this.value = parsedValue;
this.memoizedBytes = delayedBytes;
} else {
@@ -426,7 +418,6 @@ public class LazyFieldLite {
}
}
-
private static void checkArguments(ExtensionRegistryLite extensionRegistry, ByteString bytes) {
if (extensionRegistry == null) {
throw new NullPointerException("found null ExtensionRegistry");
diff --git a/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java b/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java
index d474c51e..a2de6f9c 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyStringArrayList.java
@@ -39,26 +39,22 @@ import java.util.List;
import java.util.RandomAccess;
/**
- * An implementation of {@link LazyStringList} that wraps an ArrayList. Each
- * element is one of String, ByteString, or byte[]. It caches the last one
- * requested which is most likely the one needed next. This minimizes memory
- * usage while satisfying the most common use cases.
- * <p>
- * <strong>Note that this implementation is not synchronized.</strong>
- * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
- * and at least one of the threads modifies the list structurally, it
- * <i>must</i> be synchronized externally. (A structural modification is
- * any operation that adds or deletes one or more elements, or explicitly
- * resizes the backing array; merely setting the value of an element is not
- * a structural modification.) This is typically accomplished by
- * synchronizing on some object that naturally encapsulates the list.
- * <p>
- * If the implementation is accessed via concurrent reads, this is thread safe.
- * Conversions are done in a thread safe manner. It's possible that the
- * conversion may happen more than once if two threads attempt to access the
- * same element and the modifications were not visible to each other, but this
- * will not result in any corruption of the list or change in behavior other
- * than performance.
+ * An implementation of {@link LazyStringList} that wraps an ArrayList. Each element is one of
+ * String, ByteString, or byte[]. It caches the last one requested which is most likely the one
+ * needed next. This minimizes memory usage while satisfying the most common use cases.
+ *
+ * <p><strong>Note that this implementation is not synchronized.</strong> If multiple threads access
+ * an <tt>ArrayList</tt> instance concurrently, and at least one of the threads modifies the list
+ * structurally, it <i>must</i> be synchronized externally. (A structural modification is any
+ * operation that adds or deletes one or more elements, or explicitly resizes the backing array;
+ * merely setting the value of an element is not a structural modification.) This is typically
+ * accomplished by synchronizing on some object that naturally encapsulates the list.
+ *
+ * <p>If the implementation is accessed via concurrent reads, this is thread safe. Conversions are
+ * done in a thread safe manner. It's possible that the conversion may happen more than once if two
+ * threads attempt to access the same element and the modifications were not visible to each other,
+ * but this will not result in any corruption of the list or change in behavior other than
+ * performance.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -66,10 +62,11 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
implements LazyStringList, RandomAccess {
private static final LazyStringArrayList EMPTY_LIST = new LazyStringArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
-
+
static LazyStringArrayList emptyList() {
return EMPTY_LIST;
}
@@ -83,8 +80,8 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
this(DEFAULT_CAPACITY);
}
- public LazyStringArrayList(int intialCapacity) {
- this(new ArrayList<Object>(intialCapacity));
+ public LazyStringArrayList(int initialCapacity) {
+ this(new ArrayList<Object>(initialCapacity));
}
public LazyStringArrayList(LazyStringList from) {
@@ -95,7 +92,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
public LazyStringArrayList(List<String> from) {
this(new ArrayList<Object>(from));
}
-
+
private LazyStringArrayList(ArrayList<Object> list) {
this.list = list;
}
@@ -150,13 +147,13 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
list.add(index, element);
modCount++;
}
-
+
private void add(int index, ByteString element) {
ensureIsMutable();
list.add(index, element);
modCount++;
}
-
+
private void add(int index, byte[] element) {
ensureIsMutable();
list.add(index, element);
@@ -177,8 +174,8 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
ensureIsMutable();
// When copying from another LazyStringList, directly copy the underlying
// elements rather than forcing each element to be decoded to a String.
- Collection<?> collection = c instanceof LazyStringList
- ? ((LazyStringList) c).getUnderlyingElements() : c;
+ Collection<?> collection =
+ c instanceof LazyStringList ? ((LazyStringList) c).getUnderlyingElements() : c;
boolean ret = list.addAll(index, collection);
modCount++;
return ret;
@@ -221,7 +218,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
list.add(element);
modCount++;
}
-
+
@Override
public void add(byte[] element) {
ensureIsMutable();
@@ -233,7 +230,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
public Object getRaw(int index) {
return list.get(index);
}
-
+
@Override
public ByteString getByteString(int index) {
Object o = list.get(index);
@@ -243,7 +240,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
}
return b;
}
-
+
@Override
public byte[] getByteArray(int index) {
Object o = list.get(index);
@@ -258,7 +255,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
public void set(int index, ByteString s) {
setAndReturn(index, s);
}
-
+
private Object setAndReturn(int index, ByteString s) {
ensureIsMutable();
return list.set(index, s);
@@ -268,7 +265,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
public void set(int index, byte[] s) {
setAndReturn(index, s);
}
-
+
private Object setAndReturn(int index, byte[] s) {
ensureIsMutable();
return list.set(index, s);
@@ -283,7 +280,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
return Internal.toStringUtf8((byte[]) o);
}
}
-
+
private static ByteString asByteString(Object o) {
if (o instanceof ByteString) {
return (ByteString) o;
@@ -293,7 +290,7 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
return ByteString.copyFrom((byte[]) o);
}
}
-
+
private static byte[] asByteArray(Object o) {
if (o instanceof byte[]) {
return (byte[]) o;
@@ -324,14 +321,13 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
}
}
- private static class ByteArrayListView extends AbstractList<byte[]>
- implements RandomAccess {
+ private static class ByteArrayListView extends AbstractList<byte[]> implements RandomAccess {
private final LazyStringArrayList list;
-
+
ByteArrayListView(LazyStringArrayList list) {
this.list = list;
}
-
+
@Override
public byte[] get(int index) {
return list.getByteArray(index);
@@ -362,14 +358,13 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
return asByteArray(o);
}
}
-
+
@Override
public List<byte[]> asByteArrayList() {
return new ByteArrayListView(this);
}
- private static class ByteStringListView extends AbstractList<ByteString>
- implements RandomAccess {
+ private static class ByteStringListView extends AbstractList<ByteString> implements RandomAccess {
private final LazyStringArrayList list;
ByteStringListView(LazyStringArrayList list) {
@@ -419,5 +414,4 @@ public class LazyStringArrayList extends AbstractProtobufList<String>
}
return this;
}
-
}
diff --git a/java/core/src/main/java/com/google/protobuf/LazyStringList.java b/java/core/src/main/java/com/google/protobuf/LazyStringList.java
index 3eeedca1..6b55022c 100644
--- a/java/core/src/main/java/com/google/protobuf/LazyStringList.java
+++ b/java/core/src/main/java/com/google/protobuf/LazyStringList.java
@@ -34,14 +34,12 @@ import java.util.Collection;
import java.util.List;
/**
- * An interface extending {@code List<String>} that also provides access to the
- * items of the list as UTF8-encoded ByteString or byte[] objects. This is
- * used by the protocol buffer implementation to support lazily converting bytes
- * parsed over the wire to String objects until needed and also increases the
- * efficiency of serialization if the String was never requested as the
- * ByteString or byte[] is already cached. The ByteString methods are used in
- * immutable API only and byte[] methods used in mutable API only for they use
- * different representations for string/bytes fields.
+ * An interface extending {@code List<String>} that also provides access to the items of the list as
+ * UTF8-encoded ByteString or byte[] objects. This is used by the protocol buffer implementation to
+ * support lazily converting bytes parsed over the wire to String objects until needed and also
+ * increases the efficiency of serialization if the String was never requested as the ByteString or
+ * byte[] is already cached. The ByteString methods are used in immutable API only and byte[]
+ * methods used in mutable API only for they use different representations for string/bytes fields.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -52,19 +50,19 @@ public interface LazyStringList extends ProtocolStringList {
*
* @param index index of the element to return
* @return the element at the specified position in this list
- * @throws IndexOutOfBoundsException if the index is out of range
- * ({@code index < 0 || index >= size()})
+ * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >=
+ * size()})
*/
ByteString getByteString(int index);
/**
- * Returns the element at the specified position in this list as an Object
- * that will either be a String or a ByteString.
+ * Returns the element at the specified position in this list as an Object that will either be a
+ * String or a ByteString.
*
* @param index index of the element to return
* @return the element at the specified position in this list
- * @throws IndexOutOfBoundsException if the index is out of range
- * ({@code index < 0 || index >= size()})
+ * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >=
+ * size()})
*/
Object getRaw(int index);
@@ -73,99 +71,91 @@ public interface LazyStringList extends ProtocolStringList {
*
* @param index index of the element to return
* @return the element at the specified position in this list
- * @throws IndexOutOfBoundsException if the index is out of range
- * ({@code index < 0 || index >= size()})
+ * @throws IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >=
+ * size()})
*/
byte[] getByteArray(int index);
/**
- * Appends the specified element to the end of this list (optional
- * operation).
+ * Appends the specified element to the end of this list (optional operation).
*
* @param element element to be appended to this list
- * @throws UnsupportedOperationException if the <tt>add</tt> operation
- * is not supported by this list
+ * @throws UnsupportedOperationException if the <tt>add</tt> operation is not supported by this
+ * list
*/
void add(ByteString element);
/**
- * Appends the specified element to the end of this list (optional
- * operation).
+ * Appends the specified element to the end of this list (optional operation).
*
* @param element element to be appended to this list
- * @throws UnsupportedOperationException if the <tt>add</tt> operation
- * is not supported by this list
+ * @throws UnsupportedOperationException if the <tt>add</tt> operation is not supported by this
+ * list
*/
void add(byte[] element);
/**
- * Replaces the element at the specified position in this list with the
- * specified element (optional operation).
+ * Replaces the element at the specified position in this list with the specified element
+ * (optional operation).
*
* @param index index of the element to replace
* @param element the element to be stored at the specified position
- * @throws UnsupportedOperationException if the <tt>set</tt> operation
- * is not supported by this list
- * IndexOutOfBoundsException if the index is out of range
- * ({@code index < 0 || index >= size()})
+ * @throws UnsupportedOperationException if the <tt>set</tt> operation is not supported by this
+ * list IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >=
+ * size()})
*/
void set(int index, ByteString element);
-
+
/**
- * Replaces the element at the specified position in this list with the
- * specified element (optional operation).
+ * Replaces the element at the specified position in this list with the specified element
+ * (optional operation).
*
* @param index index of the element to replace
* @param element the element to be stored at the specified position
- * @throws UnsupportedOperationException if the <tt>set</tt> operation
- * is not supported by this list
- * IndexOutOfBoundsException if the index is out of range
- * ({@code index < 0 || index >= size()})
+ * @throws UnsupportedOperationException if the <tt>set</tt> operation is not supported by this
+ * list IndexOutOfBoundsException if the index is out of range ({@code index < 0 || index >=
+ * size()})
*/
void set(int index, byte[] element);
/**
- * Appends all elements in the specified ByteString collection to the end of
- * this list.
+ * Appends all elements in the specified ByteString collection to the end of this list.
*
* @param c collection whose elements are to be added to this list
* @return true if this list changed as a result of the call
- * @throws UnsupportedOperationException if the <tt>addAllByteString</tt>
- * operation is not supported by this list
+ * @throws UnsupportedOperationException if the <tt>addAllByteString</tt> operation is not
+ * supported by this list
*/
boolean addAllByteString(Collection<? extends ByteString> c);
/**
- * Appends all elements in the specified byte[] collection to the end of
- * this list.
+ * Appends all elements in the specified byte[] collection to the end of this list.
*
* @param c collection whose elements are to be added to this list
* @return true if this list changed as a result of the call
- * @throws UnsupportedOperationException if the <tt>addAllByteArray</tt>
- * operation is not supported by this list
+ * @throws UnsupportedOperationException if the <tt>addAllByteArray</tt> operation is not
+ * supported by this list
*/
boolean addAllByteArray(Collection<byte[]> c);
/**
- * Returns an unmodifiable List of the underlying elements, each of which is
- * either a {@code String} or its equivalent UTF-8 encoded {@code ByteString}
- * or byte[]. It is an error for the caller to modify the returned
- * List, and attempting to do so will result in an
- * {@link UnsupportedOperationException}.
+ * Returns an unmodifiable List of the underlying elements, each of which is either a {@code
+ * String} or its equivalent UTF-8 encoded {@code ByteString} or byte[]. It is an error for the
+ * caller to modify the returned List, and attempting to do so will result in an {@link
+ * UnsupportedOperationException}.
*/
List<?> getUnderlyingElements();
/**
- * Merges all elements from another LazyStringList into this one. This method
- * differs from {@link #addAll(Collection)} on that underlying byte arrays are
- * copied instead of reference shared. Immutable API doesn't need to use this
- * method as byte[] is not used there at all.
+ * Merges all elements from another LazyStringList into this one. This method differs from {@link
+ * #addAll(Collection)} on that underlying byte arrays are copied instead of reference shared.
+ * Immutable API doesn't need to use this method as byte[] is not used there at all.
*/
void mergeFrom(LazyStringList other);
/**
- * Returns a mutable view of this list. Changes to the view will be made into
- * the original list. This method is used in mutable API only.
+ * Returns a mutable view of this list. Changes to the view will be made into the original list.
+ * This method is used in mutable API only.
*/
List<byte[]> asByteArrayList();
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 95945cb7..8cdab121 100644
--- a/java/core/src/main/java/com/google/protobuf/LongArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/LongArrayList.java
@@ -46,6 +46,7 @@ final class LongArrayList extends AbstractProtobufList<Long>
implements LongList, RandomAccess, PrimitiveNonBoxingCollection {
private static final LongArrayList EMPTY_LIST = new LongArrayList();
+
static {
EMPTY_LIST.makeImmutable();
}
@@ -54,9 +55,7 @@ final class LongArrayList extends AbstractProtobufList<Long>
return EMPTY_LIST;
}
- /**
- * The backing store for the list.
- */
+ /** The backing store for the list. */
private long[] array;
/**
@@ -65,16 +64,13 @@ final class LongArrayList extends AbstractProtobufList<Long>
*/
private int size;
- /**
- * Constructs a new mutable {@code LongArrayList} with default capacity.
- */
+ /** Constructs a new mutable {@code LongArrayList} with default capacity. */
LongArrayList() {
this(new long[DEFAULT_CAPACITY], 0);
}
/**
- * Constructs a new mutable {@code LongArrayList}
- * containing the same elements as {@code other}.
+ * Constructs a new mutable {@code LongArrayList} containing the same elements as {@code other}.
*/
private LongArrayList(long[] other, int size) {
array = other;
@@ -168,17 +164,13 @@ final class LongArrayList extends AbstractProtobufList<Long>
addLong(index, element);
}
- /**
- * Like {@link #add(Long)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(Long)} but more efficient in that it doesn't box the element. */
@Override
public void addLong(long element) {
addLong(size, element);
}
- /**
- * Like {@link #add(int, Long)} but more efficient in that it doesn't box the element.
- */
+ /** Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. */
private void addLong(int index, long element) {
ensureIsMutable();
if (index < 0 || index > size) {
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 0849b821..01754522 100644
--- a/java/core/src/main/java/com/google/protobuf/MapEntry.java
+++ b/java/core/src/main/java/com/google/protobuf/MapEntry.java
@@ -41,11 +41,11 @@ import java.util.TreeMap;
/**
* Implements MapEntry messages.
*
- * In reflection API, map fields will be treated as repeated message fields and
- * each map entry is accessed as a message. This MapEntry class is used to
- * represent these map entry messages in reflection API.
+ * <p>In reflection API, map fields will be treated as repeated message fields and each map entry is
+ * accessed as a message. This MapEntry class is used to represent these map entry messages in
+ * reflection API.
*
- * Protobuf internal. Users shouldn't use this class.
+ * <p>Protobuf internal. Users shouldn't use this class.
*/
public final class MapEntry<K, V> extends AbstractMessage {
@@ -61,15 +61,16 @@ public final class MapEntry<K, V> extends AbstractMessage {
WireFormat.FieldType valueType) {
super(keyType, defaultInstance.key, valueType, defaultInstance.value);
this.descriptor = descriptor;
- this.parser = new AbstractParser<MapEntry<K, V>>() {
+ this.parser =
+ new AbstractParser<MapEntry<K, V>>() {
- @Override
- public MapEntry<K, V> parsePartialFrom(
- CodedInputStream input, ExtensionRegistryLite extensionRegistry)
- throws InvalidProtocolBufferException {
- return new MapEntry<K, V>(Metadata.this, input, extensionRegistry);
- }
- };
+ @Override
+ public MapEntry<K, V> parsePartialFrom(
+ CodedInputStream input, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException {
+ return new MapEntry<K, V>(Metadata.this, input, extensionRegistry);
+ }
+ };
}
}
@@ -80,8 +81,10 @@ public final class MapEntry<K, V> extends AbstractMessage {
/** Create a default MapEntry instance. */
private MapEntry(
Descriptor descriptor,
- WireFormat.FieldType keyType, K defaultKey,
- WireFormat.FieldType valueType, V defaultValue) {
+ WireFormat.FieldType keyType,
+ K defaultKey,
+ WireFormat.FieldType valueType,
+ V defaultValue) {
this.key = defaultKey;
this.value = defaultValue;
this.metadata = new Metadata<K, V>(descriptor, this, keyType, valueType);
@@ -97,9 +100,7 @@ public final class MapEntry<K, V> extends AbstractMessage {
/** Parsing constructor. */
private MapEntry(
- Metadata<K, V> metadata,
- CodedInputStream input,
- ExtensionRegistryLite extensionRegistry)
+ Metadata<K, V> metadata, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
try {
this.metadata = metadata;
@@ -114,17 +115,17 @@ public final class MapEntry<K, V> extends AbstractMessage {
}
/**
- * Create a default MapEntry instance. A default MapEntry instance should be
- * created only once for each map entry message type. Generated code should
- * store the created default instance and use it later to create new MapEntry
- * messages of the same type.
+ * Create a default MapEntry instance. A default MapEntry instance should be created only once for
+ * each map entry message type. Generated code should store the created default instance and use
+ * it later to create new MapEntry messages of the same type.
*/
public static <K, V> MapEntry<K, V> newDefaultInstance(
Descriptor descriptor,
- WireFormat.FieldType keyType, K defaultKey,
- WireFormat.FieldType valueType, V defaultValue) {
- return new MapEntry<K, V>(
- descriptor, keyType, defaultKey, valueType, defaultValue);
+ WireFormat.FieldType keyType,
+ K defaultKey,
+ WireFormat.FieldType valueType,
+ V defaultValue) {
+ return new MapEntry<K, V>(descriptor, keyType, defaultKey, valueType, defaultValue);
}
public K getKey() {
@@ -197,14 +198,17 @@ public final class MapEntry<K, V> extends AbstractMessage {
private void checkFieldDescriptor(FieldDescriptor field) {
if (field.getContainingType() != metadata.descriptor) {
throw new RuntimeException(
- "Wrong FieldDescriptor \"" + field.getFullName()
- + "\" used in message \"" + metadata.descriptor.getFullName());
+ "Wrong FieldDescriptor \""
+ + field.getFullName()
+ + "\" used in message \""
+ + metadata.descriptor.getFullName());
}
}
@Override
public boolean hasField(FieldDescriptor field) {
- checkFieldDescriptor(field);;
+ checkFieldDescriptor(field);
+ ;
// A MapEntry always contains two fields.
return true;
}
@@ -215,22 +219,19 @@ public final class MapEntry<K, V> extends AbstractMessage {
Object result = field.getNumber() == 1 ? getKey() : getValue();
// Convert enums to EnumValueDescriptor.
if (field.getType() == FieldDescriptor.Type.ENUM) {
- result = field.getEnumType().findValueByNumberCreatingIfUnknown(
- (java.lang.Integer) result);
+ result = field.getEnumType().findValueByNumberCreatingIfUnknown((java.lang.Integer) result);
}
return result;
}
@Override
public int getRepeatedFieldCount(FieldDescriptor field) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
public Object getRepeatedField(FieldDescriptor field, int index) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
@@ -238,11 +239,8 @@ public final class MapEntry<K, V> extends AbstractMessage {
return UnknownFieldSet.getDefaultInstance();
}
- /**
- * Builder to create {@link MapEntry} messages.
- */
- public static class Builder<K, V>
- extends AbstractMessage.Builder<Builder<K, V>> {
+ /** Builder to create {@link MapEntry} messages. */
+ public static class Builder<K, V> extends AbstractMessage.Builder<Builder<K, V>> {
private final Metadata<K, V> metadata;
private K key;
private V value;
@@ -315,20 +313,21 @@ public final class MapEntry<K, V> extends AbstractMessage {
private void checkFieldDescriptor(FieldDescriptor field) {
if (field.getContainingType() != metadata.descriptor) {
throw new RuntimeException(
- "Wrong FieldDescriptor \"" + field.getFullName()
- + "\" used in message \"" + metadata.descriptor.getFullName());
+ "Wrong FieldDescriptor \""
+ + field.getFullName()
+ + "\" used in message \""
+ + metadata.descriptor.getFullName());
}
}
@Override
public Message.Builder newBuilderForField(FieldDescriptor field) {
- checkFieldDescriptor(field);;
+ checkFieldDescriptor(field);
+ ;
// This method should be called for message fields and in a MapEntry
// message only the value field can possibly be a message field.
- if (field.getNumber() != 2
- || field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
- throw new RuntimeException(
- "\"" + field.getFullName() + "\" is not a message value field.");
+ if (field.getNumber() != 2 || field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
+ throw new RuntimeException("\"" + field.getFullName() + "\" is not a message value field.");
}
return ((Message) value).newBuilderForType();
}
@@ -369,16 +368,13 @@ public final class MapEntry<K, V> extends AbstractMessage {
}
@Override
- public Builder<K, V> setRepeatedField(FieldDescriptor field, int index,
- Object value) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ public Builder<K, V> setRepeatedField(FieldDescriptor field, int index, Object value) {
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
public Builder<K, V> addRepeatedField(FieldDescriptor field, Object value) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
@@ -427,14 +423,12 @@ public final class MapEntry<K, V> extends AbstractMessage {
@Override
public int getRepeatedFieldCount(FieldDescriptor field) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
public Object getRepeatedField(FieldDescriptor field, int index) {
- throw new RuntimeException(
- "There is no repeated field in a map entry message.");
+ throw new RuntimeException("There is no repeated field in a map entry message.");
}
@Override
@@ -455,7 +449,7 @@ 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 dcb5dfad..ca2a3c2a 100644
--- a/java/core/src/main/java/com/google/protobuf/MapEntryLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MapEntryLite.java
@@ -37,11 +37,10 @@ import java.util.Map;
/**
* Implements the lite version of map entry messages.
*
- * This class serves as an utility class to help do serialization/parsing of
- * map entries. It's used in generated code and also in the full version
- * MapEntry message.
+ * <p>This class serves as an utility class to help do serialization/parsing of map entries. It's
+ * used in generated code and also in the full version MapEntry message.
*
- * Protobuf internal. Users shouldn't use.
+ * <p>Protobuf internal. Users shouldn't use.
*/
public class MapEntryLite<K, V> {
@@ -52,8 +51,10 @@ public class MapEntryLite<K, V> {
public final V defaultValue;
public Metadata(
- WireFormat.FieldType keyType, K defaultKey,
- WireFormat.FieldType valueType, V defaultValue) {
+ WireFormat.FieldType keyType,
+ K defaultKey,
+ WireFormat.FieldType valueType,
+ V defaultValue) {
this.keyType = keyType;
this.defaultKey = defaultKey;
this.valueType = valueType;
@@ -70,8 +71,7 @@ public class MapEntryLite<K, V> {
/** Creates a default MapEntryLite message instance. */
private MapEntryLite(
- WireFormat.FieldType keyType, K defaultKey,
- WireFormat.FieldType valueType, V defaultValue) {
+ WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) {
this.metadata = new Metadata<K, V>(keyType, defaultKey, valueType, defaultValue);
this.key = defaultKey;
this.value = defaultValue;
@@ -95,16 +95,13 @@ public class MapEntryLite<K, V> {
/**
* Creates a default MapEntryLite message instance.
*
- * This method is used by generated code to create the default instance for
- * a map entry message. The created default instance should be used to create
- * new map entry messages of the same type. For each map entry message, only
- * one default instance should be created.
+ * <p>This method is used by generated code to create the default instance for a map entry
+ * message. The created default instance should be used to create new map entry messages of the
+ * same type. For each map entry message, only one default instance should be created.
*/
public static <K, V> MapEntryLite<K, V> newDefaultInstance(
- WireFormat.FieldType keyType, K defaultKey,
- WireFormat.FieldType valueType, V defaultValue) {
- return new MapEntryLite<K, V>(
- keyType, defaultKey, valueType, defaultValue);
+ WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) {
+ return new MapEntryLite<K, V>(keyType, defaultKey, valueType, defaultValue);
}
static <K, V> void writeTo(CodedOutputStream output, Metadata<K, V> metadata, K key, V value)
@@ -120,8 +117,11 @@ public class MapEntryLite<K, V> {
@SuppressWarnings("unchecked")
static <T> T parseField(
- CodedInputStream input, ExtensionRegistryLite extensionRegistry,
- WireFormat.FieldType type, T value) throws IOException {
+ CodedInputStream input,
+ ExtensionRegistryLite extensionRegistry,
+ WireFormat.FieldType type,
+ T value)
+ throws IOException {
switch (type) {
case MESSAGE:
MessageLite.Builder subBuilder = ((MessageLite) value).toBuilder();
@@ -137,9 +137,9 @@ public class MapEntryLite<K, V> {
}
/**
- * Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite}
- * to the output stream. This helper method avoids allocation of a {@link MapEntryLite}
- * built with a key and value and is called from generated code directly.
+ * Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite} to
+ * the output stream. This helper method avoids allocation of a {@link MapEntryLite} built with a
+ * key and value and is called from generated code directly.
*/
public void serializeTo(CodedOutputStream output, int fieldNumber, K key, V value)
throws IOException {
@@ -149,9 +149,9 @@ public class MapEntryLite<K, V> {
}
/**
- * Computes the message size for the provided key and value as though they were wrapped
- * by a {@link MapEntryLite}. This helper method avoids allocation of a {@link MapEntryLite}
- * built with a key and value and is called from generated code directly.
+ * Computes the message size for the provided key and value as though they were wrapped by a
+ * {@link MapEntryLite}. This helper method avoids allocation of a {@link MapEntryLite} built with
+ * a key and value and is called from generated code directly.
*/
public int computeMessageSize(int fieldNumber, K key, V value) {
return CodedOutputStream.computeTagSize(fieldNumber)
@@ -160,8 +160,8 @@ public class MapEntryLite<K, V> {
}
/**
- * Parses an entry off of the input as a {@link Map.Entry}. This helper requires an allocation
- * so using {@link #parseInto} is preferred if possible.
+ * Parses an entry off of the input as a {@link Map.Entry}. This helper requires an allocation so
+ * using {@link #parseInto} is preferred if possible.
*/
public Map.Entry<K, V> parseEntry(ByteString bytes, ExtensionRegistryLite extensionRegistry)
throws IOException {
@@ -170,7 +170,7 @@ public class MapEntryLite<K, V> {
static <K, V> Map.Entry<K, V> parseEntry(
CodedInputStream input, Metadata<K, V> metadata, ExtensionRegistryLite extensionRegistry)
- throws IOException{
+ throws IOException {
K key = metadata.defaultKey;
V value = metadata.defaultValue;
while (true) {
@@ -192,12 +192,12 @@ public class MapEntryLite<K, V> {
}
/**
- * Parses an entry off of the input into the map. This helper avoids allocaton of a
- * {@link MapEntryLite} by parsing directly into the provided {@link MapFieldLite}.
+ * Parses an entry off of the input into the map. This helper avoids allocaton of a {@link
+ * MapEntryLite} by parsing directly into the provided {@link MapFieldLite}.
*/
public void parseInto(
MapFieldLite<K, V> map, CodedInputStream input, ExtensionRegistryLite extensionRegistry)
- throws IOException {
+ throws IOException {
int length = input.readRawVarint32();
final int oldLimit = input.pushLimit(length);
K key = metadata.defaultKey;
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 ad8ceb02..f4877360 100644
--- a/java/core/src/main/java/com/google/protobuf/MapField.java
+++ b/java/core/src/main/java/com/google/protobuf/MapField.java
@@ -44,38 +44,44 @@ import java.util.Set;
/**
* Internal representation of map fields in generated messages.
*
- * This class supports accessing the map field as a {@link Map} to be used in
- * generated API and also supports accessing the field as a {@link List} to be
- * used in reflection API. It keeps track of where the data is currently stored
- * and do necessary conversions between map and list.
+ * <p>This class supports accessing the map field as a {@link Map} to be used in generated API and
+ * also supports accessing the field as a {@link List} to be used in reflection API. It keeps track
+ * of where the data is currently stored and do necessary conversions between map and list.
*
- * This class is a protobuf implementation detail. Users shouldn't use this
- * class directly.
+ * <p>This class is a protobuf implementation detail. Users shouldn't use this class directly.
*
- * THREAD-SAFETY NOTE: Read-only access is thread-safe. Users can call getMap()
- * and getList() concurrently in multiple threads. If write-access is needed,
- * all access must be synchronized.
+ * <p>THREAD-SAFETY NOTE: Read-only access is thread-safe. Users can call getMap() and getList()
+ * concurrently in multiple threads. If write-access is needed, all access must be synchronized.
*/
public class MapField<K, V> implements MutabilityOracle {
+
/**
* Indicates where the data of this map field is currently stored.
*
- * MAP: Data is stored in mapData.
- * LIST: Data is stored in listData.
- * BOTH: mapData and listData have the same data.
+ * <ul>
+ * <li>MAP: Data is stored in mapData.
+ * <li>LIST: Data is stored in listData.
+ * <li>BOTH: mapData and listData have the same data.
+ * </ul>
*
- * When the map field is accessed (through generated API or reflection API),
- * it will shift between these 3 modes:
+ * <p>When the map field is accessed (through generated API or reflection API), it will shift
+ * between these 3 modes:
*
- * getMap() getList() getMutableMap() getMutableList()
- * MAP MAP BOTH MAP LIST
- * LIST BOTH LIST MAP LIST
- * BOTH BOTH BOTH MAP LIST
+ * <pre>
+ * <b>getMap() getList() getMutableMap() getMutableList()</b>
+ * <b>MAP</b> MAP BOTH MAP LIST
+ * <b>LIST</b> BOTH LIST MAP LIST
+ * <b>BOTH</b> BOTH BOTH MAP LIST
+ * </pre>
*
- * As the map field changes its mode, the list/map reference returned in a
- * previous method call may be invalidated.
+ * <p>As the map field changes its mode, the list/map reference returned in a previous method call
+ * may be invalidated.
*/
- private enum StorageMode {MAP, LIST, BOTH}
+ private enum StorageMode {
+ MAP,
+ LIST,
+ BOTH
+ }
private volatile boolean isMutable;
private volatile StorageMode mode;
@@ -85,6 +91,7 @@ public class MapField<K, V> implements MutabilityOracle {
// Convert between a map entry Message and a key-value pair.
private static interface Converter<K, V> {
Message convertKeyAndValueToMessage(K key, V value);
+
void convertMessageToKeyAndValue(Message message, Map<K, V> map);
Message getMessageDefaultInstance();
@@ -92,6 +99,7 @@ public class MapField<K, V> implements MutabilityOracle {
private static class ImmutableMessageConverter<K, V> implements Converter<K, V> {
private final MapEntry<K, V> defaultEntry;
+
public ImmutableMessageConverter(MapEntry<K, V> defaultEntry) {
this.defaultEntry = defaultEntry;
}
@@ -117,10 +125,7 @@ public class MapField<K, V> implements MutabilityOracle {
private final Converter<K, V> converter;
- private MapField(
- Converter<K, V> converter,
- StorageMode mode,
- Map<K, V> mapData) {
+ private MapField(Converter<K, V> converter, StorageMode mode, Map<K, V> mapData) {
this.converter = converter;
this.isMutable = true;
this.mode = mode;
@@ -128,26 +133,20 @@ public class MapField<K, V> implements MutabilityOracle {
this.listData = null;
}
- private MapField(
- MapEntry<K, V> defaultEntry,
- StorageMode mode,
- Map<K, V> mapData) {
+ private MapField(MapEntry<K, V> defaultEntry, StorageMode mode, Map<K, V> mapData) {
this(new ImmutableMessageConverter<K, V>(defaultEntry), mode, mapData);
}
/** Returns an immutable empty MapField. */
- public static <K, V> MapField<K, V> emptyMapField(
- MapEntry<K, V> defaultEntry) {
- return new MapField<K, V>(
- defaultEntry, StorageMode.MAP, Collections.<K, V>emptyMap());
+ public static <K, V> MapField<K, V> emptyMapField(MapEntry<K, V> defaultEntry) {
+ return new MapField<K, V>(defaultEntry, StorageMode.MAP, Collections.<K, V>emptyMap());
}
/** Creates a new mutable empty MapField. */
public static <K, V> MapField<K, V> newMapField(MapEntry<K, V> defaultEntry) {
- return new MapField<K, V>(
- defaultEntry, StorageMode.MAP, new LinkedHashMap<K, V>());
+ return new MapField<K, V>(defaultEntry, StorageMode.MAP, new LinkedHashMap<K, V>());
}
@@ -163,9 +162,7 @@ public class MapField<K, V> implements MutabilityOracle {
private List<Message> convertMapToList(MutatabilityAwareMap<K, V> mapData) {
List<Message> listData = new ArrayList<Message>();
for (Map.Entry<K, V> entry : mapData.entrySet()) {
- listData.add(
- convertKeyAndValueToMessage(
- entry.getKey(), entry.getValue()));
+ listData.add(convertKeyAndValueToMessage(entry.getKey(), entry.getValue()));
}
return listData;
}
@@ -229,8 +226,7 @@ public class MapField<K, V> implements MutabilityOracle {
/** Returns a deep copy of this MapField. */
public MapField<K, V> copy() {
- return new MapField<K, V>(
- converter, StorageMode.MAP, MapFieldLite.copy(getMap()));
+ return new MapField<K, V>(converter, StorageMode.MAP, MapFieldLite.copy(getMap()));
}
/** Gets the content of this MapField as a read-only List. */
@@ -258,25 +254,20 @@ public class MapField<K, V> implements MutabilityOracle {
return listData;
}
- /**
- * Gets the default instance of the message stored in the list view of this
- * map field.
- */
+ /** Gets the default instance of the message stored in the list view of this map field. */
Message getMapEntryMessageDefaultInstance() {
return converter.getMessageDefaultInstance();
}
/**
- * Makes this list immutable. All subsequent modifications will throw an
- * {@link UnsupportedOperationException}.
+ * Makes this list immutable. All subsequent modifications will throw an {@link
+ * UnsupportedOperationException}.
*/
public void makeImmutable() {
isMutable = false;
}
- /**
- * Returns whether this field can be modified.
- */
+ /** Returns whether this field can be modified. */
public boolean isMutable() {
return isMutable;
}
@@ -291,9 +282,7 @@ public class MapField<K, V> implements MutabilityOracle {
}
}
- /**
- * An internal map that checks for mutability before delegating.
- */
+ /** An internal map that checks for mutability before delegating. */
private static class MutatabilityAwareMap<K, V> implements Map<K, V> {
private final MutabilityOracle mutabilityOracle;
private final Map<K, V> delegate;
@@ -388,9 +377,7 @@ public class MapField<K, V> implements MutabilityOracle {
return delegate.toString();
}
- /**
- * An internal collection that checks for mutability before delegating.
- */
+ /** An internal collection that checks for mutability before delegating. */
private static class MutatabilityAwareCollection<E> implements Collection<E> {
private final MutabilityOracle mutabilityOracle;
private final Collection<E> delegate;
@@ -487,9 +474,7 @@ public class MapField<K, V> implements MutabilityOracle {
}
}
- /**
- * An internal set that checks for mutability before delegating.
- */
+ /** An internal set that checks for mutability before delegating. */
private static class MutatabilityAwareSet<E> implements Set<E> {
private final MutabilityOracle mutabilityOracle;
private final Set<E> delegate;
@@ -586,9 +571,7 @@ public class MapField<K, V> implements MutabilityOracle {
}
}
- /**
- * An internal iterator that checks for mutability before delegating.
- */
+ /** An internal iterator that checks for mutability before delegating. */
private static class MutatabilityAwareIterator<E> implements Iterator<E> {
private final MutabilityOracle mutabilityOracle;
private final Iterator<E> delegate;
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 a8b3dd88..7467487b 100644
--- a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
@@ -42,8 +42,7 @@ import java.util.Set;
/**
* Internal representation of map fields in generated lite-runtime messages.
*
- * This class is a protobuf implementation detail. Users shouldn't use this
- * class directly.
+ * <p>This class is a protobuf implementation detail. Users shouldn't use this class directly.
*/
public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
@@ -60,6 +59,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
@SuppressWarnings({"rawtypes", "unchecked"})
private static final MapFieldLite EMPTY_MAP_FIELD = new MapFieldLite();
+
static {
EMPTY_MAP_FIELD.makeImmutable();
}
@@ -78,16 +78,19 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
@SuppressWarnings({"unchecked", "cast"})
- @Override public Set<Map.Entry<K, V>> entrySet() {
+ @Override
+ public Set<Map.Entry<K, V>> entrySet() {
return isEmpty() ? Collections.<Map.Entry<K, V>>emptySet() : super.entrySet();
}
- @Override public void clear() {
+ @Override
+ public void clear() {
ensureMutable();
super.clear();
}
- @Override public V put(K key, V value) {
+ @Override
+ public V put(K key, V value) {
ensureMutable();
checkNotNull(key);
@@ -99,13 +102,15 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
return put(entry.getKey(), entry.getValue());
}
- @Override public void putAll(Map<? extends K, ? extends V> m) {
+ @Override
+ public void putAll(Map<? extends K, ? extends V> m) {
ensureMutable();
checkForNullKeysAndValues(m);
super.putAll(m);
}
- @Override public V remove(Object key) {
+ @Override
+ public V remove(Object key) {
ensureMutable();
return super.remove(key);
}
@@ -125,9 +130,8 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
/**
- * Checks whether two {@link Map}s are equal. We don't use the default equals
- * method of {@link Map} because it compares by identity not by content for
- * byte arrays.
+ * Checks whether two {@link Map}s are equal. We don't use the default equals method of {@link
+ * Map} because it compares by identity not by content for byte arrays.
*/
static <K, V> boolean equals(Map<K, V> a, Map<K, V> b) {
if (a == b) {
@@ -147,9 +151,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
return true;
}
- /**
- * Checks whether two map fields are equal.
- */
+ /** Checks whether two map fields are equal. */
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object object) {
@@ -168,15 +170,14 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
/**
- * Calculates the hash code for a {@link Map}. We don't use the default hash
- * code method of {@link Map} because for byte arrays and protobuf enums it
- * use {@link Object#hashCode()}.
+ * Calculates the hash code for a {@link Map}. We don't use the default hash code method of {@link
+ * Map} because for byte arrays and protobuf enums it use {@link Object#hashCode()}.
*/
static <K, V> int calculateHashCodeForMap(Map<K, V> a) {
int result = 0;
for (Map.Entry<K, V> entry : a.entrySet()) {
- result += calculateHashCodeForObject(entry.getKey())
- ^ calculateHashCodeForObject(entry.getValue());
+ result +=
+ calculateHashCodeForObject(entry.getKey()) ^ calculateHashCodeForObject(entry.getValue());
}
return result;
}
@@ -195,9 +196,9 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
/**
- * Makes a deep copy of a {@link Map}. Immutable objects in the map will be
- * shared (e.g., integers, strings, immutable messages) and mutable ones will
- * have a copy (e.g., byte arrays, mutable messages).
+ * Makes a deep copy of a {@link Map}. Immutable objects in the map will be shared (e.g.,
+ * integers, strings, immutable messages) and mutable ones will have a copy (e.g., byte arrays,
+ * mutable messages).
*/
@SuppressWarnings("unchecked")
static <K, V> Map<K, V> copy(Map<K, V> map) {
@@ -214,16 +215,14 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
/**
- * Makes this field immutable. All subsequent modifications will throw an
- * {@link UnsupportedOperationException}.
+ * Makes this field immutable. All subsequent modifications will throw an {@link
+ * UnsupportedOperationException}.
*/
public void makeImmutable() {
isMutable = false;
}
- /**
- * Returns whether this field can be modified.
- */
+ /** Returns whether this field can be modified. */
public boolean isMutable() {
return isMutable;
}
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 0770d417..52b4a208 100644
--- a/java/core/src/main/java/com/google/protobuf/Message.java
+++ b/java/core/src/main/java/com/google/protobuf/Message.java
@@ -39,12 +39,11 @@ import java.util.Map;
/**
* Abstract interface implemented by Protocol Message objects.
- * <p>
- * See also {@link MessageLite}, which defines most of the methods that typical
- * users care about. {@link Message} adds to it methods that are not available
- * in the "lite" runtime. The biggest added features are introspection and
- * reflection -- i.e., getting descriptors for the message type and accessing
- * the field values dynamically.
+ *
+ * <p>See also {@link MessageLite}, which defines most of the methods that typical users care about.
+ * {@link Message} adds to it methods that are not available in the "lite" runtime. The biggest
+ * added features are introspection and reflection -- i.e., getting descriptors for the message type
+ * and accessing the field values dynamically.
*
* @author kenton@google.com Kenton Varda
*/
@@ -59,11 +58,10 @@ public interface Message extends MessageLite, MessageOrBuilder {
// Comparison and hashing
/**
- * Compares the specified object with this message for equality. Returns
- * {@code true} if the given object is a message of the same type (as
- * defined by {@code getDescriptorForType()}) and has identical values for
- * all of its fields. Subclasses must implement this; inheriting
- * {@code Object.equals()} is incorrect.
+ * Compares the specified object with this message for equality. Returns {@code true} if the given
+ * object is a message of the same type (as defined by {@code getDescriptorForType()}) and has
+ * identical values for all of its fields. Subclasses must implement this; inheriting {@code
+ * Object.equals()} is incorrect.
*
* @param other object to be compared for equality with this message
* @return {@code true} if the specified object is equal to this message
@@ -72,10 +70,9 @@ public interface Message extends MessageLite, MessageOrBuilder {
boolean equals(Object other);
/**
- * Returns the hash code value for this message. The hash code of a message
- * should mix the message's type (object identity of the descriptor) with its
- * contents (known and unknown field values). Subclasses must implement this;
- * inheriting {@code Object.hashCode()} is incorrect.
+ * Returns the hash code value for this message. The hash code of a message should mix the
+ * message's type (object identity of the descriptor) with its contents (known and unknown field
+ * values). Subclasses must implement this; inheriting {@code Object.hashCode()} is incorrect.
*
* @return the hash code value for this message
* @see Map#hashCode()
@@ -87,9 +84,8 @@ public interface Message extends MessageLite, MessageOrBuilder {
// Convenience methods.
/**
- * Converts the message to a string in protocol buffer text format. This is
- * just a trivial wrapper around {@link
- * TextFormat#printToString(MessageOrBuilder)}.
+ * Converts the message to a string in protocol buffer text format. This is just a trivial wrapper
+ * around {@link TextFormat#printToString(MessageOrBuilder)}.
*/
@Override
String toString();
@@ -104,9 +100,7 @@ public interface Message extends MessageLite, MessageOrBuilder {
@Override
Builder toBuilder();
- /**
- * Abstract interface implemented by Protocol Message builders.
- */
+ /** Abstract interface implemented by Protocol Message builders. */
interface Builder extends MessageLite.Builder, MessageOrBuilder {
// (From MessageLite.Builder, re-declared here only for return type
// covariance.)
@@ -114,23 +108,21 @@ public interface Message extends MessageLite, MessageOrBuilder {
Builder clear();
/**
- * Merge {@code other} into the message being built. {@code other} must
- * have the exact same type as {@code this} (i.e.
- * {@code getDescriptorForType() == other.getDescriptorForType()}).
+ * Merge {@code other} into the message being built. {@code other} must have the exact same type
+ * as {@code this} (i.e. {@code getDescriptorForType() == other.getDescriptorForType()}).
*
- * Merging occurs as follows. For each field:<br>
- * * For singular primitive fields, if the field is set in {@code other},
- * then {@code other}'s value overwrites the value in this message.<br>
- * * For singular message fields, if the field is set in {@code other},
- * 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.<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.
+ * <p>Merging occurs as follows. For each field:<br>
+ * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s
+ * value overwrites the value in this message.<br>
+ * * For singular message fields, if the field is set in {@code other}, 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.<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.
*
- * This is equivalent to the {@code Message::MergeFrom} method in C++.
+ * <p>This is equivalent to the {@code Message::MergeFrom} method in C++.
*/
Builder mergeFrom(Message other);
@@ -152,101 +144,90 @@ public interface Message extends MessageLite, MessageOrBuilder {
Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
- /**
- * Get the message's type's descriptor.
- * See {@link Message#getDescriptorForType()}.
- */
+ /** Get the message's type's descriptor. See {@link Message#getDescriptorForType()}. */
@Override
Descriptors.Descriptor getDescriptorForType();
/**
- * Create a Builder for messages of the appropriate type for the given
- * field. Messages built with this can then be passed to setField(),
- * setRepeatedField(), or addRepeatedField().
+ * Create a Builder for messages of the appropriate type for the given field. Messages built
+ * with this can then be passed to setField(), setRepeatedField(), or addRepeatedField().
*/
Builder newBuilderForField(Descriptors.FieldDescriptor field);
/**
* Get a nested builder instance for the given field.
- * <p>
- * Normally, we hold a reference to the immutable message object for the
- * message type field. Some implementations(the generated message builders),
- * however, can also hold a reference to the builder object (a nested
- * builder) for the field.
- * <p>
- * If the field is already backed up by a nested builder, the nested builder
- * will be returned. Otherwise, a new field builder will be created and
- * returned. The original message field (if exist) will be merged into the
- * field builder, which will then be nested into its parent builder.
- * <p>
- * NOTE: implementations that do not support nested builders will throw
- * <code>UnsupportedOperationException</code>.
+ *
+ * <p>Normally, we hold a reference to the immutable message object for the message type field.
+ * Some implementations(the generated message builders), however, can also hold a reference to
+ * the builder object (a nested builder) for the field.
+ *
+ * <p>If the field is already backed up by a nested builder, the nested builder will be
+ * returned. Otherwise, a new field builder will be created and returned. The original message
+ * field (if exist) will be merged into the field builder, which will then be nested into its
+ * parent builder.
+ *
+ * <p>NOTE: implementations that do not support nested builders will throw <code>
+ * UnsupportedOperationException</code>.
*/
Builder getFieldBuilder(Descriptors.FieldDescriptor field);
/**
* Get a nested builder instance for the given repeated field instance.
- * <p>
- * Normally, we hold a reference to the immutable message object for the
- * message type field. Some implementations(the generated message builders),
- * however, can also hold a reference to the builder object (a nested
- * builder) for the field.
- * <p>
- * If the field is already backed up by a nested builder, the nested builder
- * will be returned. Otherwise, a new field builder will be created and
- * returned. The original message field (if exist) will be merged into the
- * field builder, which will then be nested into its parent builder.
- * <p>
- * NOTE: implementations that do not support nested builders will throw
- * <code>UnsupportedOperationException</code>.
+ *
+ * <p>Normally, we hold a reference to the immutable message object for the message type field.
+ * Some implementations(the generated message builders), however, can also hold a reference to
+ * the builder object (a nested builder) for the field.
+ *
+ * <p>If the field is already backed up by a nested builder, the nested builder will be
+ * returned. Otherwise, a new field builder will be created and returned. The original message
+ * field (if exist) will be merged into the field builder, which will then be nested into its
+ * parent builder.
+ *
+ * <p>NOTE: implementations that do not support nested builders will throw <code>
+ * UnsupportedOperationException</code>.
*/
- Builder getRepeatedFieldBuilder(Descriptors.FieldDescriptor field,
- int index);
+ Builder getRepeatedFieldBuilder(Descriptors.FieldDescriptor field, int index);
/**
- * Sets a field to the given value. The value must be of the correct type
- * for this field, i.e. the same type that
- * {@link Message#getField(Descriptors.FieldDescriptor)} would return.
+ * Sets a field to the given value. The value must be of the correct type for this field, i.e.
+ * the same type that {@link Message#getField(Descriptors.FieldDescriptor)} would return.
*/
Builder setField(Descriptors.FieldDescriptor field, Object value);
/**
- * Clears the field. This is exactly equivalent to calling the generated
- * "clear" accessor method corresponding to the field.
+ * Clears the field. This is exactly equivalent to calling the generated "clear" accessor method
+ * corresponding to the field.
*/
Builder clearField(Descriptors.FieldDescriptor field);
/**
- * Clears the oneof. This is exactly equivalent to calling the generated
- * "clear" accessor method corresponding to the oneof.
+ * Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method
+ * corresponding to the oneof.
*/
Builder clearOneof(Descriptors.OneofDescriptor oneof);
/**
- * Sets an element of a repeated field to the given value. The value must
- * be of the correct type for this field, i.e. the same type that
- * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)} would
- * return.
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() != getDescriptorForType()}.
+ * Sets an element of a repeated field to the given value. The value must be of the correct type
+ * for this field, i.e. the same type that {@link
+ * Message#getRepeatedField(Descriptors.FieldDescriptor,int)} would return.
+ *
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
- Builder setRepeatedField(Descriptors.FieldDescriptor field,
- int index, Object value);
+ Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value);
/**
* Like {@code setRepeatedField}, but appends the value as a new element.
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() != getDescriptorForType()}.
+ *
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value);
/** Set the {@link UnknownFieldSet} for this message. */
Builder setUnknownFields(UnknownFieldSet unknownFields);
- /**
- * Merge some unknown fields into the {@link UnknownFieldSet} for this
- * message.
- */
+ /** Merge some unknown fields into the {@link UnknownFieldSet} for this message. */
Builder mergeUnknownFields(UnknownFieldSet unknownFields);
// ---------------------------------------------------------------
diff --git a/java/core/src/main/java/com/google/protobuf/MessageLite.java b/java/core/src/main/java/com/google/protobuf/MessageLite.java
index 88f531df..7d2ef33a 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageLite.java
@@ -40,91 +40,79 @@ import java.io.OutputStream;
/**
* Abstract interface implemented by Protocol Message objects.
*
- * <p>This interface is implemented by all protocol message objects. Non-lite
- * messages additionally implement the Message interface, which is a subclass
- * of MessageLite. Use MessageLite instead when you only need the subset of
- * features which it supports -- namely, nothing that uses descriptors or
- * reflection. You can instruct the protocol compiler to generate classes
- * which implement only MessageLite, not the full Message interface, by adding
- * the follow line to the .proto file:
+ * <p>This interface is implemented by all protocol message objects. Non-lite messages additionally
+ * implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when
+ * you only need the subset of features which it supports -- namely, nothing that uses descriptors
+ * or reflection. You can instruct the protocol compiler to generate classes which implement only
+ * MessageLite, not the full Message interface, by adding the follow line to the .proto file:
+ *
* <pre>
* option optimize_for = LITE_RUNTIME;
* </pre>
*
- * <p>This is particularly useful on resource-constrained systems where the
- * full protocol buffers runtime library is too big.
+ * <p>This is particularly useful on resource-constrained systems where the full protocol buffers
+ * runtime library is too big.
*
- * <p>Note that on non-constrained systems (e.g. servers) when you need to link
- * in lots of protocol definitions, a better way to reduce total code footprint
- * is to use {@code optimize_for = CODE_SIZE}. This will make the generated
- * code smaller while still supporting all the same features (at the expense of
- * speed). {@code optimize_for = LITE_RUNTIME} is best when you only have a
- * small number of message types linked into your binary, in which case the
- * size of the protocol buffers runtime itself is the biggest problem.
+ * <p>Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol
+ * definitions, a better way to reduce total code footprint is to use {@code optimize_for =
+ * CODE_SIZE}. This will make the generated code smaller while still supporting all the same
+ * features (at the expense of speed). {@code optimize_for = LITE_RUNTIME} is best when you only
+ * have a small number of message types linked into your binary, in which case the size of the
+ * protocol buffers runtime itself is the biggest problem.
*
* @author kenton@google.com Kenton Varda
*/
public interface MessageLite extends MessageLiteOrBuilder {
-
/**
- * Serializes the message and writes it to {@code output}. This does not
- * flush or close the stream.
+ * Serializes the message and writes it to {@code output}. This does not flush or close the
+ * stream.
*/
void writeTo(CodedOutputStream output) throws IOException;
/**
- * Get the number of bytes required to encode this message. The result
- * is only computed on the first call and memoized after that.
+ * Get the number of bytes required to encode this message. The result is only computed on the
+ * first call and memoized after that.
*/
int getSerializedSize();
-
- /**
- * Gets the parser for a message of the same type as this message.
- */
+ /** Gets the parser for a message of the same type as this message. */
Parser<? extends MessageLite> getParserForType();
// -----------------------------------------------------------------
// Convenience methods.
/**
- * Serializes the message to a {@code ByteString} and returns it. This is
- * just a trivial wrapper around
- * {@link #writeTo(CodedOutputStream)}.
+ * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper
+ * around {@link #writeTo(CodedOutputStream)}.
*/
ByteString toByteString();
/**
- * Serializes the message to a {@code byte} array and returns it. This is
- * just a trivial wrapper around
- * {@link #writeTo(CodedOutputStream)}.
+ * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper
+ * around {@link #writeTo(CodedOutputStream)}.
*/
byte[] toByteArray();
/**
- * Serializes the message and writes it to {@code output}. This is just a
- * trivial wrapper around {@link #writeTo(CodedOutputStream)}. This does
- * not flush or close the stream.
- * <p>
- * NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write
- * any more data to the stream after the message, you must somehow ensure
- * that the parser on the receiving end does not interpret this as being
- * part of the protocol message. This can be done e.g. by writing the size
- * of the message before the data, then making sure to limit the input to
- * that size on the receiving end (e.g. by wrapping the InputStream in one
- * which limits the input). Alternatively, just use
- * {@link #writeDelimitedTo(OutputStream)}.
+ * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around
+ * {@link #writeTo(CodedOutputStream)}. This does not flush or close the stream.
+ *
+ * <p>NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write any more data to the
+ * stream after the message, you must somehow ensure that the parser on the receiving end does not
+ * interpret this as being part of the protocol message. This can be done e.g. by writing the size
+ * of the message before the data, then making sure to limit the input to that size on the
+ * receiving end (e.g. by wrapping the InputStream in one which limits the input). Alternatively,
+ * just use {@link #writeDelimitedTo(OutputStream)}.
*/
void writeTo(OutputStream output) throws IOException;
/**
- * Like {@link #writeTo(OutputStream)}, but writes the size of the message
- * as a varint before writing the data. This allows more data to be written
- * to the stream after the message without the need to delimit the message
- * data yourself. Use {@link Builder#mergeDelimitedFrom(InputStream)} (or
- * the static method {@code YourMessageType.parseDelimitedFrom(InputStream)})
- * to parse messages written by this method.
+ * Like {@link #writeTo(OutputStream)}, but writes the size of the message as a varint before
+ * writing the data. This allows more data to be written to the stream after the message without
+ * the need to delimit the message data yourself. Use {@link
+ * Builder#mergeDelimitedFrom(InputStream)} (or the static method {@code
+ * YourMessageType.parseDelimitedFrom(InputStream)}) to parse messages written by this method.
*/
void writeDelimitedTo(OutputStream output) throws IOException;
@@ -132,210 +120,179 @@ public interface MessageLite extends MessageLiteOrBuilder {
// =================================================================
// Builders
- /**
- * Constructs a new builder for a message of the same type as this message.
- */
+ /** Constructs a new builder for a message of the same type as this message. */
Builder newBuilderForType();
/**
- * Constructs a builder initialized with the current message. Use this to
- * derive a new message from the current one.
+ * Constructs a builder initialized with the current message. Use this to derive a new message
+ * from the current one.
*/
Builder toBuilder();
- /**
- * Abstract interface implemented by Protocol Message builders.
- */
+ /** Abstract interface implemented by Protocol Message builders. */
interface Builder extends MessageLiteOrBuilder, Cloneable {
/** Resets all fields to their default values. */
Builder clear();
/**
- * Constructs the message based on the state of the Builder. Subsequent
- * changes to the Builder will not affect the returned message.
- * @throws UninitializedMessageException The message is missing one or more
- * required fields (i.e. {@link #isInitialized()} returns false).
- * Use {@link #buildPartial()} to bypass this check.
+ * Constructs the message based on the state of the Builder. Subsequent changes to the Builder
+ * will not affect the returned message.
+ *
+ * @throws UninitializedMessageException The message is missing one or more required fields
+ * (i.e. {@link #isInitialized()} returns false). Use {@link #buildPartial()} to bypass this
+ * check.
*/
MessageLite build();
/**
- * Like {@link #build()}, but does not throw an exception if the message
- * is missing required fields. Instead, a partial message is returned.
- * Subsequent changes to the Builder will not affect the returned message.
+ * Like {@link #build()}, but does not throw an exception if the message is missing required
+ * fields. Instead, a partial message is returned. Subsequent changes to the Builder will not
+ * affect the returned message.
*/
MessageLite buildPartial();
/**
* Clones the Builder.
+ *
* @see Object#clone()
*/
Builder clone();
/**
- * Parses a message of this type from the input and merges it with this
- * message.
+ * Parses a message of this type from the input and merges it with this message.
+ *
+ * <p>Warning: This does not verify that all required fields are present in the input message.
+ * If you call {@link #build()} without setting all required fields, it will throw an {@link
+ * UninitializedMessageException}, which is a {@code RuntimeException} and thus might not be
+ * caught. There are a few good ways to deal with this:
*
- * <p>Warning: This does not verify that all required fields are present in
- * the input message. If you call {@link #build()} without setting all
- * required fields, it will throw an {@link UninitializedMessageException},
- * which is a {@code RuntimeException} and thus might not be caught. There
- * are a few good ways to deal with this:
* <ul>
- * <li>Call {@link #isInitialized()} to verify that all required fields
- * are set before building.
- * <li>Use {@code buildPartial()} to build, which ignores missing
- * required fields.
+ * <li>Call {@link #isInitialized()} to verify that all required fields are set before
+ * building.
+ * <li>Use {@code buildPartial()} to build, which ignores missing required fields.
* </ul>
*
- * <p>Note: The caller should call
- * {@link CodedInputStream#checkLastTagWas(int)} after calling this to
- * verify that the last tag seen was the appropriate end-group tag,
- * or zero for EOF.
+ * <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling
+ * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF.
*/
Builder mergeFrom(CodedInputStream input) throws IOException;
/**
- * Like {@link Builder#mergeFrom(CodedInputStream)}, but also
- * parses extensions. The extensions that you want to be able to parse
- * must be registered in {@code extensionRegistry}. Extensions not in
- * the registry will be treated as unknown fields.
+ * Like {@link Builder#mergeFrom(CodedInputStream)}, but also parses extensions. The extensions
+ * that you want to be able to parse must be registered in {@code extensionRegistry}. Extensions
+ * not in the registry will be treated as unknown fields.
*/
- Builder mergeFrom(CodedInputStream input,
- ExtensionRegistryLite extensionRegistry)
- throws IOException;
+ Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
+ throws IOException;
// ---------------------------------------------------------------
// Convenience methods.
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
- Builder mergeFrom(ByteString data,
- ExtensionRegistryLite extensionRegistry)
- throws InvalidProtocolBufferException;
+ Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException;
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
- Builder mergeFrom(byte[] data, int off, int len)
- throws InvalidProtocolBufferException;
+ Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
- Builder mergeFrom(byte[] data,
- ExtensionRegistryLite extensionRegistry)
- throws InvalidProtocolBufferException;
+ Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException;
/**
- * Parse {@code data} as a message of this type and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
+ * Parse {@code data} as a message of this type and merge it with the message being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
- Builder mergeFrom(byte[] data, int off, int len,
- ExtensionRegistryLite extensionRegistry)
- throws InvalidProtocolBufferException;
+ Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
+ throws InvalidProtocolBufferException;
/**
- * Parse a message of this type from {@code input} and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}. Note that this method always
- * reads the <i>entire</i> input (unless it throws an exception). If you
- * want it to stop earlier, you will need to wrap your input in some
- * wrapper stream that limits reading. Or, use
- * {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message
- * and {@link #mergeDelimitedFrom(InputStream)} to read it.
- * <p>
- * Despite usually reading the entire input, this does not close the stream.
+ * Parse a message of this type from {@code input} and merge it with the message being built.
+ * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. Note that this
+ * method always reads the <i>entire</i> input (unless it throws an exception). If you want it
+ * to stop earlier, you will need to wrap your input in some wrapper stream that limits reading.
+ * Or, use {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message and {@link
+ * #mergeDelimitedFrom(InputStream)} to read it.
+ *
+ * <p>Despite usually reading the entire input, this does not close the stream.
*
* @return this
*/
Builder mergeFrom(InputStream input) throws IOException;
/**
- * Parse a message of this type from {@code input} and merge it with the
- * message being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
+ * Parse a message of this type from {@code input} and merge it with the message being built.
+ * This is just a small wrapper around {@link
+ * #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
- Builder mergeFrom(InputStream input,
- ExtensionRegistryLite extensionRegistry)
- throws IOException;
-
+ Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
+ throws IOException;
+
/**
- * Merge {@code other} into the message being built. {@code other} must
- * have the exact same type as {@code this} (i.e.
- * {@code getClass().equals(getDefaultInstanceForType().getClass())}).
+ * Merge {@code other} into the message being built. {@code other} must have the exact same type
+ * as {@code this} (i.e. {@code getClass().equals(getDefaultInstanceForType().getClass())}).
*
- * Merging occurs as follows. For each field:<br>
- * * For singular primitive fields, if the field is set in {@code other},
- * then {@code other}'s value overwrites the value in this message.<br>
- * * For singular message fields, if the field is set in {@code other},
- * 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.
- * * 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.
+ * <p>Merging occurs as follows. For each field:<br>
+ * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s
+ * value overwrites the value in this message.<br>
+ * * For singular message fields, if the field is set in {@code other}, 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. * 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.
*
- * This is equivalent to the {@code Message::MergeFrom} method in C++.
+ * <p>This is equivalent to the {@code Message::MergeFrom} method in C++.
*/
Builder mergeFrom(MessageLite other);
/**
- * Like {@link #mergeFrom(InputStream)}, but does not read until EOF.
- * Instead, the size of the message (encoded as a varint) is read first,
- * then the message data. Use
- * {@link MessageLite#writeDelimitedTo(OutputStream)} to write messages in
- * this format.
+ * Like {@link #mergeFrom(InputStream)}, but does not read until EOF. Instead, the size of the
+ * message (encoded as a varint) is read first, then the message data. Use {@link
+ * MessageLite#writeDelimitedTo(OutputStream)} to write messages in this format.
*
- * @return True if successful, or false if the stream is at EOF when the
- * method starts. Any other error (including reaching EOF during
- * parsing) will cause an exception to be thrown.
+ * @return True if successful, or false if the stream is at EOF when the method starts. Any
+ * other error (including reaching EOF during parsing) will cause an exception to be thrown.
*/
- boolean mergeDelimitedFrom(InputStream input)
- throws IOException;
+ boolean mergeDelimitedFrom(InputStream input) throws IOException;
- /**
- * Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions.
- */
- boolean mergeDelimitedFrom(InputStream input,
- ExtensionRegistryLite extensionRegistry)
- throws IOException;
+ /** Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. */
+ boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
+ throws IOException;
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java b/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java
index 818386ce..7a5ef3ed 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageLiteOrBuilder.java
@@ -31,30 +31,27 @@
package com.google.protobuf;
/**
- * Base interface for methods common to {@link MessageLite}
- * and {@link MessageLite.Builder} to provide type equivalency.
+ * Base interface for methods common to {@link MessageLite} and {@link MessageLite.Builder} to
+ * provide type equivalency.
*
* @author jonp@google.com (Jon Perlow)
*/
public interface MessageLiteOrBuilder {
/**
- * Get an instance of the type with no fields set. Because no fields are set,
- * all getters for singular fields will return default values and repeated
- * fields will appear empty.
- * This may or may not be a singleton. This differs from the
- * {@code getDefaultInstance()} method of generated message classes in that
- * this method is an abstract method of the {@code MessageLite} interface
- * whereas {@code getDefaultInstance()} is a static method of a specific
- * class. They return the same thing.
+ * Get an instance of the type with no fields set. Because no fields are set, all getters for
+ * singular fields will return default values and repeated fields will appear empty. This may or
+ * may not be a singleton. This differs from the {@code getDefaultInstance()} method of generated
+ * message classes in that this method is an abstract method of the {@code MessageLite} interface
+ * whereas {@code getDefaultInstance()} is a static method of a specific class. They return the
+ * same thing.
*/
MessageLite getDefaultInstanceForType();
/**
- * Returns true if all required fields in the message and all embedded
- * messages are set, false otherwise.
+ * Returns true if all required fields in the message and all embedded messages are set, false
+ * otherwise.
*
* <p>See also: {@link MessageOrBuilder#getInitializationErrorString()}
*/
boolean isInitialized();
-
}
diff --git a/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java b/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java
index 5e7d7821..0254df99 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageOrBuilder.java
@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Map;
/**
- * Base interface for methods common to {@link Message} and
- * {@link Message.Builder} to provide type equivalency.
+ * Base interface for methods common to {@link Message} and {@link Message.Builder} to provide type
+ * equivalency.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -46,95 +46,85 @@ public interface MessageOrBuilder extends MessageLiteOrBuilder {
Message getDefaultInstanceForType();
/**
- * Returns a list of field paths (e.g. "foo.bar.baz") of required fields
- * which are not set in this message. You should call
- * {@link MessageLiteOrBuilder#isInitialized()} first to check if there
- * are any missing fields, as that method is likely to be much faster
- * than this one even when the message is fully-initialized.
+ * Returns a list of field paths (e.g. "foo.bar.baz") of required fields which are not set in this
+ * message. You should call {@link MessageLiteOrBuilder#isInitialized()} first to check if there
+ * are any missing fields, as that method is likely to be much faster than this one even when the
+ * message is fully-initialized.
*/
List<String> findInitializationErrors();
/**
- * Returns a comma-delimited list of required fields which are not set
- * in this message object. You should call
- * {@link MessageLiteOrBuilder#isInitialized()} first to check if there
- * are any missing fields, as that method is likely to be much faster
- * than this one even when the message is fully-initialized.
+ * Returns a comma-delimited list of required fields which are not set in this message object. You
+ * should call {@link MessageLiteOrBuilder#isInitialized()} first to check if there are any
+ * missing fields, as that method is likely to be much faster than this one even when the message
+ * is fully-initialized.
*/
String getInitializationErrorString();
/**
- * Get the message's type's descriptor. This differs from the
- * {@code getDescriptor()} method of generated message classes in that
- * this method is an abstract method of the {@code Message} interface
- * whereas {@code getDescriptor()} is a static method of a specific class.
- * They return the same thing.
+ * Get the message's type's descriptor. This differs from the {@code getDescriptor()} method of
+ * generated message classes in that this method is an abstract method of the {@code Message}
+ * interface whereas {@code getDescriptor()} is a static method of a specific class. They return
+ * the same thing.
*/
Descriptors.Descriptor getDescriptorForType();
/**
- * Returns a collection of all the fields in this message which are set
- * and their corresponding values. A singular ("required" or "optional")
- * field is set iff hasField() returns true for that field. A "repeated"
- * field is set iff getRepeatedFieldCount() is greater than zero. The
- * values are exactly what would be returned by calling
- * {@link #getField(Descriptors.FieldDescriptor)} for each field. The map
- * is guaranteed to be a sorted map, so iterating over it will return fields
- * in order by field number.
- * <br>
- * If this is for a builder, the returned map may or may not reflect future
- * changes to the builder. Either way, the returned map is itself
- * unmodifiable.
+ * Returns a collection of all the fields in this message which are set and their corresponding
+ * values. A singular ("required" or "optional") field is set iff hasField() returns true for that
+ * field. A "repeated" field is set iff getRepeatedFieldCount() is greater than zero. The values
+ * are exactly what would be returned by calling {@link #getField(Descriptors.FieldDescriptor)}
+ * for each field. The map is guaranteed to be a sorted map, so iterating over it will return
+ * fields in order by field number. <br>
+ * If this is for a builder, the returned map may or may not reflect future changes to the
+ * builder. Either way, the returned map is itself unmodifiable.
*/
Map<Descriptors.FieldDescriptor, Object> getAllFields();
/**
* Returns true if the given oneof is set.
- * @throws IllegalArgumentException if
- * {@code oneof.getContainingType() != getDescriptorForType()}.
+ *
+ * @throws IllegalArgumentException if {@code oneof.getContainingType() !=
+ * getDescriptorForType()}.
*/
boolean hasOneof(Descriptors.OneofDescriptor oneof);
- /**
- * Obtains the FieldDescriptor if the given oneof is set. Returns null
- * if no field is set.
- */
- Descriptors.FieldDescriptor getOneofFieldDescriptor(
- Descriptors.OneofDescriptor oneof);
+ /** Obtains the FieldDescriptor if the given oneof is set. Returns null if no field is set. */
+ Descriptors.FieldDescriptor getOneofFieldDescriptor(Descriptors.OneofDescriptor oneof);
/**
- * Returns true if the given field is set. This is exactly equivalent to
- * calling the generated "has" accessor method corresponding to the field.
- * @throws IllegalArgumentException The field is a repeated field, or
- * {@code field.getContainingType() != getDescriptorForType()}.
+ * Returns true if the given field is set. This is exactly equivalent to calling the generated
+ * "has" accessor method corresponding to the field.
+ *
+ * @throws IllegalArgumentException The field is a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
boolean hasField(Descriptors.FieldDescriptor field);
/**
- * Obtains the value of the given field, or the default value if it is
- * not set. For primitive fields, the boxed primitive value is returned.
- * For enum fields, the EnumValueDescriptor for the value is returned. For
- * embedded message fields, the sub-message is returned. For repeated
+ * Obtains the value of the given field, or the default value if it is not set. For primitive
+ * fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for the
+ * value is returned. For embedded message fields, the sub-message is returned. For repeated
* fields, a java.util.List is returned.
*/
Object getField(Descriptors.FieldDescriptor field);
/**
- * Gets the number of elements of a repeated field. This is exactly
- * equivalent to calling the generated "Count" accessor method corresponding
- * to the field.
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() != getDescriptorForType()}.
+ * Gets the number of elements of a repeated field. This is exactly equivalent to calling the
+ * generated "Count" accessor method corresponding to the field.
+ *
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
int getRepeatedFieldCount(Descriptors.FieldDescriptor field);
/**
- * Gets an element of a repeated field. For primitive fields, the boxed
- * primitive value is returned. For enum fields, the EnumValueDescriptor
- * for the value is returned. For embedded message fields, the sub-message
- * is returned.
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() != getDescriptorForType()}.
+ * Gets an element of a repeated field. For primitive fields, the boxed primitive value is
+ * returned. For enum fields, the EnumValueDescriptor for the value is returned. For embedded
+ * message fields, the sub-message is returned.
+ *
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
Object getRepeatedField(Descriptors.FieldDescriptor field, int index);
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 69ad7ddf..9fc72bd9 100644
--- a/java/core/src/main/java/com/google/protobuf/MessageReflection.java
+++ b/java/core/src/main/java/com/google/protobuf/MessageReflection.java
@@ -54,20 +54,19 @@ class MessageReflection {
message.getDescriptorForType().getOptions().getMessageSetWireFormat();
if (alwaysWriteRequiredFields) {
fields = new TreeMap<FieldDescriptor, Object>(fields);
- for (final FieldDescriptor field :
- message.getDescriptorForType().getFields()) {
+ for (final FieldDescriptor field : message.getDescriptorForType().getFields()) {
if (field.isRequired() && !fields.containsKey(field)) {
fields.put(field, message.getField(field));
}
}
}
- for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry :
- fields.entrySet()) {
+ for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fields.entrySet()) {
final Descriptors.FieldDescriptor field = entry.getKey();
final Object value = entry.getValue();
- if (isMessageSet && field.isExtension() &&
- field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE &&
- !field.isRepeated()) {
+ if (isMessageSet
+ && field.isExtension()
+ && field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE
+ && !field.isRepeated()) {
output.writeMessageSetExtension(field.getNumber(), (Message) value);
} else {
FieldSet.writeField(field, value, output);
@@ -82,22 +81,20 @@ class MessageReflection {
}
}
- static int getSerializedSize(
- Message message,
- Map<FieldDescriptor, Object> fields) {
+ static int getSerializedSize(Message message, Map<FieldDescriptor, Object> fields) {
int size = 0;
final boolean isMessageSet =
message.getDescriptorForType().getOptions().getMessageSetWireFormat();
- for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry :
- fields.entrySet()) {
+ for (final Map.Entry<Descriptors.FieldDescriptor, Object> entry : fields.entrySet()) {
final Descriptors.FieldDescriptor field = entry.getKey();
final Object value = entry.getValue();
- if (isMessageSet && field.isExtension() &&
- field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE &&
- !field.isRepeated()) {
- size += CodedOutputStream.computeMessageSetExtensionSize(
- field.getNumber(), (Message) value);
+ if (isMessageSet
+ && field.isExtension()
+ && field.getType() == Descriptors.FieldDescriptor.Type.MESSAGE
+ && !field.isRepeated()) {
+ size +=
+ CodedOutputStream.computeMessageSetExtensionSize(field.getNumber(), (Message) value);
} else {
size += FieldSet.computeFieldSize(field, value);
}
@@ -126,9 +123,7 @@ class MessageReflection {
@SuppressWarnings("unchecked")
static boolean isInitialized(MessageOrBuilder message) {
// Check that all required fields are present.
- for (final Descriptors.FieldDescriptor field : message
- .getDescriptorForType()
- .getFields()) {
+ for (final Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) {
if (field.isRequired()) {
if (!message.hasField(field)) {
return false;
@@ -142,8 +137,7 @@ class MessageReflection {
final Descriptors.FieldDescriptor field = entry.getKey();
if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) {
if (field.isRepeated()) {
- for (final Message element
- : (List<Message>) entry.getValue()) {
+ for (final Message element : (List<Message>) entry.getValue()) {
if (!element.isInitialized()) {
return false;
}
@@ -159,31 +153,24 @@ class MessageReflection {
return true;
}
- private static String subMessagePrefix(final String prefix,
- final Descriptors.FieldDescriptor field,
- final int index) {
+ private static String subMessagePrefix(
+ final String prefix, final Descriptors.FieldDescriptor field, final int index) {
final StringBuilder result = new StringBuilder(prefix);
if (field.isExtension()) {
- result.append('(')
- .append(field.getFullName())
- .append(')');
+ result.append('(').append(field.getFullName()).append(')');
} else {
result.append(field.getName());
}
if (index != -1) {
- result.append('[')
- .append(index)
- .append(']');
+ result.append('[').append(index).append(']');
}
result.append('.');
return result.toString();
}
- private static void findMissingFields(final MessageOrBuilder message,
- final String prefix,
- final List<String> results) {
- for (final Descriptors.FieldDescriptor field :
- message.getDescriptorForType().getFields()) {
+ private static void findMissingFields(
+ final MessageOrBuilder message, final String prefix, final List<String> results) {
+ for (final Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) {
if (field.isRequired() && !message.hasField(field)) {
results.add(prefix + field.getName());
}
@@ -198,15 +185,13 @@ class MessageReflection {
if (field.isRepeated()) {
int i = 0;
for (final Object element : (List) value) {
- findMissingFields((MessageOrBuilder) element,
- subMessagePrefix(prefix, field, i++),
- results);
+ findMissingFields(
+ (MessageOrBuilder) element, subMessagePrefix(prefix, field, i++), results);
}
} else {
if (message.hasField(field)) {
- findMissingFields((MessageOrBuilder) value,
- subMessagePrefix(prefix, field, -1),
- results);
+ findMissingFields(
+ (MessageOrBuilder) value, subMessagePrefix(prefix, field, -1), results);
}
}
}
@@ -214,11 +199,10 @@ class MessageReflection {
}
/**
- * Populates {@code this.missingFields} with the full "path" of each missing
- * required field in the given message.
+ * Populates {@code this.missingFields} with the full "path" of each missing required field in the
+ * given message.
*/
- static List<String> findMissingFields(
- final MessageOrBuilder message) {
+ static List<String> findMissingFields(final MessageOrBuilder message) {
final List<String> results = new ArrayList<String>();
findMissingFields(message, "", results);
return results;
@@ -226,12 +210,11 @@ class MessageReflection {
static interface MergeTarget {
enum ContainerType {
- MESSAGE, EXTENSION_SET
+ MESSAGE,
+ EXTENSION_SET
}
- /**
- * Returns the descriptor for the target.
- */
+ /** Returns the descriptor for the target. */
public Descriptors.Descriptor getDescriptorForType();
public ContainerType getContainerType();
@@ -240,21 +223,19 @@ class MessageReflection {
ExtensionRegistry registry, String name);
public ExtensionRegistry.ExtensionInfo findExtensionByNumber(
- ExtensionRegistry registry, Descriptors.Descriptor containingType,
- int fieldNumber);
+ ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber);
/**
- * Obtains the value of the given field, or the default value if it is not
- * set. For primitive fields, the boxed primitive value is returned. For
- * enum fields, the EnumValueDescriptor for the value is returned. For
- * embedded message fields, the sub-message is returned. For repeated
+ * Obtains the value of the given field, or the default value if it is not set. For primitive
+ * fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for
+ * the value is returned. For embedded message fields, the sub-message is returned. For repeated
* fields, a java.util.List is returned.
*/
public Object getField(Descriptors.FieldDescriptor field);
/**
- * Returns true if the given field is set. This is exactly equivalent to
- * calling the generated "has" accessor method corresponding to the field.
+ * Returns true if the given field is set. This is exactly equivalent to calling the generated
+ * "has" accessor method corresponding to the field.
*
* @throws IllegalArgumentException The field is a repeated field, or {@code
* field.getContainingType() != getDescriptorForType()}.
@@ -262,106 +243,98 @@ class MessageReflection {
boolean hasField(Descriptors.FieldDescriptor field);
/**
- * Sets a field to the given value. The value must be of the correct type
- * for this field, i.e. the same type that
- * {@link Message#getField(Descriptors.FieldDescriptor)}
- * would return.
+ * Sets a field to the given value. The value must be of the correct type for this field, i.e.
+ * the same type that {@link Message#getField(Descriptors.FieldDescriptor)} would return.
*/
MergeTarget setField(Descriptors.FieldDescriptor field, Object value);
/**
- * Clears the field. This is exactly equivalent to calling the generated
- * "clear" accessor method corresponding to the field.
+ * Clears the field. This is exactly equivalent to calling the generated "clear" accessor method
+ * corresponding to the field.
*/
MergeTarget clearField(Descriptors.FieldDescriptor field);
/**
- * Sets an element of a repeated field to the given value. The value must
- * be of the correct type for this field, i.e. the same type that {@link
+ * Sets an element of a repeated field to the given value. The value must be of the correct type
+ * for this field, i.e. the same type that {@link
* Message#getRepeatedField(Descriptors.FieldDescriptor, int)} would return.
*
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() !=
- * getDescriptorForType()}.
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
- MergeTarget setRepeatedField(Descriptors.FieldDescriptor field,
- int index, Object value);
+ MergeTarget setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value);
/**
* Like {@code setRepeatedField}, but appends the value as a new element.
*
- * @throws IllegalArgumentException The field is not a repeated field, or
- * {@code field.getContainingType() !=
- * getDescriptorForType()}.
+ * @throws IllegalArgumentException The field is not a repeated field, or {@code
+ * field.getContainingType() != getDescriptorForType()}.
*/
- MergeTarget addRepeatedField(Descriptors.FieldDescriptor field,
- Object value);
+ MergeTarget addRepeatedField(Descriptors.FieldDescriptor field, Object value);
/**
* Returns true if the given oneof is set.
*
- * @throws IllegalArgumentException if
- * {@code oneof.getContainingType() != getDescriptorForType()}.
+ * @throws IllegalArgumentException if {@code oneof.getContainingType() !=
+ * getDescriptorForType()}.
*/
boolean hasOneof(Descriptors.OneofDescriptor oneof);
/**
- * Clears the oneof. This is exactly equivalent to calling the generated
- * "clear" accessor method corresponding to the oneof.
+ * Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method
+ * corresponding to the oneof.
*/
MergeTarget clearOneof(Descriptors.OneofDescriptor oneof);
- /**
- * Obtains the FieldDescriptor if the given oneof is set. Returns null
- * if no field is set.
- */
+ /** Obtains the FieldDescriptor if the given oneof is set. Returns null if no field is set. */
Descriptors.FieldDescriptor getOneofFieldDescriptor(Descriptors.OneofDescriptor oneof);
/**
- * Parse the input stream into a sub field group defined based on either
- * FieldDescriptor or the default instance.
+ * Parse the input stream into a sub field group defined based on either FieldDescriptor or the
+ * default instance.
*/
- Object parseGroup(CodedInputStream input, ExtensionRegistryLite registry,
- Descriptors.FieldDescriptor descriptor, Message defaultInstance)
+ Object parseGroup(
+ CodedInputStream input,
+ ExtensionRegistryLite registry,
+ Descriptors.FieldDescriptor descriptor,
+ Message defaultInstance)
throws IOException;
/**
- * Parse the input stream into a sub field message defined based on either
- * FieldDescriptor or the default instance.
+ * Parse the input stream into a sub field message defined based on either FieldDescriptor or
+ * the default instance.
*/
- Object parseMessage(CodedInputStream input, ExtensionRegistryLite registry,
- Descriptors.FieldDescriptor descriptor, Message defaultInstance)
+ Object parseMessage(
+ CodedInputStream input,
+ ExtensionRegistryLite registry,
+ Descriptors.FieldDescriptor descriptor,
+ Message defaultInstance)
throws IOException;
/**
- * Parse from a ByteString into a sub field message defined based on either
- * FieldDescriptor or the default instance. There isn't a varint indicating
- * the length of the message at the beginning of the input ByteString.
+ * Parse from a ByteString into a sub field message defined based on either FieldDescriptor or
+ * the default instance. There isn't a varint indicating the length of the message at the
+ * beginning of the input ByteString.
*/
Object parseMessageFromBytes(
- ByteString bytes, ExtensionRegistryLite registry,
- Descriptors.FieldDescriptor descriptor, Message defaultInstance)
+ ByteString bytes,
+ ExtensionRegistryLite registry,
+ Descriptors.FieldDescriptor descriptor,
+ Message defaultInstance)
throws IOException;
- /**
- * Returns the UTF8 validation level for the field.
- */
- WireFormat.Utf8Validation getUtf8Validation(Descriptors.FieldDescriptor
- descriptor);
+ /** Returns the UTF8 validation level for the field. */
+ WireFormat.Utf8Validation getUtf8Validation(Descriptors.FieldDescriptor descriptor);
/**
- * Returns a new merge target for a sub-field. When defaultInstance is
- * provided, it indicates the descriptor is for an extension type, and
- * implementations should create a new instance from the defaultInstance
- * prototype directly.
+ * Returns a new merge target for a sub-field. When defaultInstance is provided, it indicates
+ * the descriptor is for an extension type, and implementations should create a new instance
+ * from the defaultInstance prototype directly.
*/
MergeTarget newMergeTargetForField(
- Descriptors.FieldDescriptor descriptor,
- Message defaultInstance);
+ Descriptors.FieldDescriptor descriptor, Message defaultInstance);
- /**
- * Finishes the merge and returns the underlying object.
- */
+ /** Finishes the merge and returns the underlying object. */
Object finish();
}
@@ -443,8 +416,7 @@ class MessageReflection {
@Override
public ExtensionRegistry.ExtensionInfo findExtensionByNumber(
ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber) {
- return registry.findImmutableExtensionByNumber(containingType,
- fieldNumber);
+ return registry.findImmutableExtensionByNumber(containingType, fieldNumber);
}
@Override
@@ -523,8 +495,7 @@ class MessageReflection {
public MergeTarget newMergeTargetForField(
Descriptors.FieldDescriptor field, Message defaultInstance) {
if (defaultInstance != null) {
- return new BuilderAdapter(
- defaultInstance.newBuilderForType());
+ return new BuilderAdapter(defaultInstance.newBuilderForType());
} else {
return new BuilderAdapter(builder.newBuilderForField(field));
}
@@ -536,8 +507,7 @@ class MessageReflection {
return WireFormat.Utf8Validation.STRICT;
}
// TODO(liujisi): support lazy strings for repeated fields.
- if (!descriptor.isRepeated()
- && builder instanceof GeneratedMessage.Builder) {
+ if (!descriptor.isRepeated() && builder instanceof GeneratedMessage.Builder) {
return WireFormat.Utf8Validation.LAZY;
}
return WireFormat.Utf8Validation.LOOSE;
@@ -560,8 +530,7 @@ class MessageReflection {
@Override
public Descriptors.Descriptor getDescriptorForType() {
- throw new UnsupportedOperationException(
- "getDescriptorForType() called on FieldSet object");
+ throw new UnsupportedOperationException("getDescriptorForType() called on FieldSet object");
}
@Override
@@ -629,8 +598,7 @@ class MessageReflection {
@Override
public ExtensionRegistry.ExtensionInfo findExtensionByNumber(
ExtensionRegistry registry, Descriptors.Descriptor containingType, int fieldNumber) {
- return registry.findImmutableExtensionByNumber(containingType,
- fieldNumber);
+ return registry.findImmutableExtensionByNumber(containingType, fieldNumber);
}
@Override
@@ -640,8 +608,7 @@ class MessageReflection {
Descriptors.FieldDescriptor field,
Message defaultInstance)
throws IOException {
- Message.Builder subBuilder =
- defaultInstance.newBuilderForType();
+ Message.Builder subBuilder = defaultInstance.newBuilderForType();
if (!field.isRepeated()) {
Message originalMessage = (Message) getField(field);
if (originalMessage != null) {
@@ -659,8 +626,7 @@ class MessageReflection {
Descriptors.FieldDescriptor field,
Message defaultInstance)
throws IOException {
- Message.Builder subBuilder =
- defaultInstance.newBuilderForType();
+ Message.Builder subBuilder = defaultInstance.newBuilderForType();
if (!field.isRepeated()) {
Message originalMessage = (Message) getField(field);
if (originalMessage != null) {
@@ -678,7 +644,7 @@ class MessageReflection {
Descriptors.FieldDescriptor field,
Message defaultInstance)
throws IOException {
- Message.Builder subBuilder = defaultInstance.newBuilderForType();
+ Message.Builder subBuilder = defaultInstance.newBuilderForType();
if (!field.isRepeated()) {
Message originalMessage = (Message) getField(field);
if (originalMessage != null) {
@@ -692,8 +658,7 @@ class MessageReflection {
@Override
public MergeTarget newMergeTargetForField(
Descriptors.FieldDescriptor descriptor, Message defaultInstance) {
- throw new UnsupportedOperationException(
- "newMergeTargetForField() called on FieldSet object");
+ throw new UnsupportedOperationException("newMergeTargetForField() called on FieldSet object");
}
@Override
@@ -707,8 +672,7 @@ class MessageReflection {
@Override
public Object finish() {
- throw new UnsupportedOperationException(
- "finish() called on FieldSet object");
+ throw new UnsupportedOperationException("finish() called on FieldSet object");
}
}
@@ -731,8 +695,7 @@ class MessageReflection {
MergeTarget target,
int tag)
throws IOException {
- if (type.getOptions().getMessageSetWireFormat() &&
- tag == WireFormat.MESSAGE_SET_ITEM_TAG) {
+ if (type.getOptions().getMessageSetWireFormat() && tag == WireFormat.MESSAGE_SET_ITEM_TAG) {
mergeMessageSetExtensionFromCodedStream(
input, unknownFields, extensionRegistry, type, target);
return true;
@@ -752,19 +715,16 @@ class MessageReflection {
// were empty.
if (extensionRegistry instanceof ExtensionRegistry) {
final ExtensionRegistry.ExtensionInfo extension =
- target.findExtensionByNumber((ExtensionRegistry) extensionRegistry,
- type, fieldNumber);
+ target.findExtensionByNumber((ExtensionRegistry) extensionRegistry, type, fieldNumber);
if (extension == null) {
field = null;
} else {
field = extension.descriptor;
defaultInstance = extension.defaultInstance;
- if (defaultInstance == null &&
- field.getJavaType()
- == Descriptors.FieldDescriptor.JavaType.MESSAGE) {
+ if (defaultInstance == null
+ && field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalStateException(
- "Message-typed extension lacked default instance: " +
- field.getFullName());
+ "Message-typed extension lacked default instance: " + field.getFullName());
}
}
} else {
@@ -779,21 +739,19 @@ class MessageReflection {
boolean unknown = false;
boolean packed = false;
if (field == null) {
- unknown = true; // Unknown field.
- } else if (wireType == FieldSet.getWireFormatForFieldType(
- field.getLiteType(),
- false /* isPacked */)) {
+ unknown = true; // Unknown field.
+ } else if (wireType
+ == FieldSet.getWireFormatForFieldType(field.getLiteType(), /* isPacked= */ false)) {
packed = false;
- } else if (field.isPackable() &&
- wireType == FieldSet.getWireFormatForFieldType(
- field.getLiteType(),
- true /* isPacked */)) {
+ } else if (field.isPackable()
+ && wireType
+ == FieldSet.getWireFormatForFieldType(field.getLiteType(), /* isPacked= */ true)) {
packed = true;
} else {
- unknown = true; // Unknown wire type.
+ unknown = true; // Unknown wire type.
}
- if (unknown) { // Unknown field or wrong wire type. Skip.
+ if (unknown) { // Unknown field or wrong wire type. Skip.
if (unknownFields != null) {
return unknownFields.mergeFieldFrom(tag, input);
} else {
@@ -808,8 +766,8 @@ class MessageReflection {
while (input.getBytesUntilLimit() > 0) {
final int rawValue = input.readEnum();
if (field.getFile().supportsUnknownEnumValue()) {
- target.addRepeatedField(field,
- field.getEnumType().findValueByNumberCreatingIfUnknown(rawValue));
+ target.addRepeatedField(
+ field, field.getEnumType().findValueByNumberCreatingIfUnknown(rawValue));
} else {
final Object value = field.getEnumType().findValueByNumber(rawValue);
if (value == null) {
@@ -822,8 +780,9 @@ class MessageReflection {
}
} else {
while (input.getBytesUntilLimit() > 0) {
- final Object value = WireFormat.readPrimitiveField(
- input, field.getLiteType(), target.getUtf8Validation(field));
+ final Object value =
+ WireFormat.readPrimitiveField(
+ input, field.getLiteType(), target.getUtf8Validation(field));
target.addRepeatedField(field, value);
}
}
@@ -831,16 +790,16 @@ class MessageReflection {
} else {
final Object value;
switch (field.getType()) {
- case GROUP: {
- value = target
- .parseGroup(input, extensionRegistry, field, defaultInstance);
- break;
- }
- case MESSAGE: {
- value = target
- .parseMessage(input, extensionRegistry, field, defaultInstance);
- break;
- }
+ case GROUP:
+ {
+ value = target.parseGroup(input, extensionRegistry, field, defaultInstance);
+ break;
+ }
+ case MESSAGE:
+ {
+ value = target.parseMessage(input, extensionRegistry, field, defaultInstance);
+ break;
+ }
case ENUM:
final int rawValue = input.readEnum();
if (field.getFile().supportsUnknownEnumValue()) {
@@ -858,8 +817,9 @@ class MessageReflection {
}
break;
default:
- value = WireFormat.readPrimitiveField(
- input, field.getLiteType(), target.getUtf8Validation(field));
+ value =
+ WireFormat.readPrimitiveField(
+ input, field.getLiteType(), target.getUtf8Validation(field));
break;
}
@@ -873,16 +833,14 @@ class MessageReflection {
return true;
}
- /**
- * Called by {@code #mergeFieldFrom()} to parse a MessageSet extension into
- * MergeTarget.
- */
+ /** Called by {@code #mergeFieldFrom()} to parse a MessageSet extension into MergeTarget. */
private static void mergeMessageSetExtensionFromCodedStream(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
Descriptors.Descriptor type,
- MergeTarget target) throws IOException {
+ MergeTarget target)
+ throws IOException {
// The wire format for MessageSet is:
// message MessageSet {
@@ -921,19 +879,17 @@ class MessageReflection {
// extensions of it. Otherwise we will treat the registry as if it
// were empty.
if (extensionRegistry instanceof ExtensionRegistry) {
- extension = target.findExtensionByNumber(
- (ExtensionRegistry) extensionRegistry, type, typeId);
+ extension =
+ target.findExtensionByNumber((ExtensionRegistry) extensionRegistry, type, typeId);
}
}
} else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) {
if (typeId != 0) {
- if (extension != null &&
- ExtensionRegistryLite.isEagerlyParseMessageSets()) {
+ if (extension != null && ExtensionRegistryLite.isEagerlyParseMessageSets()) {
// We already know the type, so we can parse directly from the
// input with no copying. Hooray!
- eagerlyMergeMessageSetExtension(
- input, extension, extensionRegistry, target);
+ eagerlyMergeMessageSetExtension(input, extension, extensionRegistry, target);
rawBytes = null;
continue;
}
@@ -952,12 +908,11 @@ class MessageReflection {
// Process the raw bytes.
if (rawBytes != null && typeId != 0) { // Zero is not a valid type ID.
if (extension != null) { // We known the type
- mergeMessageSetExtensionFromBytes(
- rawBytes, extension, extensionRegistry, target);
+ mergeMessageSetExtensionFromBytes(rawBytes, extension, extensionRegistry, target);
} else { // We don't know how to parse this. Ignore it.
if (rawBytes != null && unknownFields != null) {
- unknownFields.mergeField(typeId, UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(rawBytes).build());
+ unknownFields.mergeField(
+ typeId, UnknownFieldSet.Field.newBuilder().addLengthDelimited(rawBytes).build());
}
}
}
@@ -967,20 +922,21 @@ class MessageReflection {
ByteString rawBytes,
ExtensionRegistry.ExtensionInfo extension,
ExtensionRegistryLite extensionRegistry,
- MergeTarget target) throws IOException {
+ MergeTarget target)
+ throws IOException {
Descriptors.FieldDescriptor field = extension.descriptor;
boolean hasOriginalValue = target.hasField(field);
if (hasOriginalValue || ExtensionRegistryLite.isEagerlyParseMessageSets()) {
// If the field already exists, we just parse the field.
- Object value = target.parseMessageFromBytes(
- rawBytes, extensionRegistry,field, extension.defaultInstance);
+ Object value =
+ target.parseMessageFromBytes(
+ rawBytes, extensionRegistry, field, extension.defaultInstance);
target.setField(field, value);
} else {
// Use LazyField to load MessageSet lazily.
- LazyField lazyField = new LazyField(
- extension.defaultInstance, extensionRegistry, rawBytes);
+ LazyField lazyField = new LazyField(extension.defaultInstance, extensionRegistry, rawBytes);
target.setField(field, lazyField);
}
}
@@ -989,10 +945,10 @@ class MessageReflection {
CodedInputStream input,
ExtensionRegistry.ExtensionInfo extension,
ExtensionRegistryLite extensionRegistry,
- MergeTarget target) throws IOException {
+ MergeTarget target)
+ throws IOException {
Descriptors.FieldDescriptor field = extension.descriptor;
- Object value = target.parseMessage(input, extensionRegistry, field,
- extension.defaultInstance);
+ Object value = target.parseMessage(input, extensionRegistry, field, extension.defaultInstance);
target.setField(field, value);
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java b/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java
index 82b723c9..7c2f1575 100644
--- a/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java
+++ b/java/core/src/main/java/com/google/protobuf/MutabilityOracle.java
@@ -30,19 +30,16 @@
package com.google.protobuf;
-/**
- * Verifies that an object is mutable, throwing if not.
- */
+/** Verifies that an object is mutable, throwing if not. */
interface MutabilityOracle {
- static final MutabilityOracle IMMUTABLE = new MutabilityOracle() {
- @Override
- public void ensureMutable() {
- throw new UnsupportedOperationException();
- }
- };
+ static final MutabilityOracle IMMUTABLE =
+ new MutabilityOracle() {
+ @Override
+ public void ensureMutable() {
+ throw new UnsupportedOperationException();
+ }
+ };
- /**
- * Throws an {@link UnsupportedOperationException} if not mutable.
- */
+ /** Throws an {@link UnsupportedOperationException} if not mutable. */
void ensureMutable();
}
diff --git a/java/core/src/main/java/com/google/protobuf/NioByteString.java b/java/core/src/main/java/com/google/protobuf/NioByteString.java
index 76594809..64de6b1b 100644
--- a/java/core/src/main/java/com/google/protobuf/NioByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/NioByteString.java
@@ -44,9 +44,7 @@ import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
-/**
- * A {@link ByteString} that wraps around a {@link ByteBuffer}.
- */
+/** A {@link ByteString} that wraps around a {@link ByteBuffer}. */
final class NioByteString extends ByteString.LeafByteString {
private final ByteBuffer buffer;
@@ -60,16 +58,12 @@ final class NioByteString extends ByteString.LeafByteString {
// =================================================================
// Serializable
- /**
- * Magic method that lets us override serialization behavior.
- */
+ /** Magic method that lets us override serialization behavior. */
private Object writeReplace() {
return ByteString.copyFrom(buffer.slice());
}
- /**
- * Magic method that lets us override deserialization behavior.
- */
+ /** Magic method that lets us override deserialization behavior. */
private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException {
throw new InvalidObjectException("NioByteString instances are not to be serialized directly");
}
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 e07c6895..259b5a68 100644
--- a/java/core/src/main/java/com/google/protobuf/Parser.java
+++ b/java/core/src/main/java/com/google/protobuf/Parser.java
@@ -36,7 +36,7 @@ import java.nio.ByteBuffer;
/**
* Abstract interface for parsing Protocol Messages.
*
- * The implementation should be stateless and thread-safe.
+ * <p>The implementation should be stateless and thread-safe.
*
* <p>All methods may throw {@link InvalidProtocolBufferException}. In the event of invalid data,
* like an encoding error, the cause of the thrown exception will be {@code null}. However, if an
@@ -55,39 +55,31 @@ public interface Parser<MessageType> {
/**
* Parses a message of {@code MessageType} from the input.
*
- * <p>Note: The caller should call
- * {@link CodedInputStream#checkLastTagWas(int)} after calling this to
- * verify that the last tag seen was the appropriate end-group tag,
- * or zero for EOF.
+ * <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling
+ * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF.
*/
- public MessageType parseFrom(CodedInputStream input)
- throws InvalidProtocolBufferException;
+ public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(CodedInputStream)}, but also parses extensions.
- * The extensions that you want to be able to parse must be registered in
- * {@code extensionRegistry}. Extensions not in the registry will be treated
- * as unknown fields.
+ * Like {@link #parseFrom(CodedInputStream)}, but also parses extensions. The extensions that you
+ * want to be able to parse must be registered in {@code extensionRegistry}. Extensions not in the
+ * registry will be treated as unknown fields.
*/
- public MessageType parseFrom(CodedInputStream input,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(CodedInputStream)}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseFrom(CodedInputStream)}, but does not throw an exception if the message is
+ * missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(CodedInputStream input)
- throws InvalidProtocolBufferException;
+ public MessageType parsePartialFrom(CodedInputStream input) throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)}, but does not throw an
+ * exception if the message is missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(CodedInputStream input,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parsePartialFrom(
+ CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
// ---------------------------------------------------------------
@@ -106,180 +98,145 @@ public interface Parser<MessageType> {
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)}.
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream)}.
*/
- public MessageType parseFrom(ByteString data)
- throws InvalidProtocolBufferException;
+ public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException;
/**
- * Parses {@code data} as a message of {@code MessageType}.
- * This is just a small wrapper around
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
- public MessageType parseFrom(ByteString data,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(ByteString)}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseFrom(ByteString)}, but does not throw an exception if the message is missing
+ * required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(ByteString data)
- throws InvalidProtocolBufferException;
+ public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if
+ * the message is missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(ByteString data,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Parses {@code data} as a message of {@code MessageType}.
- * This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream)}.
*/
- public MessageType parseFrom(byte[] data, int off, int len)
- throws InvalidProtocolBufferException;
+ public MessageType parseFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
/**
- * Parses {@code data} as a message of {@code MessageType}.
- * This is just a small wrapper around
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
- public MessageType parseFrom(byte[] data, int off, int len,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parseFrom(
+ byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Parses {@code data} as a message of {@code MessageType}.
- * This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream)}.
*/
- public MessageType parseFrom(byte[] data)
- throws InvalidProtocolBufferException;
+ public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException;
/**
- * Parses {@code data} as a message of {@code MessageType}.
- * This is just a small wrapper around
+ * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
- public MessageType parseFrom(byte[] data,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(byte[], int, int)}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseFrom(byte[], int, int)}, but does not throw an exception if the message is
+ * missing required fields. Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(byte[] data, int off, int len)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if
+ * the message is missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(byte[] data, int off, int len,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parsePartialFrom(
+ byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(byte[])}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseFrom(byte[])}, but does not throw an exception if the message is missing
+ * required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(byte[] data)
- throws InvalidProtocolBufferException;
+ public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(byte[], ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseFrom(byte[], ExtensionRegistryLite)}, but does not throw an exception if the
+ * message is missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(byte[] data,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Parse a message of {@code MessageType} from {@code input}.
- * This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
- * Note that this method always reads the <i>entire</i> input (unless it
- * throws an exception). If you want it to stop earlier, you will need to
- * wrap your input in some wrapper stream that limits reading. Or, use
- * {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your
- * message and {@link #parseDelimitedFrom(InputStream)} to read it.
- * <p>
- * Despite usually reading the entire input, this does not close the stream.
+ * Parse a message of {@code MessageType} from {@code input}. This is just a small wrapper around
+ * {@link #parseFrom(CodedInputStream)}. Note that this method always reads the <i>entire</i>
+ * input (unless it throws an exception). If you want it to stop earlier, you will need to wrap
+ * your input in some wrapper stream that limits reading. Or, use {@link
+ * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your message and {@link
+ * #parseDelimitedFrom(InputStream)} to read it.
+ *
+ * <p>Despite usually reading the entire input, this does not close the stream.
*/
- public MessageType parseFrom(InputStream input)
- throws InvalidProtocolBufferException;
+ public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException;
/**
- * Parses a message of {@code MessageType} from {@code input}.
- * This is just a small wrapper around
+ * Parses a message of {@code MessageType} from {@code input}. This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
- public MessageType parseFrom(InputStream input,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(InputStream)}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseFrom(InputStream)}, but does not throw an exception if the message is missing
+ * required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(InputStream input)
- throws InvalidProtocolBufferException;
+ public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, but does not throw an exception if
+ * the message is missing required fields. Instead, a partial message is returned.
*/
- public MessageType parsePartialFrom(InputStream input,
- ExtensionRegistryLite extensionRegistry)
+ public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseFrom(InputStream)}, but does not read util EOF.
- * Instead, the size of message (encoded as a varint) is read first,
- * then the message data. Use
- * {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} to write
- * messages in this format.
+ * Like {@link #parseFrom(InputStream)}, but does not read util EOF. Instead, the size of message
+ * (encoded as a varint) is read first, then the message data. Use {@link
+ * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write messages in this format.
*
- * @return Parsed message if successful, or null if the stream is at EOF when
- * the method starts. Any other error (including reaching EOF during
- * parsing) will cause an exception to be thrown.
+ * @return Parsed message if successful, or null if the stream is at EOF when the method starts.
+ * Any other error (including reaching EOF during parsing) will cause an exception to be
+ * thrown.
*/
- public MessageType parseDelimitedFrom(InputStream input)
- throws InvalidProtocolBufferException;
+ public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException;
- /**
- * Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions.
- */
- public MessageType parseDelimitedFrom(InputStream input,
- ExtensionRegistryLite extensionRegistry)
+ /** Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. */
+ public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an
- * exception if the message is missing required fields. Instead, a partial
- * message is returned.
+ * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an exception if the message
+ * is missing required fields. Instead, a partial message is returned.
*/
public MessageType parsePartialDelimitedFrom(InputStream input)
throws InvalidProtocolBufferException;
/**
- * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)},
- * but does not throw an exception if the message is missing required fields.
- * Instead, a partial message is returned.
+ * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, but does not throw an
+ * exception if the message is missing required fields. Instead, a partial message is returned.
*/
public MessageType parsePartialDelimitedFrom(
- InputStream input,
- ExtensionRegistryLite extensionRegistry)
+ InputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
}
diff --git a/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java b/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java
index 81255ec2..98341613 100644
--- a/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java
+++ b/java/core/src/main/java/com/google/protobuf/ProtobufArrayList.java
@@ -31,31 +31,29 @@
package com.google.protobuf;
import com.google.protobuf.Internal.ProtobufList;
-
import java.util.ArrayList;
import java.util.List;
-/**
- * Implements {@link ProtobufList} for non-primitive and {@link String} types.
- */
+/** Implements {@link ProtobufList} for non-primitive and {@link String} types. */
final class ProtobufArrayList<E> extends AbstractProtobufList<E> {
private static final ProtobufArrayList<Object> EMPTY_LIST = new ProtobufArrayList<Object>();
+
static {
EMPTY_LIST.makeImmutable();
}
-
+
@SuppressWarnings("unchecked") // Guaranteed safe by runtime.
public static <E> ProtobufArrayList<E> emptyList() {
return (ProtobufArrayList<E>) EMPTY_LIST;
}
-
+
private final List<E> list;
ProtobufArrayList() {
this(new ArrayList<E>(DEFAULT_CAPACITY));
}
-
+
private ProtobufArrayList(List<E> list) {
this.list = list;
}
@@ -69,7 +67,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> {
newList.addAll(list);
return new ProtobufArrayList<E>(newList);
}
-
+
@Override
public void add(int index, E element) {
ensureIsMutable();
@@ -81,7 +79,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> {
public E get(int index) {
return list.get(index);
}
-
+
@Override
public E remove(int index) {
ensureIsMutable();
@@ -89,7 +87,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> {
modCount++;
return toReturn;
}
-
+
@Override
public E set(int index, E element) {
ensureIsMutable();
diff --git a/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java b/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java
index a596d301..5d6f5ac4 100644
--- a/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java
+++ b/java/core/src/main/java/com/google/protobuf/ProtocolMessageEnum.java
@@ -33,27 +33,20 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
-/**
- * Interface of useful methods added to all enums generated by the protocol
- * compiler.
- */
+/** Interface of useful methods added to all enums generated by the protocol compiler. */
public interface ProtocolMessageEnum extends Internal.EnumLite {
- /**
- * Return the value's numeric value as defined in the .proto file.
- */
+ /** Return the value's numeric value as defined in the .proto file. */
@Override
int getNumber();
/**
- * Return the value's descriptor, which contains information such as
- * value name, number, and type.
+ * Return the value's descriptor, which contains information such as value name, number, and type.
*/
EnumValueDescriptor getValueDescriptor();
/**
- * Return the enum type's descriptor, which contains information
- * about each defined value, etc.
+ * Return the enum type's descriptor, which contains information about each defined value, etc.
*/
EnumDescriptor getDescriptorForType();
}
diff --git a/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java b/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java
index d553b41e..5df3dbdb 100644
--- a/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java
+++ b/java/core/src/main/java/com/google/protobuf/ProtocolStringList.java
@@ -33,16 +33,14 @@ package com.google.protobuf;
import java.util.List;
/**
- * An interface extending {@code List<String>} used for repeated string fields
- * to provide optional access to the data as a list of ByteStrings. The
- * underlying implementation stores values as either ByteStrings or Strings
- * (see {@link LazyStringArrayList}) depending on how the value was initialized
- * or last read, and it is often more efficient to deal with lists of
- * ByteStrings when handling protos that have been deserialized from bytes.
+ * An interface extending {@code List<String>} used for repeated string fields to provide optional
+ * access to the data as a list of ByteStrings. The underlying implementation stores values as
+ * either ByteStrings or Strings (see {@link LazyStringArrayList}) depending on how the value was
+ * initialized or last read, and it is often more efficient to deal with lists of ByteStrings when
+ * handling protos that have been deserialized from bytes.
*/
public interface ProtocolStringList extends List<String> {
/** Returns a view of the data as a list of ByteStrings. */
List<ByteString> asByteStringList();
-
}
diff --git a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
index 29f567dc..f3b09fba 100644
--- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilder.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;
@@ -37,36 +39,29 @@ import java.util.Collections;
import java.util.List;
/**
- * {@code RepeatedFieldBuilder} implements a structure that a protocol
- * message uses to hold a repeated field of other protocol messages. It supports
- * the classical use case of adding immutable {@link Message}'s to the
- * repeated field and is highly optimized around this (no extra memory
- * allocations and sharing of immutable arrays).
- * <br>
- * It also supports the additional use case of adding a {@link Message.Builder}
- * to the repeated field and deferring conversion of that {@code Builder}
- * to an immutable {@code Message}. In this way, it's possible to maintain
- * a tree of {@code Builder}'s that acts as a fully read/write data
- * structure.
- * <br>
- * Logically, one can think of a tree of builders as converting the entire tree
- * to messages when build is called on the root or when any method is called
- * that desires a Message instead of a Builder. In terms of the implementation,
- * the {@code SingleFieldBuilder} and {@code RepeatedFieldBuilder}
- * classes cache messages that were created so that messages only need to be
- * created when some change occurred in its builder or a builder for one of its
- * descendants.
+ * {@code RepeatedFieldBuilder} implements a structure that a protocol message uses to hold a
+ * repeated field of other protocol messages. It supports the classical use case of adding immutable
+ * {@link Message}'s to the repeated field and is highly optimized around this (no extra memory
+ * allocations and sharing of immutable arrays). <br>
+ * It also supports the additional use case of adding a {@link Message.Builder} to the repeated
+ * field and deferring conversion of that {@code Builder} to an immutable {@code Message}. In this
+ * way, it's possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data
+ * structure. <br>
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when
+ * build is called on the root or when any method is called that desires a Message instead of a
+ * Builder. In terms of the implementation, the {@code SingleFieldBuilder} and {@code
+ * RepeatedFieldBuilder} classes cache messages that were created so that messages only need to be
+ * created when some change occurred in its builder or a builder for one of its descendants.
*
* @param <MType> the type of message for the field
* @param <BType> the type of builder for the field
* @param <IType> the common interface for the message and the builder
- *
* @author jonp@google.com (Jon Perlow)
*/
-public class RepeatedFieldBuilder
- <MType extends GeneratedMessage,
- BType extends GeneratedMessage.Builder,
- IType extends MessageOrBuilder>
+public class RepeatedFieldBuilder<
+ MType extends GeneratedMessage,
+ BType extends GeneratedMessage.Builder,
+ IType extends MessageOrBuilder>
implements GeneratedMessage.BuilderParent {
// Parent to send changes to.
@@ -118,8 +113,7 @@ public class RepeatedFieldBuilder
// is fully backed by this object and all changes are reflected in it.
// Access to any item returns either a builder or message depending on
// what is most efficient.
- private MessageOrBuilderExternalList<MType, BType, IType>
- externalMessageOrBuilderList;
+ private MessageOrBuilderExternalList<MType, BType, IType> externalMessageOrBuilderList;
/**
* Constructs a new builder with an empty list of messages.
@@ -146,8 +140,8 @@ public class RepeatedFieldBuilder
}
/**
- * Ensures that the list of messages is mutable so it can be updated. If it's
- * immutable, a copy is made.
+ * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is
+ * made.
*/
private void ensureMutableMessageList() {
if (!isMessagesListMutable) {
@@ -157,15 +151,12 @@ public class RepeatedFieldBuilder
}
/**
- * Ensures that the list of builders is not null. If it's null, the list is
- * created and initialized to be the same size as the messages list with
- * null entries.
+ * Ensures that the list of builders is not null. If it's null, the list is created and
+ * initialized to be the same size as the messages list with null entries.
*/
private void ensureBuilders() {
if (this.builders == null) {
- this.builders =
- new ArrayList<SingleFieldBuilder<MType, BType, IType>>(
- messages.size());
+ this.builders = new ArrayList<SingleFieldBuilder<MType, BType, IType>>(messages.size());
for (int i = 0; i < messages.size(); i++) {
builders.add(null);
}
@@ -191,9 +182,9 @@ public class RepeatedFieldBuilder
}
/**
- * Get the message at the specified index. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it.
+ * Get the message at the specified index. If the message is currently stored as a {@code
+ * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial}
+ * on it.
*
* @param index the index of the message to get
* @return the message for the specified index
@@ -203,13 +194,13 @@ public class RepeatedFieldBuilder
}
/**
- * Get the message at the specified index. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it.
+ * Get the message at the specified index. If the message is currently stored as a {@code
+ * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial}
+ * on it.
*
* @param index the index of the message to get
- * @param forBuild this is being called for build so we want to make sure
- * we SingleFieldBuilder.build to send dirty invalidations
+ * @param forBuild this is being called for build so we want to make sure we
+ * SingleFieldBuilder.build to send dirty invalidations
* @return the message for the specified index
*/
private MType getMessage(int index, boolean forBuild) {
@@ -233,9 +224,8 @@ public class RepeatedFieldBuilder
}
/**
- * Gets a builder for the specified index. If no builder has been created for
- * that index, a builder is created on demand by calling
- * {@link Message#toBuilder}.
+ * Gets a builder for the specified index. If no builder has been created for that index, a
+ * builder is created on demand by calling {@link Message#toBuilder}.
*
* @param index the index of the message to get
* @return The builder for that index
@@ -245,16 +235,15 @@ public class RepeatedFieldBuilder
SingleFieldBuilder<MType, BType, IType> builder = builders.get(index);
if (builder == null) {
MType message = messages.get(index);
- builder = new SingleFieldBuilder<MType, BType, IType>(
- message, this, isClean);
+ builder = new SingleFieldBuilder<MType, BType, IType>(message, this, isClean);
builders.set(index, builder);
}
return builder.getBuilder();
}
/**
- * Gets the base class interface for the specified index. This may either be
- * a builder or a message. It will return whatever is more efficient.
+ * Gets the base class interface for the specified index. This may either be a builder or a
+ * message. It will return whatever is more efficient.
*
* @param index the index of the message to get
* @return the message or builder for the index as the base class interface
@@ -281,23 +270,18 @@ public class RepeatedFieldBuilder
}
/**
- * Sets a message at the specified index replacing the existing item at
- * that index.
+ * Sets a message at the specified index replacing the existing item at that index.
*
* @param index the index to set.
* @param message the message to set
* @return the builder
*/
- public RepeatedFieldBuilder<MType, BType, IType> setMessage(
- int index, MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ public RepeatedFieldBuilder<MType, BType, IType> setMessage(int index, MType message) {
+ checkNotNull(message);
ensureMutableMessageList();
messages.set(index, message);
if (builders != null) {
- SingleFieldBuilder<MType, BType, IType> entry =
- builders.set(index, null);
+ SingleFieldBuilder<MType, BType, IType> entry = builders.set(index, null);
if (entry != null) {
entry.dispose();
}
@@ -313,11 +297,8 @@ public class RepeatedFieldBuilder
* @param message the message to add
* @return the builder
*/
- public RepeatedFieldBuilder<MType, BType, IType> addMessage(
- MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ public RepeatedFieldBuilder<MType, BType, IType> addMessage(MType message) {
+ checkNotNull(message);
ensureMutableMessageList();
messages.add(message);
if (builders != null) {
@@ -329,19 +310,16 @@ public class RepeatedFieldBuilder
}
/**
- * Inserts the specified message at the specified position in this list.
- * Shifts the element currently at that position (if any) and any subsequent
- * elements to the right (adds one to their indices).
+ * Inserts the specified message at the specified position in this list. Shifts the element
+ * currently at that position (if any) and any subsequent elements to the right (adds one to their
+ * indices).
*
* @param index the index at which to insert the message
* @param message the message to add
* @return the builder
*/
- public RepeatedFieldBuilder<MType, BType, IType> addMessage(
- int index, MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
+ public RepeatedFieldBuilder<MType, BType, IType> addMessage(int index, MType message) {
+ checkNotNull(message);
ensureMutableMessageList();
messages.add(index, message);
if (builders != null) {
@@ -353,9 +331,8 @@ public class RepeatedFieldBuilder
}
/**
- * Appends all of the messages in the specified collection to the end of
- * this list, in the order that they are returned by the specified
- * collection's iterator.
+ * Appends all of the messages in the specified collection to the end of this list, in the order
+ * that they are returned by the specified collection's iterator.
*
* @param values the messages to add
* @return the builder
@@ -363,16 +340,14 @@ public class RepeatedFieldBuilder
public RepeatedFieldBuilder<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.
int size = -1;
if (values instanceof Collection) {
- @SuppressWarnings("unchecked") final
- Collection<MType> collection = (Collection<MType>) values;
+ @SuppressWarnings("unchecked")
+ final Collection<MType> collection = (Collection<MType>) values;
if (collection.size() == 0) {
return this;
}
@@ -381,8 +356,7 @@ public class RepeatedFieldBuilder
ensureMutableMessageList();
if (size >= 0 && messages instanceof ArrayList) {
- ((ArrayList<MType>) messages)
- .ensureCapacity(messages.size() + size);
+ ((ArrayList<MType>) messages).ensureCapacity(messages.size() + size);
}
for (MType value : values) {
@@ -404,8 +378,7 @@ public class RepeatedFieldBuilder
ensureMutableMessageList();
ensureBuilders();
SingleFieldBuilder<MType, BType, IType> builder =
- new SingleFieldBuilder<MType, BType, IType>(
- message, this, isClean);
+ new SingleFieldBuilder<MType, BType, IType>(message, this, isClean);
messages.add(null);
builders.add(builder);
onChanged();
@@ -414,9 +387,8 @@ public class RepeatedFieldBuilder
}
/**
- * Inserts a new builder at the specified position in this list.
- * Shifts the element currently at that position (if any) and any subsequent
- * elements to the right (adds one to their indices).
+ * Inserts a new builder at the specified position in this list. Shifts the element currently at
+ * that position (if any) and any subsequent elements to the right (adds one to their indices).
*
* @param index the index at which to insert the builder
* @param message the message to add which is the basis of the builder
@@ -426,8 +398,7 @@ public class RepeatedFieldBuilder
ensureMutableMessageList();
ensureBuilders();
SingleFieldBuilder<MType, BType, IType> builder =
- new SingleFieldBuilder<MType, BType, IType>(
- message, this, isClean);
+ new SingleFieldBuilder<MType, BType, IType>(message, this, isClean);
messages.add(index, null);
builders.add(index, builder);
onChanged();
@@ -436,9 +407,9 @@ public class RepeatedFieldBuilder
}
/**
- * Removes the element at the specified position in this list. Shifts any
- * subsequent elements to the left (subtracts one from their indices).
- * Returns the element that was removed from the list.
+ * Removes the element at the specified position in this list. Shifts any subsequent elements to
+ * the left (subtracts one from their indices). Returns the element that was removed from the
+ * list.
*
* @param index the index at which to remove the message
*/
@@ -446,8 +417,7 @@ public class RepeatedFieldBuilder
ensureMutableMessageList();
messages.remove(index);
if (builders != null) {
- SingleFieldBuilder<MType, BType, IType> entry =
- builders.remove(index);
+ SingleFieldBuilder<MType, BType, IType> entry = builders.remove(index);
if (entry != null) {
entry.dispose();
}
@@ -456,16 +426,12 @@ public class RepeatedFieldBuilder
incrementModCounts();
}
- /**
- * Removes all of the elements from this list.
- * The list will be empty after this call returns.
- */
+ /** Removes all of the elements from this list. The list will be empty after this call returns. */
public void clear() {
messages = Collections.emptyList();
isMessagesListMutable = false;
if (builders != null) {
- for (SingleFieldBuilder<MType, BType, IType> entry :
- builders) {
+ for (SingleFieldBuilder<MType, BType, IType> entry : builders) {
if (entry != null) {
entry.dispose();
}
@@ -525,50 +491,47 @@ public class RepeatedFieldBuilder
}
/**
- * Gets a view of the builder as a list of messages. The returned list is live
- * and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of messages. The returned list is live and will reflect
+ * any changes to the underlying builder.
*
* @return the messages in the list
*/
public List<MType> getMessageList() {
if (externalMessageList == null) {
- externalMessageList =
- new MessageExternalList<MType, BType, IType>(this);
+ externalMessageList = new MessageExternalList<MType, BType, IType>(this);
}
return externalMessageList;
}
/**
- * Gets a view of the builder as a list of builders. This returned list is
- * live and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of builders. This returned list is live and will reflect
+ * any changes to the underlying builder.
*
* @return the builders in the list
*/
public List<BType> getBuilderList() {
if (externalBuilderList == null) {
- externalBuilderList =
- new BuilderExternalList<MType, BType, IType>(this);
+ externalBuilderList = new BuilderExternalList<MType, BType, IType>(this);
}
return externalBuilderList;
}
/**
- * Gets a view of the builder as a list of MessageOrBuilders. This returned
- * list is live and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will
+ * reflect any changes to the underlying builder.
*
* @return the builders in the list
*/
public List<IType> getMessageOrBuilderList() {
if (externalMessageOrBuilderList == null) {
- externalMessageOrBuilderList =
- new MessageOrBuilderExternalList<MType, BType, IType>(this);
+ externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(this);
}
return externalMessageOrBuilderList;
}
/**
- * Called when a the builder or one of its nested children has changed
- * and any parent should be notified of its invalidation.
+ * Called when a the builder or one of its nested children has changed and any parent should be
+ * notified of its invalidation.
*/
private void onChanged() {
if (isClean && parent != null) {
@@ -585,9 +548,8 @@ public class RepeatedFieldBuilder
}
/**
- * Increments the mod counts so that an ConcurrentModificationException can
- * be thrown if calling code tries to modify the builder while its iterating
- * the list.
+ * Increments the mod counts so that an ConcurrentModificationException can be thrown if calling
+ * code tries to modify the builder while its iterating the list.
*/
private void incrementModCounts() {
if (externalMessageList != null) {
@@ -609,15 +571,14 @@ public class RepeatedFieldBuilder
* @param <IType> the common interface for the message and the builder
*/
private static class MessageExternalList<
- MType extends GeneratedMessage,
- BType extends GeneratedMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends GeneratedMessage,
+ BType extends GeneratedMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<MType> implements List<MType> {
RepeatedFieldBuilder<MType, BType, IType> builder;
- MessageExternalList(
- RepeatedFieldBuilder<MType, BType, IType> builder) {
+ MessageExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) {
this.builder = builder;
}
@@ -644,15 +605,14 @@ public class RepeatedFieldBuilder
* @param <IType> the common interface for the message and the builder
*/
private static class BuilderExternalList<
- MType extends GeneratedMessage,
- BType extends GeneratedMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends GeneratedMessage,
+ BType extends GeneratedMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<BType> implements List<BType> {
RepeatedFieldBuilder<MType, BType, IType> builder;
- BuilderExternalList(
- RepeatedFieldBuilder<MType, BType, IType> builder) {
+ BuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) {
this.builder = builder;
}
@@ -679,15 +639,14 @@ public class RepeatedFieldBuilder
* @param <IType> the common interface for the message and the builder
*/
private static class MessageOrBuilderExternalList<
- MType extends GeneratedMessage,
- BType extends GeneratedMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends GeneratedMessage,
+ BType extends GeneratedMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<IType> implements List<IType> {
RepeatedFieldBuilder<MType, BType, IType> builder;
- MessageOrBuilderExternalList(
- RepeatedFieldBuilder<MType, BType, IType> builder) {
+ MessageOrBuilderExternalList(RepeatedFieldBuilder<MType, BType, IType> builder) {
this.builder = builder;
}
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 30c991d4..fb1667c4 100644
--- a/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
+++ b/java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
@@ -39,36 +39,29 @@ import java.util.Collections;
import java.util.List;
/**
- * {@code RepeatedFieldBuilderV3} implements a structure that a protocol
- * message uses to hold a repeated field of other protocol messages. It supports
- * the classical use case of adding immutable {@link Message}'s to the
- * repeated field and is highly optimized around this (no extra memory
- * allocations and sharing of immutable arrays).
- * <br>
- * It also supports the additional use case of adding a {@link Message.Builder}
- * to the repeated field and deferring conversion of that {@code Builder}
- * to an immutable {@code Message}. In this way, it's possible to maintain
- * a tree of {@code Builder}'s that acts as a fully read/write data
- * structure.
- * <br>
- * Logically, one can think of a tree of builders as converting the entire tree
- * to messages when build is called on the root or when any method is called
- * that desires a Message instead of a Builder. In terms of the implementation,
- * the {@code SingleFieldBuilderV3} and {@code RepeatedFieldBuilderV3}
- * classes cache messages that were created so that messages only need to be
- * created when some change occurred in its builder or a builder for one of its
- * descendants.
+ * {@code RepeatedFieldBuilderV3} implements a structure that a protocol message uses to hold a
+ * repeated field of other protocol messages. It supports the classical use case of adding immutable
+ * {@link Message}'s to the repeated field and is highly optimized around this (no extra memory
+ * allocations and sharing of immutable arrays). <br>
+ * It also supports the additional use case of adding a {@link Message.Builder} to the repeated
+ * field and deferring conversion of that {@code Builder} to an immutable {@code Message}. In this
+ * way, it's possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data
+ * structure. <br>
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when
+ * build is called on the root or when any method is called that desires a Message instead of a
+ * Builder. In terms of the implementation, the {@code SingleFieldBuilderV3} and {@code
+ * RepeatedFieldBuilderV3} classes cache messages that were created so that messages only need to be
+ * created when some change occurred in its builder or a builder for one of its descendants.
*
* @param <MType> the type of message for the field
* @param <BType> the type of builder for the field
* @param <IType> the common interface for the message and the builder
- *
* @author jonp@google.com (Jon Perlow)
*/
-public class RepeatedFieldBuilderV3
- <MType extends AbstractMessage,
- BType extends AbstractMessage.Builder,
- IType extends MessageOrBuilder>
+public class RepeatedFieldBuilderV3<
+ MType extends AbstractMessage,
+ BType extends AbstractMessage.Builder,
+ IType extends MessageOrBuilder>
implements AbstractMessage.BuilderParent {
// Parent to send changes to.
@@ -120,8 +113,7 @@ public class RepeatedFieldBuilderV3
// is fully backed by this object and all changes are reflected in it.
// Access to any item returns either a builder or message depending on
// what is most efficient.
- private MessageOrBuilderExternalList<MType, BType, IType>
- externalMessageOrBuilderList;
+ private MessageOrBuilderExternalList<MType, BType, IType> externalMessageOrBuilderList;
/**
* Constructs a new builder with an empty list of messages.
@@ -148,8 +140,8 @@ public class RepeatedFieldBuilderV3
}
/**
- * Ensures that the list of messages is mutable so it can be updated. If it's
- * immutable, a copy is made.
+ * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is
+ * made.
*/
private void ensureMutableMessageList() {
if (!isMessagesListMutable) {
@@ -159,15 +151,12 @@ public class RepeatedFieldBuilderV3
}
/**
- * Ensures that the list of builders is not null. If it's null, the list is
- * created and initialized to be the same size as the messages list with
- * null entries.
+ * Ensures that the list of builders is not null. If it's null, the list is created and
+ * initialized to be the same size as the messages list with null entries.
*/
private void ensureBuilders() {
if (this.builders == null) {
- this.builders =
- new ArrayList<SingleFieldBuilderV3<MType, BType, IType>>(
- messages.size());
+ this.builders = new ArrayList<SingleFieldBuilderV3<MType, BType, IType>>(messages.size());
for (int i = 0; i < messages.size(); i++) {
builders.add(null);
}
@@ -193,9 +182,9 @@ public class RepeatedFieldBuilderV3
}
/**
- * Get the message at the specified index. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it.
+ * Get the message at the specified index. If the message is currently stored as a {@code
+ * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial}
+ * on it.
*
* @param index the index of the message to get
* @return the message for the specified index
@@ -205,13 +194,13 @@ public class RepeatedFieldBuilderV3
}
/**
- * Get the message at the specified index. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it.
+ * Get the message at the specified index. If the message is currently stored as a {@code
+ * Builder}, it is converted to a {@code Message} by calling {@link Message.Builder#buildPartial}
+ * on it.
*
* @param index the index of the message to get
- * @param forBuild this is being called for build so we want to make sure
- * we SingleFieldBuilderV3.build to send dirty invalidations
+ * @param forBuild this is being called for build so we want to make sure we
+ * SingleFieldBuilderV3.build to send dirty invalidations
* @return the message for the specified index
*/
private MType getMessage(int index, boolean forBuild) {
@@ -235,9 +224,8 @@ public class RepeatedFieldBuilderV3
}
/**
- * Gets a builder for the specified index. If no builder has been created for
- * that index, a builder is created on demand by calling
- * {@link Message#toBuilder}.
+ * Gets a builder for the specified index. If no builder has been created for that index, a
+ * builder is created on demand by calling {@link Message#toBuilder}.
*
* @param index the index of the message to get
* @return The builder for that index
@@ -247,16 +235,15 @@ public class RepeatedFieldBuilderV3
SingleFieldBuilderV3<MType, BType, IType> builder = builders.get(index);
if (builder == null) {
MType message = messages.get(index);
- builder = new SingleFieldBuilderV3<MType, BType, IType>(
- message, this, isClean);
+ builder = new SingleFieldBuilderV3<MType, BType, IType>(message, this, isClean);
builders.set(index, builder);
}
return builder.getBuilder();
}
/**
- * Gets the base class interface for the specified index. This may either be
- * a builder or a message. It will return whatever is more efficient.
+ * Gets the base class interface for the specified index. This may either be a builder or a
+ * message. It will return whatever is more efficient.
*
* @param index the index of the message to get
* @return the message or builder for the index as the base class interface
@@ -283,21 +270,18 @@ public class RepeatedFieldBuilderV3
}
/**
- * Sets a message at the specified index replacing the existing item at
- * that index.
+ * Sets a message at the specified index replacing the existing item at that index.
*
* @param index the index to set.
* @param message the message to set
* @return the builder
*/
- public RepeatedFieldBuilderV3<MType, BType, IType> setMessage(
- int index, MType message) {
+ public RepeatedFieldBuilderV3<MType, BType, IType> setMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
messages.set(index, message);
if (builders != null) {
- SingleFieldBuilderV3<MType, BType, IType> entry =
- builders.set(index, null);
+ SingleFieldBuilderV3<MType, BType, IType> entry = builders.set(index, null);
if (entry != null) {
entry.dispose();
}
@@ -313,8 +297,7 @@ public class RepeatedFieldBuilderV3
* @param message the message to add
* @return the builder
*/
- public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(
- MType message) {
+ public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(MType message) {
checkNotNull(message);
ensureMutableMessageList();
messages.add(message);
@@ -327,16 +310,15 @@ public class RepeatedFieldBuilderV3
}
/**
- * Inserts the specified message at the specified position in this list.
- * Shifts the element currently at that position (if any) and any subsequent
- * elements to the right (adds one to their indices).
+ * Inserts the specified message at the specified position in this list. Shifts the element
+ * currently at that position (if any) and any subsequent elements to the right (adds one to their
+ * indices).
*
* @param index the index at which to insert the message
* @param message the message to add
* @return the builder
*/
- public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(
- int index, MType message) {
+ public RepeatedFieldBuilderV3<MType, BType, IType> addMessage(int index, MType message) {
checkNotNull(message);
ensureMutableMessageList();
messages.add(index, message);
@@ -349,9 +331,8 @@ public class RepeatedFieldBuilderV3
}
/**
- * Appends all of the messages in the specified collection to the end of
- * this list, in the order that they are returned by the specified
- * collection's iterator.
+ * Appends all of the messages in the specified collection to the end of this list, in the order
+ * that they are returned by the specified collection's iterator.
*
* @param values the messages to add
* @return the builder
@@ -365,8 +346,8 @@ public class RepeatedFieldBuilderV3
// If we can inspect the size, we can more efficiently add messages.
int size = -1;
if (values instanceof Collection) {
- @SuppressWarnings("unchecked") final
- Collection<MType> collection = (Collection<MType>) values;
+ @SuppressWarnings("unchecked")
+ final Collection<MType> collection = (Collection<MType>) values;
if (collection.size() == 0) {
return this;
}
@@ -375,8 +356,7 @@ public class RepeatedFieldBuilderV3
ensureMutableMessageList();
if (size >= 0 && messages instanceof ArrayList) {
- ((ArrayList<MType>) messages)
- .ensureCapacity(messages.size() + size);
+ ((ArrayList<MType>) messages).ensureCapacity(messages.size() + size);
}
for (MType value : values) {
@@ -398,8 +378,7 @@ public class RepeatedFieldBuilderV3
ensureMutableMessageList();
ensureBuilders();
SingleFieldBuilderV3<MType, BType, IType> builder =
- new SingleFieldBuilderV3<MType, BType, IType>(
- message, this, isClean);
+ new SingleFieldBuilderV3<MType, BType, IType>(message, this, isClean);
messages.add(null);
builders.add(builder);
onChanged();
@@ -408,9 +387,8 @@ public class RepeatedFieldBuilderV3
}
/**
- * Inserts a new builder at the specified position in this list.
- * Shifts the element currently at that position (if any) and any subsequent
- * elements to the right (adds one to their indices).
+ * Inserts a new builder at the specified position in this list. Shifts the element currently at
+ * that position (if any) and any subsequent elements to the right (adds one to their indices).
*
* @param index the index at which to insert the builder
* @param message the message to add which is the basis of the builder
@@ -420,8 +398,7 @@ public class RepeatedFieldBuilderV3
ensureMutableMessageList();
ensureBuilders();
SingleFieldBuilderV3<MType, BType, IType> builder =
- new SingleFieldBuilderV3<MType, BType, IType>(
- message, this, isClean);
+ new SingleFieldBuilderV3<MType, BType, IType>(message, this, isClean);
messages.add(index, null);
builders.add(index, builder);
onChanged();
@@ -430,9 +407,9 @@ public class RepeatedFieldBuilderV3
}
/**
- * Removes the element at the specified position in this list. Shifts any
- * subsequent elements to the left (subtracts one from their indices).
- * Returns the element that was removed from the list.
+ * Removes the element at the specified position in this list. Shifts any subsequent elements to
+ * the left (subtracts one from their indices). Returns the element that was removed from the
+ * list.
*
* @param index the index at which to remove the message
*/
@@ -440,8 +417,7 @@ public class RepeatedFieldBuilderV3
ensureMutableMessageList();
messages.remove(index);
if (builders != null) {
- SingleFieldBuilderV3<MType, BType, IType> entry =
- builders.remove(index);
+ SingleFieldBuilderV3<MType, BType, IType> entry = builders.remove(index);
if (entry != null) {
entry.dispose();
}
@@ -450,16 +426,12 @@ public class RepeatedFieldBuilderV3
incrementModCounts();
}
- /**
- * Removes all of the elements from this list.
- * The list will be empty after this call returns.
- */
+ /** Removes all of the elements from this list. The list will be empty after this call returns. */
public void clear() {
messages = Collections.emptyList();
isMessagesListMutable = false;
if (builders != null) {
- for (SingleFieldBuilderV3<MType, BType, IType> entry :
- builders) {
+ for (SingleFieldBuilderV3<MType, BType, IType> entry : builders) {
if (entry != null) {
entry.dispose();
}
@@ -519,50 +491,47 @@ public class RepeatedFieldBuilderV3
}
/**
- * Gets a view of the builder as a list of messages. The returned list is live
- * and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of messages. The returned list is live and will reflect
+ * any changes to the underlying builder.
*
* @return the messages in the list
*/
public List<MType> getMessageList() {
if (externalMessageList == null) {
- externalMessageList =
- new MessageExternalList<MType, BType, IType>(this);
+ externalMessageList = new MessageExternalList<MType, BType, IType>(this);
}
return externalMessageList;
}
/**
- * Gets a view of the builder as a list of builders. This returned list is
- * live and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of builders. This returned list is live and will reflect
+ * any changes to the underlying builder.
*
* @return the builders in the list
*/
public List<BType> getBuilderList() {
if (externalBuilderList == null) {
- externalBuilderList =
- new BuilderExternalList<MType, BType, IType>(this);
+ externalBuilderList = new BuilderExternalList<MType, BType, IType>(this);
}
return externalBuilderList;
}
/**
- * Gets a view of the builder as a list of MessageOrBuilders. This returned
- * list is live and will reflect any changes to the underlying builder.
+ * Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will
+ * reflect any changes to the underlying builder.
*
* @return the builders in the list
*/
public List<IType> getMessageOrBuilderList() {
if (externalMessageOrBuilderList == null) {
- externalMessageOrBuilderList =
- new MessageOrBuilderExternalList<MType, BType, IType>(this);
+ externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(this);
}
return externalMessageOrBuilderList;
}
/**
- * Called when a the builder or one of its nested children has changed
- * and any parent should be notified of its invalidation.
+ * Called when a the builder or one of its nested children has changed and any parent should be
+ * notified of its invalidation.
*/
private void onChanged() {
if (isClean && parent != null) {
@@ -579,9 +548,8 @@ public class RepeatedFieldBuilderV3
}
/**
- * Increments the mod counts so that an ConcurrentModificationException can
- * be thrown if calling code tries to modify the builder while its iterating
- * the list.
+ * Increments the mod counts so that an ConcurrentModificationException can be thrown if calling
+ * code tries to modify the builder while its iterating the list.
*/
private void incrementModCounts() {
if (externalMessageList != null) {
@@ -603,15 +571,14 @@ public class RepeatedFieldBuilderV3
* @param <IType> the common interface for the message and the builder
*/
private static class MessageExternalList<
- MType extends AbstractMessage,
- BType extends AbstractMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends AbstractMessage,
+ BType extends AbstractMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<MType> implements List<MType> {
RepeatedFieldBuilderV3<MType, BType, IType> builder;
- MessageExternalList(
- RepeatedFieldBuilderV3<MType, BType, IType> builder) {
+ MessageExternalList(RepeatedFieldBuilderV3<MType, BType, IType> builder) {
this.builder = builder;
}
@@ -638,15 +605,14 @@ public class RepeatedFieldBuilderV3
* @param <IType> the common interface for the message and the builder
*/
private static class BuilderExternalList<
- MType extends AbstractMessage,
- BType extends AbstractMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends AbstractMessage,
+ BType extends AbstractMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<BType> implements List<BType> {
RepeatedFieldBuilderV3<MType, BType, IType> builder;
- BuilderExternalList(
- RepeatedFieldBuilderV3<MType, BType, IType> builder) {
+ BuilderExternalList(RepeatedFieldBuilderV3<MType, BType, IType> builder) {
this.builder = builder;
}
@@ -673,15 +639,14 @@ public class RepeatedFieldBuilderV3
* @param <IType> the common interface for the message and the builder
*/
private static class MessageOrBuilderExternalList<
- MType extends AbstractMessage,
- BType extends AbstractMessage.Builder,
- IType extends MessageOrBuilder>
+ MType extends AbstractMessage,
+ BType extends AbstractMessage.Builder,
+ IType extends MessageOrBuilder>
extends AbstractList<IType> implements List<IType> {
RepeatedFieldBuilderV3<MType, BType, IType> builder;
- MessageOrBuilderExternalList(
- RepeatedFieldBuilderV3<MType, BType, IType> builder) {
+ MessageOrBuilderExternalList(RepeatedFieldBuilderV3<MType, BType, IType> builder) {
this.builder = builder;
}
diff --git a/java/core/src/main/java/com/google/protobuf/RopeByteString.java b/java/core/src/main/java/com/google/protobuf/RopeByteString.java
index 6fa555df..154fd5da 100644
--- a/java/core/src/main/java/com/google/protobuf/RopeByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/RopeByteString.java
@@ -46,41 +46,35 @@ import java.util.NoSuchElementException;
import java.util.Stack;
/**
- * Class to represent {@code ByteStrings} formed by concatenation of other
- * ByteStrings, without copying the data in the pieces. The concatenation is
- * represented as a tree whose leaf nodes are each a
- * {@link com.google.protobuf.ByteString.LeafByteString}.
+ * Class to represent {@code ByteStrings} formed by concatenation of other ByteStrings, without
+ * copying the data in the pieces. The concatenation is represented as a tree whose leaf nodes are
+ * each a {@link com.google.protobuf.ByteString.LeafByteString}.
*
* <p>Most of the operation here is inspired by the now-famous paper <a
* href="https://web.archive.org/web/20060202015456/http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf">
- * BAP95 </a> Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and
- * michael plass
+ * BAP95 </a> Ropes: an Alternative to Strings hans-j. boehm, russ atkinson and michael plass
*
- * <p>The algorithms described in the paper have been implemented for character
- * strings in {@code com.google.common.string.Rope} and in the c++ class {@code
- * cord.cc}.
+ * <p>The algorithms described in the paper have been implemented for character strings in {@code
+ * com.google.common.string.Rope} and in the c++ class {@code cord.cc}.
*
- * <p>Fundamentally the Rope algorithm represents the collection of pieces as a
- * binary tree. BAP95 uses a Fibonacci bound relating depth to a minimum
- * sequence length, sequences that are too short relative to their depth cause a
- * tree rebalance. More precisely, a tree of depth d is "balanced" in the
- * terminology of BAP95 if its length is at least F(d+2), where F(n) is the
- * n-the Fibonacci number. Thus for depths 0, 1, 2, 3, 4, 5,... we have minimum
- * lengths 1, 2, 3, 5, 8, 13,...
+ * <p>Fundamentally the Rope algorithm represents the collection of pieces as a binary tree. BAP95
+ * uses a Fibonacci bound relating depth to a minimum sequence length, sequences that are too short
+ * relative to their depth cause a tree rebalance. More precisely, a tree of depth d is "balanced"
+ * in the terminology of BAP95 if its length is at least F(d+2), where F(n) is the n-the Fibonacci
+ * number. Thus for depths 0, 1, 2, 3, 4, 5,... we have minimum lengths 1, 2, 3, 5, 8, 13,...
*
* @author carlanton@google.com (Carl Haverl)
*/
final class RopeByteString extends ByteString {
/**
- * BAP95. Let Fn be the nth Fibonacci number. A {@link RopeByteString} of
- * depth n is "balanced", i.e flat enough, if its length is at least Fn+2,
- * e.g. a "balanced" {@link RopeByteString} of depth 1 must have length at
- * least 2, of depth 4 must have length >= 8, etc.
+ * BAP95. Let Fn be the nth Fibonacci number. A {@link RopeByteString} of depth n is "balanced",
+ * i.e flat enough, if its length is at least Fn+2, e.g. a "balanced" {@link RopeByteString} of
+ * depth 1 must have length at least 2, of depth 4 must have length >= 8, etc.
*
- * <p>There's nothing special about using the Fibonacci numbers for this, but
- * they are a reasonable sequence for encapsulating the idea that we are OK
- * with longer strings being encoded in deeper binary trees.
+ * <p>There's nothing special about using the Fibonacci numbers for this, but they are a
+ * reasonable sequence for encapsulating the idea that we are OK with longer strings being encoded
+ * in deeper binary trees.
*
* <p>For 32-bit integers, this array has length 46.
*/
@@ -121,13 +115,11 @@ final class RopeByteString extends ByteString {
private final int treeDepth;
/**
- * Create a new RopeByteString, which can be thought of as a new tree node, by
- * recording references to the two given strings.
+ * Create a new RopeByteString, which can be thought of as a new tree node, by recording
+ * references to the two given strings.
*
- * @param left string on the left of this node, should have {@code size() >
- * 0}
- * @param right string on the right of this node, should have {@code size() >
- * 0}
+ * @param left string on the left of this node, should have {@code size() > 0}
+ * @param right string on the right of this node, should have {@code size() > 0}
*/
private RopeByteString(ByteString left, ByteString right) {
this.left = left;
@@ -138,17 +130,15 @@ final class RopeByteString extends ByteString {
}
/**
- * Concatenate the given strings while performing various optimizations to
- * slow the growth rate of tree depth and tree node count. The result is
- * either a {@link com.google.protobuf.ByteString.LeafByteString} or a
- * {@link RopeByteString} depending on which optimizations, if any, were
- * applied.
+ * Concatenate the given strings while performing various optimizations to slow the growth rate of
+ * tree depth and tree node count. The result is either a {@link
+ * com.google.protobuf.ByteString.LeafByteString} or a {@link RopeByteString} depending on which
+ * optimizations, if any, were applied.
*
- * <p>Small pieces of length less than {@link
- * ByteString#CONCATENATE_BY_COPY_SIZE} may be copied by value here, as in
- * BAP95. Large pieces are referenced without copy.
+ * <p>Small pieces of length less than {@link ByteString#CONCATENATE_BY_COPY_SIZE} may be copied
+ * by value here, as in BAP95. Large pieces are referenced without copy.
*
- * @param left string on the left
+ * @param left string on the left
* @param right string on the right
* @return concatenation representing the same sequence as the given strings
*/
@@ -208,31 +198,29 @@ final class RopeByteString extends ByteString {
}
/**
- * Concatenates two strings by copying data values. This is called in a few
- * cases in order to reduce the growth of the number of tree nodes.
+ * Concatenates two strings by copying data values. This is called in a few cases in order to
+ * reduce the growth of the number of tree nodes.
*
- * @param left string on the left
+ * @param left string on the left
* @param right string on the right
* @return string formed by copying data bytes
*/
- private static ByteString concatenateBytes(ByteString left,
- ByteString right) {
+ private static ByteString concatenateBytes(ByteString left, ByteString right) {
int leftSize = left.size();
int rightSize = right.size();
byte[] bytes = new byte[leftSize + rightSize];
left.copyTo(bytes, 0, 0, leftSize);
right.copyTo(bytes, 0, leftSize, rightSize);
- return ByteString.wrap(bytes); // Constructor wraps bytes
+ return ByteString.wrap(bytes); // Constructor wraps bytes
}
/**
- * Create a new RopeByteString for testing only while bypassing all the
- * defenses of {@link #concatenate(ByteString, ByteString)}. This allows
- * testing trees of specific structure. We are also able to insert empty
- * leaves, though these are dis-allowed, so that we can make sure the
+ * Create a new RopeByteString for testing only while bypassing all the defenses of {@link
+ * #concatenate(ByteString, ByteString)}. This allows testing trees of specific structure. We are
+ * also able to insert empty leaves, though these are dis-allowed, so that we can make sure the
* implementation can withstand their presence.
*
- * @param left string on the left of this node
+ * @param left string on the left of this node
* @param right string on the right of this node
* @return an unsafe instance for testing only
*/
@@ -241,9 +229,8 @@ final class RopeByteString extends ByteString {
}
/**
- * Gets the byte at the given index.
- * Throws {@link ArrayIndexOutOfBoundsException} for backwards-compatibility
- * reasons although it would more properly be {@link
+ * Gets the byte at the given index. Throws {@link ArrayIndexOutOfBoundsException} for
+ * backwards-compatibility reasons although it would more properly be {@link
* IndexOutOfBoundsException}.
*
* @param index index of byte
@@ -276,10 +263,9 @@ final class RopeByteString extends ByteString {
}
/**
- * Determines if the tree is balanced according to BAP95, which means the tree
- * is flat-enough with respect to the bounds. Note that this definition of
- * balanced is one where sub-trees of balanced trees are not necessarily
- * balanced.
+ * Determines if the tree is balanced according to BAP95, which means the tree is flat-enough with
+ * respect to the bounds. Note that this definition of balanced is one where sub-trees of balanced
+ * trees are not necessarily balanced.
*
* @return true if the tree is balanced
*/
@@ -289,17 +275,16 @@ final class RopeByteString extends ByteString {
}
/**
- * Takes a substring of this one. This involves recursive descent along the
- * left and right edges of the substring, and referencing any wholly contained
- * segments in between. Any leaf nodes entirely uninvolved in the substring
- * will not be referenced by the substring.
+ * Takes a substring of this one. This involves recursive descent along the left and right edges
+ * of the substring, and referencing any wholly contained segments in between. Any leaf nodes
+ * entirely uninvolved in the substring will not be referenced by the substring.
*
- * <p>Substrings of {@code length < 2} should result in at most a single
- * recursive call chain, terminating at a leaf node. Thus the result will be a
- * {@link com.google.protobuf.ByteString.LeafByteString}.
+ * <p>Substrings of {@code length < 2} should result in at most a single recursive call chain,
+ * terminating at a leaf node. Thus the result will be a {@link
+ * com.google.protobuf.ByteString.LeafByteString}.
*
* @param beginIndex start at this index
- * @param endIndex the last character is the one before this index
+ * @param endIndex the last character is the one before this index
* @return substring leaf node or tree
*/
@Override
@@ -340,18 +325,16 @@ final class RopeByteString extends ByteString {
// ByteString -> byte[]
@Override
- protected void copyToInternal(byte[] target, int sourceOffset,
- int targetOffset, int numberToCopy) {
- if (sourceOffset + numberToCopy <= leftLength) {
+ protected void copyToInternal(
+ byte[] target, int sourceOffset, int targetOffset, int numberToCopy) {
+ if (sourceOffset + numberToCopy <= leftLength) {
left.copyToInternal(target, sourceOffset, targetOffset, numberToCopy);
} else if (sourceOffset >= leftLength) {
- right.copyToInternal(target, sourceOffset - leftLength, targetOffset,
- numberToCopy);
+ right.copyToInternal(target, sourceOffset - leftLength, targetOffset, numberToCopy);
} else {
int leftLength = this.leftLength - sourceOffset;
left.copyToInternal(target, sourceOffset, targetOffset, leftLength);
- right.copyToInternal(target, 0, targetOffset + leftLength,
- numberToCopy - leftLength);
+ right.copyToInternal(target, 0, targetOffset + leftLength, numberToCopy - leftLength);
}
}
@@ -387,8 +370,7 @@ final class RopeByteString extends ByteString {
}
@Override
- void writeToInternal(OutputStream out, int sourceOffset,
- int numberToWrite) throws IOException {
+ void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException {
if (sourceOffset + numberToWrite <= leftLength) {
left.writeToInternal(out, sourceOffset, numberToWrite);
} else if (sourceOffset >= leftLength) {
@@ -471,13 +453,11 @@ final class RopeByteString extends ByteString {
}
/**
- * Determines if this string is equal to another of the same length by
- * iterating over the leaf nodes. On each step of the iteration, the
- * overlapping segments of the leaves are compared.
+ * Determines if this string is equal to another of the same length by iterating over the leaf
+ * nodes. On each step of the iteration, the overlapping segments of the leaves are compared.
*
* @param other string of the same length as this one
- * @return true if the values of this string equals the value of the given
- * one
+ * @return true if the values of this string equals the value of the given one
*/
private boolean equalsFragments(ByteString other) {
int thisOffset = 0;
@@ -495,9 +475,10 @@ final class RopeByteString extends ByteString {
int bytesToCompare = Math.min(thisRemaining, thatRemaining);
// At least one of the offsets will be zero
- boolean stillEqual = (thisOffset == 0)
- ? thisString.equalsRange(thatString, thatOffset, bytesToCompare)
- : thatString.equalsRange(thisString, thisOffset, bytesToCompare);
+ boolean stillEqual =
+ (thisOffset == 0)
+ ? thisString.equalsRange(thatString, thatOffset, bytesToCompare)
+ : thatString.equalsRange(thisString, thisOffset, bytesToCompare);
if (!stillEqual) {
return false;
}
@@ -553,14 +534,13 @@ final class RopeByteString extends ByteString {
}
/**
- * This class implements the balancing algorithm of BAP95. In the paper the
- * authors use an array to keep track of pieces, while here we use a stack.
- * The tree is balanced by traversing subtrees in left to right order, and the
- * stack always contains the part of the string we've traversed so far.
+ * This class implements the balancing algorithm of BAP95. In the paper the authors use an array
+ * to keep track of pieces, while here we use a stack. The tree is balanced by traversing subtrees
+ * in left to right order, and the stack always contains the part of the string we've traversed so
+ * far.
*
- * <p>One surprising aspect of the algorithm is the result of balancing is not
- * necessarily balanced, though it is nearly balanced. For details, see
- * BAP95.
+ * <p>One surprising aspect of the algorithm is the result of balancing is not necessarily
+ * balanced, though it is nearly balanced. For details, see BAP95.
*/
private static class Balancer {
// Stack containing the part of the string, starting from the left, that
@@ -596,21 +576,18 @@ final class RopeByteString extends ByteString {
doBalance(rbs.right);
} else {
throw new IllegalArgumentException(
- "Has a new type of ByteString been created? Found " +
- root.getClass());
+ "Has a new type of ByteString been created? Found " + root.getClass());
}
}
/**
- * Push a string on the balance stack (BAP95). BAP95 uses an array and
- * calls the elements in the array 'bins'. We instead use a stack, so the
- * 'bins' of lengths are represented by differences between the elements of
- * minLengthByDepth.
+ * Push a string on the balance stack (BAP95). BAP95 uses an array and calls the elements in the
+ * array 'bins'. We instead use a stack, so the 'bins' of lengths are represented by differences
+ * between the elements of minLengthByDepth.
*
- * <p>If the length bin for our string, and all shorter length bins, are
- * empty, we just push it on the stack. Otherwise, we need to start
- * concatenating, putting the given string in the "middle" and continuing
- * until we land in an empty length bin that matches the length of our
+ * <p>If the length bin for our string, and all shorter length bins, are empty, we just push it
+ * on the stack. Otherwise, we need to start concatenating, putting the given string in the
+ * "middle" and continuing until we land in an empty length bin that matches the length of our
* concatenation.
*
* @param byteString string to place on the balance stack
@@ -630,8 +607,7 @@ final class RopeByteString extends ByteString {
// Concatenate the subtrees of shorter length
ByteString newTree = prefixesStack.pop();
- while (!prefixesStack.isEmpty()
- && prefixesStack.peek().size() < binStart) {
+ while (!prefixesStack.isEmpty() && prefixesStack.peek().size() < binStart) {
ByteString left = prefixesStack.pop();
newTree = new RopeByteString(left, newTree);
}
@@ -668,18 +644,15 @@ final class RopeByteString extends ByteString {
}
/**
- * This class is a continuable tree traversal, which keeps the state
- * information which would exist on the stack in a recursive traversal instead
- * on a stack of "Bread Crumbs". The maximum depth of the stack in this
- * iterator is the same as the depth of the tree being traversed.
+ * This class is a continuable tree traversal, which keeps the state information which would exist
+ * on the stack in a recursive traversal instead on a stack of "Bread Crumbs". The maximum depth
+ * of the stack in this iterator is the same as the depth of the tree being traversed.
*
- * <p>This iterator is used to implement
- * {@link RopeByteString#equalsFragments(ByteString)}.
+ * <p>This iterator is used to implement {@link RopeByteString#equalsFragments(ByteString)}.
*/
private static class PieceIterator implements Iterator<LeafByteString> {
- private final Stack<RopeByteString> breadCrumbs =
- new Stack<RopeByteString>();
+ private final Stack<RopeByteString> breadCrumbs = new Stack<RopeByteString>();
private LeafByteString next;
private PieceIterator(ByteString root) {
@@ -717,8 +690,7 @@ final class RopeByteString extends ByteString {
}
/**
- * Returns the next item and advances one
- * {@link com.google.protobuf.ByteString.LeafByteString}.
+ * Returns the next item and advances one {@link com.google.protobuf.ByteString.LeafByteString}.
*
* @return next non-empty LeafByteString or {@code null}
*/
@@ -748,14 +720,10 @@ final class RopeByteString extends ByteString {
}
private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException {
- throw new InvalidObjectException(
- "RopeByteStream instances are not to be serialized directly");
+ throw new InvalidObjectException("RopeByteStream instances are not to be serialized directly");
}
- /**
- * This class is the {@link RopeByteString} equivalent for
- * {@link ByteArrayInputStream}.
- */
+ /** This class is the {@link RopeByteString} equivalent for {@link ByteArrayInputStream}. */
private class RopeInputStream extends InputStream {
// Iterates through the pieces of the rope
private PieceIterator pieceIterator;
@@ -775,7 +743,7 @@ final class RopeByteString extends ByteString {
}
@Override
- public int read(byte b[], int offset, int length) {
+ public int read(byte[] b, int offset, int length) {
if (b == null) {
throw new NullPointerException();
} else if (offset < 0 || length < 0 || length > b.length - offset) {
@@ -795,24 +763,23 @@ final class RopeByteString extends ByteString {
}
/**
- * Internal implementation of read and skip. If b != null, then read the
- * next {@code length} bytes into the buffer {@code b} at
- * offset {@code offset}. If b == null, then skip the next {@code length}
- * bytes.
- * <p>
- * This method assumes that all error checking has already happened.
- * <p>
- * Returns the actual number of bytes read or skipped.
+ * Internal implementation of read and skip. If b != null, then read the next {@code length}
+ * bytes into the buffer {@code b} at offset {@code offset}. If b == null, then skip the next
+ * {@code length} bytes.
+ *
+ * <p>This method assumes that all error checking has already happened.
+ *
+ * <p>Returns the actual number of bytes read or skipped.
*/
- private int readSkipInternal(byte b[], int offset, int length) {
+ private int readSkipInternal(byte[] b, int offset, int length) {
int bytesRemaining = length;
while (bytesRemaining > 0) {
advanceIfCurrentPieceFullyRead();
if (currentPiece == null) {
if (bytesRemaining == length) {
- // We didn't manage to read anything
- return -1;
- }
+ // We didn't manage to read anything
+ return -1;
+ }
break;
} else {
// Copy the bytes from this piece.
@@ -826,7 +793,7 @@ final class RopeByteString extends ByteString {
bytesRemaining -= count;
}
}
- // Return the number of bytes read.
+ // Return the number of bytes read.
return length - bytesRemaining;
}
@@ -874,9 +841,8 @@ final class RopeByteString extends ByteString {
}
/**
- * Skips to the next piece if we have read all the data in the current
- * piece. Sets currentPiece to null if we have reached the end of the
- * input.
+ * Skips to the next piece if we have read all the data in the current piece. Sets currentPiece
+ * to null if we have reached the end of the input.
*/
private void advanceIfCurrentPieceFullyRead() {
if (currentPiece != null && currentPieceIndex == currentPieceSize) {
diff --git a/java/core/src/main/java/com/google/protobuf/RpcCallback.java b/java/core/src/main/java/com/google/protobuf/RpcCallback.java
index 10752968..51a34b63 100644
--- a/java/core/src/main/java/com/google/protobuf/RpcCallback.java
+++ b/java/core/src/main/java/com/google/protobuf/RpcCallback.java
@@ -31,14 +31,13 @@
package com.google.protobuf;
/**
- * Interface for an RPC callback, normally called when an RPC completes.
- * {@code ParameterType} is normally the method's response message type.
+ * Interface for an RPC callback, normally called when an RPC completes. {@code ParameterType} is
+ * normally the method's response message type.
*
- * <p>Starting with version 2.3.0, RPC implementations should not try to build
- * on this, but should instead provide code generator plugins which generate
- * code specific to the particular RPC implementation. This way the generated
- * code can be more appropriate for the implementation in use and can avoid
- * unnecessary layers of indirection.
+ * <p>Starting with version 2.3.0, RPC implementations should not try to build on this, but should
+ * instead provide code generator plugins which generate code specific to the particular RPC
+ * implementation. This way the generated code can be more appropriate for the implementation in use
+ * and can avoid unnecessary layers of indirection.
*
* @author kenton@google.com Kenton Varda
*/
diff --git a/java/core/src/main/java/com/google/protobuf/RpcChannel.java b/java/core/src/main/java/com/google/protobuf/RpcChannel.java
index f272f4ad..13b5ec16 100644
--- a/java/core/src/main/java/com/google/protobuf/RpcChannel.java
+++ b/java/core/src/main/java/com/google/protobuf/RpcChannel.java
@@ -31,11 +31,10 @@
package com.google.protobuf;
/**
- * <p>Abstract interface for an RPC channel. An {@code RpcChannel} represents a
- * communication line to a {@link Service} which can be used to call that
- * {@link Service}'s methods. The {@link Service} may be running on another
- * machine. Normally, you should not call an {@code RpcChannel} directly, but
- * instead construct a stub {@link Service} wrapping it. Example:
+ * Abstract interface for an RPC channel. An {@code RpcChannel} represents a communication line to a
+ * {@link Service} which can be used to call that {@link Service}'s methods. The {@link Service} may
+ * be running on another machine. Normally, you should not call an {@code RpcChannel} directly, but
+ * instead construct a stub {@link Service} wrapping it. Example:
*
* <pre>
* RpcChannel channel = rpcImpl.newChannel("remotehost.example.com:1234");
@@ -44,28 +43,26 @@ package com.google.protobuf;
* service.myMethod(controller, request, callback);
* </pre>
*
- * <p>Starting with version 2.3.0, RPC implementations should not try to build
- * on this, but should instead provide code generator plugins which generate
- * code specific to the particular RPC implementation. This way the generated
- * code can be more appropriate for the implementation in use and can avoid
- * unnecessary layers of indirection.
+ * <p>Starting with version 2.3.0, RPC implementations should not try to build on this, but should
+ * instead provide code generator plugins which generate code specific to the particular RPC
+ * implementation. This way the generated code can be more appropriate for the implementation in use
+ * and can avoid unnecessary layers of indirection.
*
* @author kenton@google.com Kenton Varda
*/
public interface RpcChannel {
/**
- * Call the given method of the remote service. This method is similar to
- * {@code Service.callMethod()} with one important difference: the caller
- * decides the types of the {@code Message} objects, not the callee. The
- * request may be of any type as long as
- * {@code request.getDescriptor() == method.getInputType()}.
- * The response passed to the callback will be of the same type as
- * {@code responsePrototype} (which must have
- * {@code getDescriptor() == method.getOutputType()}).
+ * Call the given method of the remote service. This method is similar to {@code
+ * Service.callMethod()} with one important difference: the caller decides the types of the {@code
+ * Message} objects, not the callee. The request may be of any type as long as {@code
+ * request.getDescriptor() == method.getInputType()}. The response passed to the callback will be
+ * of the same type as {@code responsePrototype} (which must have {@code getDescriptor() ==
+ * method.getOutputType()}).
*/
- void callMethod(Descriptors.MethodDescriptor method,
- RpcController controller,
- Message request,
- Message responsePrototype,
- RpcCallback<Message> done);
+ void callMethod(
+ Descriptors.MethodDescriptor method,
+ RpcController controller,
+ Message request,
+ Message responsePrototype,
+ RpcCallback<Message> done);
}
diff --git a/java/core/src/main/java/com/google/protobuf/RpcController.java b/java/core/src/main/java/com/google/protobuf/RpcController.java
index a92dd7be..073f27a2 100644
--- a/java/core/src/main/java/com/google/protobuf/RpcController.java
+++ b/java/core/src/main/java/com/google/protobuf/RpcController.java
@@ -31,20 +31,18 @@
package com.google.protobuf;
/**
- * <p>An {@code RpcController} mediates a single method call. The primary
- * purpose of the controller is to provide a way to manipulate settings
- * specific to the RPC implementation and to find out about RPC-level errors.
+ * An {@code RpcController} mediates a single method call. The primary purpose of the controller is
+ * to provide a way to manipulate settings specific to the RPC implementation and to find out about
+ * RPC-level errors.
*
- * <p>Starting with version 2.3.0, RPC implementations should not try to build
- * on this, but should instead provide code generator plugins which generate
- * code specific to the particular RPC implementation. This way the generated
- * code can be more appropriate for the implementation in use and can avoid
- * unnecessary layers of indirection.
+ * <p>Starting with version 2.3.0, RPC implementations should not try to build on this, but should
+ * instead provide code generator plugins which generate code specific to the particular RPC
+ * implementation. This way the generated code can be more appropriate for the implementation in use
+ * and can avoid unnecessary layers of indirection.
*
- * <p>The methods provided by the {@code RpcController} interface are intended
- * to be a "least common denominator" set of features which we expect all
- * implementations to support. Specific implementations may provide more
- * advanced features (e.g. deadline propagation).
+ * <p>The methods provided by the {@code RpcController} interface are intended to be a "least common
+ * denominator" set of features which we expect all implementations to support. Specific
+ * implementations may provide more advanced features (e.g. deadline propagation).
*
* @author kenton@google.com Kenton Varda
*/
@@ -54,31 +52,25 @@ public interface RpcController {
// are undefined on the server side (may throw RuntimeExceptions).
/**
- * Resets the RpcController to its initial state so that it may be reused in
- * a new call. This can be called from the client side only. It must not
- * be called while an RPC is in progress.
+ * Resets the RpcController to its initial state so that it may be reused in a new call. This can
+ * be called from the client side only. It must not be called while an RPC is in progress.
*/
void reset();
/**
- * After a call has finished, returns true if the call failed. The possible
- * reasons for failure depend on the RPC implementation. {@code failed()}
- * most only be called on the client side, and must not be called before a
- * call has finished.
+ * After a call has finished, returns true if the call failed. The possible reasons for failure
+ * depend on the RPC implementation. {@code failed()} most only be called on the client side, and
+ * must not be called before a call has finished.
*/
boolean failed();
- /**
- * If {@code failed()} is {@code true}, returns a human-readable description
- * of the error.
- */
+ /** If {@code failed()} is {@code true}, returns a human-readable description of the error. */
String errorText();
/**
- * Advises the RPC system that the caller desires that the RPC call be
- * canceled. The RPC system may cancel it immediately, may wait awhile and
- * then cancel it, or may not even cancel the call at all. If the call is
- * canceled, the "done" callback will still be called and the RpcController
+ * Advises the RPC system that the caller desires that the RPC call be canceled. The RPC system
+ * may cancel it immediately, may wait awhile and then cancel it, or may not even cancel the call
+ * at all. If the call is canceled, the "done" callback will still be called and the RpcController
* will indicate that the call failed at that time.
*/
void startCancel();
@@ -88,31 +80,29 @@ public interface RpcController {
// are undefined on the client side (may throw RuntimeExceptions).
/**
- * Causes {@code failed()} to return true on the client side. {@code reason}
- * will be incorporated into the message returned by {@code errorText()}.
- * If you find you need to return machine-readable information about
- * failures, you should incorporate it into your response protocol buffer
- * and should NOT call {@code setFailed()}.
+ * Causes {@code failed()} to return true on the client side. {@code reason} will be incorporated
+ * into the message returned by {@code errorText()}. If you find you need to return
+ * machine-readable information about failures, you should incorporate it into your response
+ * protocol buffer and should NOT call {@code setFailed()}.
*/
void setFailed(String reason);
/**
- * If {@code true}, indicates that the client canceled the RPC, so the server
- * may as well give up on replying to it. This method must be called on the
- * server side only. The server should still call the final "done" callback.
+ * If {@code true}, indicates that the client canceled the RPC, so the server may as well give up
+ * on replying to it. This method must be called on the server side only. The server should still
+ * call the final "done" callback.
*/
boolean isCanceled();
/**
- * Asks that the given callback be called when the RPC is canceled. The
- * parameter passed to the callback will always be {@code null}. The
- * callback will always be called exactly once. If the RPC completes without
- * being canceled, the callback will be called after completion. If the RPC
- * has already been canceled when NotifyOnCancel() is called, the callback
- * will be called immediately.
+ * Asks that the given callback be called when the RPC is canceled. The parameter passed to the
+ * callback will always be {@code null}. The callback will always be called exactly once. If the
+ * RPC completes without being canceled, the callback will be called after completion. If the RPC
+ * has already been canceled when NotifyOnCancel() is called, the callback will be called
+ * immediately.
*
- * <p>{@code notifyOnCancel()} must be called no more than once per request.
- * It must be called on the server side only.
+ * <p>{@code notifyOnCancel()} must be called no more than once per request. It must be called on
+ * the server side only.
*/
void notifyOnCancel(RpcCallback<Object> callback);
}
diff --git a/java/core/src/main/java/com/google/protobuf/RpcUtil.java b/java/core/src/main/java/com/google/protobuf/RpcUtil.java
index f7d555ae..7bd056a5 100644
--- a/java/core/src/main/java/com/google/protobuf/RpcUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/RpcUtil.java
@@ -39,14 +39,13 @@ public final class RpcUtil {
private RpcUtil() {}
/**
- * Take an {@code RpcCallback<Message>} and convert it to an
- * {@code RpcCallback} accepting a specific message type. This is always
- * type-safe (parameter type contravariance).
+ * Take an {@code RpcCallback<Message>} and convert it to an {@code RpcCallback} accepting a
+ * specific message type. This is always type-safe (parameter type contravariance).
*/
@SuppressWarnings("unchecked")
- public static <Type extends Message> RpcCallback<Type>
- specializeCallback(final RpcCallback<Message> originalCallback) {
- return (RpcCallback<Type>)originalCallback;
+ public static <Type extends Message> RpcCallback<Type> specializeCallback(
+ final RpcCallback<Message> originalCallback) {
+ return (RpcCallback<Type>) originalCallback;
// The above cast works, but only due to technical details of the Java
// implementation. A more theoretically correct -- but less efficient --
// implementation would be as follows:
@@ -58,15 +57,13 @@ public final class RpcUtil {
}
/**
- * Take an {@code RpcCallback} accepting a specific message type and convert
- * it to an {@code RpcCallback<Message>}. The generalized callback will
- * accept any message object which has the same descriptor, and will convert
- * it to the correct class before calling the original callback. However,
- * if the generalized callback is given a message with a different descriptor,
- * an exception will be thrown.
+ * Take an {@code RpcCallback} accepting a specific message type and convert it to an {@code
+ * RpcCallback<Message>}. The generalized callback will accept any message object which has the
+ * same descriptor, and will convert it to the correct class before calling the original callback.
+ * However, if the generalized callback is given a message with a different descriptor, an
+ * exception will be thrown.
*/
- public static <Type extends Message>
- RpcCallback<Message> generalizeCallback(
+ public static <Type extends Message> RpcCallback<Message> generalizeCallback(
final RpcCallback<Type> originalCallback,
final Class<Type> originalClass,
final Type defaultInstance) {
@@ -85,25 +82,21 @@ public final class RpcUtil {
}
/**
- * Creates a new message of type "Type" which is a copy of "source". "source"
- * must have the same descriptor but may be a different class (e.g.
- * DynamicMessage).
+ * Creates a new message of type "Type" which is a copy of "source". "source" must have the same
+ * descriptor but may be a different class (e.g. DynamicMessage).
*/
@SuppressWarnings("unchecked")
private static <Type extends Message> Type copyAsType(
final Type typeDefaultInstance, final Message source) {
- return (Type) typeDefaultInstance
- .newBuilderForType().mergeFrom(source).build();
+ return (Type) typeDefaultInstance.newBuilderForType().mergeFrom(source).build();
}
/**
- * Creates a callback which can only be called once. This may be useful for
- * security, when passing a callback to untrusted code: most callbacks do
- * not expect to be called more than once, so doing so may expose bugs if it
- * is not prevented.
+ * Creates a callback which can only be called once. This may be useful for security, when passing
+ * a callback to untrusted code: most callbacks do not expect to be called more than once, so
+ * doing so may expose bugs if it is not prevented.
*/
- public static <ParameterType>
- RpcCallback<ParameterType> newOneTimeCallback(
+ public static <ParameterType> RpcCallback<ParameterType> newOneTimeCallback(
final RpcCallback<ParameterType> originalCallback) {
return new RpcCallback<ParameterType>() {
private boolean alreadyCalled = false;
@@ -122,15 +115,12 @@ public final class RpcUtil {
};
}
- /**
- * Exception thrown when a one-time callback is called more than once.
- */
+ /** Exception thrown when a one-time callback is called more than once. */
public static final class AlreadyCalledException extends RuntimeException {
private static final long serialVersionUID = 5469741279507848266L;
public AlreadyCalledException() {
- super("This RpcCallback was already called and cannot be called " +
- "multiple times.");
+ super("This RpcCallback was already called and cannot be called multiple times.");
}
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/Service.java b/java/core/src/main/java/com/google/protobuf/Service.java
index ba7b033e..d45cdaec 100644
--- a/java/core/src/main/java/com/google/protobuf/Service.java
+++ b/java/core/src/main/java/com/google/protobuf/Service.java
@@ -31,70 +31,63 @@
package com.google.protobuf;
/**
- * Abstract base interface for protocol-buffer-based RPC services. Services
- * themselves are abstract classes (implemented either by servers or as
- * stubs), but they subclass this base interface. The methods of this
- * interface can be used to call the methods of the service without knowing
- * its exact type at compile time (analogous to the Message interface).
+ * Abstract base interface for protocol-buffer-based RPC services. Services themselves are abstract
+ * classes (implemented either by servers or as stubs), but they subclass this base interface. The
+ * methods of this interface can be used to call the methods of the service without knowing its
+ * exact type at compile time (analogous to the Message interface).
*
- * <p>Starting with version 2.3.0, RPC implementations should not try to build
- * on this, but should instead provide code generator plugins which generate
- * code specific to the particular RPC implementation. This way the generated
- * code can be more appropriate for the implementation in use and can avoid
- * unnecessary layers of indirection.
+ * <p>Starting with version 2.3.0, RPC implementations should not try to build on this, but should
+ * instead provide code generator plugins which generate code specific to the particular RPC
+ * implementation. This way the generated code can be more appropriate for the implementation in use
+ * and can avoid unnecessary layers of indirection.
*
* @author kenton@google.com Kenton Varda
*/
public interface Service {
- /**
- * Get the {@code ServiceDescriptor} describing this service and its methods.
- */
+ /** Get the {@code ServiceDescriptor} describing this service and its methods. */
Descriptors.ServiceDescriptor getDescriptorForType();
/**
- * <p>Call a method of the service specified by MethodDescriptor. This is
- * normally implemented as a simple {@code switch()} that calls the standard
- * definitions of the service's methods.
+ * Call a method of the service specified by MethodDescriptor. This is normally implemented as a
+ * simple {@code switch()} that calls the standard definitions of the service's methods.
*
* <p>Preconditions:
+ *
* <ul>
* <li>{@code method.getService() == getDescriptorForType()}
- * <li>{@code request} is of the exact same class as the object returned by
- * {@code getRequestPrototype(method)}.
- * <li>{@code controller} is of the correct type for the RPC implementation
- * being used by this Service. For stubs, the "correct type" depends
- * on the RpcChannel which the stub is using. Server-side Service
- * implementations are expected to accept whatever type of
- * {@code RpcController} the server-side RPC implementation uses.
+ * <li>{@code request} is of the exact same class as the object returned by {@code
+ * getRequestPrototype(method)}.
+ * <li>{@code controller} is of the correct type for the RPC implementation being used by this
+ * Service. For stubs, the "correct type" depends on the RpcChannel which the stub is using.
+ * Server-side Service implementations are expected to accept whatever type of {@code
+ * RpcController} the server-side RPC implementation uses.
* </ul>
*
* <p>Postconditions:
+ *
* <ul>
- * <li>{@code done} will be called when the method is complete. This may be
- * before {@code callMethod()} returns or it may be at some point in
- * the future.
- * <li>The parameter to {@code done} is the response. It must be of the
- * exact same type as would be returned by
- * {@code getResponsePrototype(method)}.
- * <li>If the RPC failed, the parameter to {@code done} will be
- * {@code null}. Further details about the failure can be found by
- * querying {@code controller}.
+ * <li>{@code done} will be called when the method is complete. This may be before {@code
+ * callMethod()} returns or it may be at some point in the future.
+ * <li>The parameter to {@code done} is the response. It must be of the exact same type as would
+ * be returned by {@code getResponsePrototype(method)}.
+ * <li>If the RPC failed, the parameter to {@code done} will be {@code null}. Further details
+ * about the failure can be found by querying {@code controller}.
* </ul>
*/
- void callMethod(Descriptors.MethodDescriptor method,
- RpcController controller,
- Message request,
- RpcCallback<Message> done);
+ void callMethod(
+ Descriptors.MethodDescriptor method,
+ RpcController controller,
+ Message request,
+ RpcCallback<Message> done);
/**
- * <p>{@code callMethod()} requires that the request passed in is of a
- * particular subclass of {@code Message}. {@code getRequestPrototype()}
- * gets the default instances of this type for a given method. You can then
- * call {@code Message.newBuilderForType()} on this instance to
- * construct a builder to build an object which you can then pass to
- * {@code callMethod()}.
+ * {@code callMethod()} requires that the request passed in is of a particular subclass of {@code
+ * Message}. {@code getRequestPrototype()} gets the default instances of this type for a given
+ * method. You can then call {@code Message.newBuilderForType()} on this instance to construct a
+ * builder to build an object which you can then pass to {@code callMethod()}.
*
* <p>Example:
+ *
* <pre>
* MethodDescriptor method =
* service.getDescriptorForType().findMethodByName("Foo");
@@ -107,11 +100,10 @@ public interface Service {
Message getRequestPrototype(Descriptors.MethodDescriptor method);
/**
- * Like {@code getRequestPrototype()}, but gets a prototype of the response
- * message. {@code getResponsePrototype()} is generally not needed because
- * the {@code Service} implementation constructs the response message itself,
- * but it may be useful in some cases to know ahead of time what type of
- * object will be returned.
+ * Like {@code getRequestPrototype()}, but gets a prototype of the response message. {@code
+ * getResponsePrototype()} is generally not needed because the {@code Service} implementation
+ * constructs the response message itself, but it may be useful in some cases to know ahead of
+ * time what type of object will be returned.
*/
Message getResponsePrototype(Descriptors.MethodDescriptor method);
}
diff --git a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
index 941b5def..acdc1de1 100644
--- a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
+++ b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilder.java
@@ -30,36 +30,32 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
/**
- * {@code SingleFieldBuilder} implements a structure that a protocol
- * message uses to hold a single field of another protocol message. It supports
- * the classical use case of setting an immutable {@link Message} as the value
- * of the field and is highly optimized around this.
- * <br>
- * It also supports the additional use case of setting a {@link Message.Builder}
- * as the field and deferring conversion of that {@code Builder}
- * to an immutable {@code Message}. In this way, it's possible to maintain
- * a tree of {@code Builder}'s that acts as a fully read/write data
- * structure.
+ * {@code SingleFieldBuilder} implements a structure that a protocol message uses to hold a single
+ * field of another protocol message. It supports the classical use case of setting an immutable
+ * {@link Message} as the value of the field and is highly optimized around this.
+ *
+ * <p>It also supports the additional use case of setting a {@link Message.Builder} as the field and
+ * deferring conversion of that {@code Builder} to an immutable {@code Message}. In this way, it's
+ * possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data structure.
* <br>
- * Logically, one can think of a tree of builders as converting the entire tree
- * to messages when build is called on the root or when any method is called
- * that desires a Message instead of a Builder. In terms of the implementation,
- * the {@code SingleFieldBuilder} and {@code RepeatedFieldBuilder}
- * classes cache messages that were created so that messages only need to be
- * created when some change occurred in its builder or a builder for one of its
- * descendants.
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when
+ * build is called on the root or when any method is called that desires a Message instead of a
+ * Builder. In terms of the implementation, the {@code SingleFieldBuilder} and {@code
+ * RepeatedFieldBuilder} classes cache messages that were created so that messages only need to be
+ * created when some change occurred in its builder or a builder for one of its descendants.
*
* @param <MType> the type of message for the field
* @param <BType> the type of builder for the field
* @param <IType> the common interface for the message and the builder
- *
* @author jonp@google.com (Jon Perlow)
*/
-public class SingleFieldBuilder
- <MType extends GeneratedMessage,
- BType extends GeneratedMessage.Builder,
- IType extends MessageOrBuilder>
+public class SingleFieldBuilder<
+ MType extends GeneratedMessage,
+ BType extends GeneratedMessage.Builder,
+ IType extends MessageOrBuilder>
implements GeneratedMessage.BuilderParent {
// Parent to send changes to.
@@ -80,14 +76,8 @@ public class SingleFieldBuilder
// to dispatch dirty invalidations. See GeneratedMessage.BuilderListener.
private boolean isClean;
- public SingleFieldBuilder(
- MType message,
- GeneratedMessage.BuilderParent parent,
- boolean isClean) {
- if (message == null) {
- throw new NullPointerException();
- }
- this.message = message;
+ public SingleFieldBuilder(MType message, GeneratedMessage.BuilderParent parent, boolean isClean) {
+ this.message = checkNotNull(message);
this.parent = parent;
this.isClean = isClean;
}
@@ -98,10 +88,9 @@ public class SingleFieldBuilder
}
/**
- * Get the message for the field. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it. If no message has
- * been set, returns the default instance of the message.
+ * Get the message for the field. If the message is currently stored as a {@code Builder}, it is
+ * converted to a {@code Message} by calling {@link Message.Builder#buildPartial} on it. If no
+ * message has been set, returns the default instance of the message.
*
* @return the message for the field
*/
@@ -127,8 +116,8 @@ public class SingleFieldBuilder
}
/**
- * Gets a builder for the field. If no builder has been created yet, a
- * builder is created on demand by calling {@link Message#toBuilder}.
+ * Gets a builder for the field. If no builder has been created yet, a builder is created on
+ * demand by calling {@link Message#toBuilder}.
*
* @return The builder for the field
*/
@@ -147,32 +136,28 @@ public class SingleFieldBuilder
}
/**
- * Gets the base class interface for the field. This may either be a builder
- * or a message. It will return whatever is more efficient.
+ * Gets the base class interface for the field. This may either be a builder or a message. It will
+ * return whatever is more efficient.
*
* @return the message or builder for the field as the base class interface
*/
@SuppressWarnings("unchecked")
public IType getMessageOrBuilder() {
if (builder != null) {
- return (IType) builder;
+ return (IType) builder;
} else {
return (IType) message;
}
}
/**
- * Sets a message for the field replacing any existing value.
+ * Sets a message for the field replacing any existing value.
*
* @param message the message to set
* @return the builder
*/
- public SingleFieldBuilder<MType, BType, IType> setMessage(
- MType message) {
- if (message == null) {
- throw new NullPointerException();
- }
- this.message = message;
+ public SingleFieldBuilder<MType, BType, IType> setMessage(MType message) {
+ this.message = checkNotNull(message);
if (builder != null) {
builder.dispose();
builder = null;
@@ -187,8 +172,7 @@ public class SingleFieldBuilder
* @param value the value to merge from
* @return the builder
*/
- public SingleFieldBuilder<MType, BType, IType> mergeFrom(
- MType value) {
+ public SingleFieldBuilder<MType, BType, IType> mergeFrom(MType value) {
if (builder == null && message == message.getDefaultInstanceForType()) {
message = value;
} else {
@@ -205,9 +189,11 @@ public class SingleFieldBuilder
*/
@SuppressWarnings("unchecked")
public SingleFieldBuilder<MType, BType, IType> clear() {
- message = (MType) (message != null ?
- message.getDefaultInstanceForType() :
- builder.getDefaultInstanceForType());
+ message =
+ (MType)
+ (message != null
+ ? message.getDefaultInstanceForType()
+ : builder.getDefaultInstanceForType());
if (builder != null) {
builder.dispose();
builder = null;
@@ -217,8 +203,8 @@ public class SingleFieldBuilder
}
/**
- * Called when a the builder or one of its nested children has changed
- * and any parent should be notified of its invalidation.
+ * Called when a the builder or one of its nested children has changed and any parent should be
+ * notified of its invalidation.
*/
private void onChanged() {
// If builder is null, this is the case where onChanged is being called
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 8ab0f26d..78a4a216 100644
--- a/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java
+++ b/java/core/src/main/java/com/google/protobuf/SingleFieldBuilderV3.java
@@ -33,35 +33,29 @@ 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
- * the classical use case of setting an immutable {@link Message} as the value
- * of the field and is highly optimized around this.
- * <br>
- * It also supports the additional use case of setting a {@link Message.Builder}
- * as the field and deferring conversion of that {@code Builder}
- * to an immutable {@code Message}. In this way, it's possible to maintain
- * a tree of {@code Builder}'s that acts as a fully read/write data
- * structure.
+ * {@code SingleFieldBuilderV3} implements a structure that a protocol message uses to hold a single
+ * field of another protocol message. It supports the classical use case of setting an immutable
+ * {@link Message} as the value of the field and is highly optimized around this.
+ *
+ * <p>It also supports the additional use case of setting a {@link Message.Builder} as the field and
+ * deferring conversion of that {@code Builder} to an immutable {@code Message}. In this way, it's
+ * possible to maintain a tree of {@code Builder}'s that acts as a fully read/write data structure.
* <br>
- * Logically, one can think of a tree of builders as converting the entire tree
- * to messages when build is called on the root or when any method is called
- * that desires a Message instead of a Builder. In terms of the implementation,
- * the {@code SingleFieldBuilderV3} and {@code RepeatedFieldBuilderV3}
- * classes cache messages that were created so that messages only need to be
- * created when some change occurred in its builder or a builder for one of its
- * descendants.
+ * Logically, one can think of a tree of builders as converting the entire tree to messages when
+ * build is called on the root or when any method is called that desires a Message instead of a
+ * Builder. In terms of the implementation, the {@code SingleFieldBuilderV3} and {@code
+ * RepeatedFieldBuilderV3} classes cache messages that were created so that messages only need to be
+ * created when some change occurred in its builder or a builder for one of its descendants.
*
* @param <MType> the type of message for the field
* @param <BType> the type of builder for the field
* @param <IType> the common interface for the message and the builder
- *
* @author jonp@google.com (Jon Perlow)
*/
-public class SingleFieldBuilderV3
- <MType extends AbstractMessage,
- BType extends AbstractMessage.Builder,
- IType extends MessageOrBuilder>
+public class SingleFieldBuilderV3<
+ MType extends AbstractMessage,
+ BType extends AbstractMessage.Builder,
+ IType extends MessageOrBuilder>
implements AbstractMessage.BuilderParent {
// Parent to send changes to.
@@ -82,10 +76,7 @@ public class SingleFieldBuilderV3
// to dispatch dirty invalidations. See AbstractMessage.BuilderListener.
private boolean isClean;
- public SingleFieldBuilderV3(
- MType message,
- AbstractMessage.BuilderParent parent,
- boolean isClean) {
+ public SingleFieldBuilderV3(MType message, AbstractMessage.BuilderParent parent, boolean isClean) {
this.message = checkNotNull(message);
this.parent = parent;
this.isClean = isClean;
@@ -97,10 +88,9 @@ public class SingleFieldBuilderV3
}
/**
- * Get the message for the field. If the message is currently stored
- * as a {@code Builder}, it is converted to a {@code Message} by
- * calling {@link Message.Builder#buildPartial} on it. If no message has
- * been set, returns the default instance of the message.
+ * Get the message for the field. If the message is currently stored as a {@code Builder}, it is
+ * converted to a {@code Message} by calling {@link Message.Builder#buildPartial} on it. If no
+ * message has been set, returns the default instance of the message.
*
* @return the message for the field
*/
@@ -126,8 +116,8 @@ public class SingleFieldBuilderV3
}
/**
- * Gets a builder for the field. If no builder has been created yet, a
- * builder is created on demand by calling {@link Message#toBuilder}.
+ * Gets a builder for the field. If no builder has been created yet, a builder is created on
+ * demand by calling {@link Message#toBuilder}.
*
* @return The builder for the field
*/
@@ -146,28 +136,27 @@ public class SingleFieldBuilderV3
}
/**
- * Gets the base class interface for the field. This may either be a builder
- * or a message. It will return whatever is more efficient.
+ * Gets the base class interface for the field. This may either be a builder or a message. It will
+ * return whatever is more efficient.
*
* @return the message or builder for the field as the base class interface
*/
@SuppressWarnings("unchecked")
public IType getMessageOrBuilder() {
if (builder != null) {
- return (IType) builder;
+ return (IType) builder;
} else {
return (IType) message;
}
}
/**
- * Sets a message for the field replacing any existing value.
+ * Sets a message for the field replacing any existing value.
*
* @param message the message to set
* @return the builder
*/
- public SingleFieldBuilderV3<MType, BType, IType> setMessage(
- MType message) {
+ public SingleFieldBuilderV3<MType, BType, IType> setMessage(MType message) {
this.message = checkNotNull(message);
if (builder != null) {
builder.dispose();
@@ -183,8 +172,7 @@ public class SingleFieldBuilderV3
* @param value the value to merge from
* @return the builder
*/
- public SingleFieldBuilderV3<MType, BType, IType> mergeFrom(
- MType value) {
+ public SingleFieldBuilderV3<MType, BType, IType> mergeFrom(MType value) {
if (builder == null && message == message.getDefaultInstanceForType()) {
message = value;
} else {
@@ -201,9 +189,11 @@ public class SingleFieldBuilderV3
*/
@SuppressWarnings("unchecked")
public SingleFieldBuilderV3<MType, BType, IType> clear() {
- message = (MType) (message != null ?
- message.getDefaultInstanceForType() :
- builder.getDefaultInstanceForType());
+ message =
+ (MType)
+ (message != null
+ ? message.getDefaultInstanceForType()
+ : builder.getDefaultInstanceForType());
if (builder != null) {
builder.dispose();
builder = null;
@@ -213,8 +203,8 @@ public class SingleFieldBuilderV3
}
/**
- * Called when a the builder or one of its nested children has changed
- * and any parent should be notified of its invalidation.
+ * Called when a the builder or one of its nested children has changed and any parent should be
+ * notified of its invalidation.
*/
private void onChanged() {
// If builder is null, this is the case where onChanged is being called
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 279edc4d..6bd65d6f 100644
--- a/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
+++ b/java/core/src/main/java/com/google/protobuf/SmallSortedMap.java
@@ -43,15 +43,14 @@ import java.util.SortedMap;
import java.util.TreeMap;
/**
- * A custom map implementation from FieldDescriptor to Object optimized to
- * minimize the number of memory allocations for instances with a small number
- * of mappings. The implementation stores the first {@code k} mappings in an
- * array for a configurable value of {@code k}, allowing direct access to the
- * corresponding {@code Entry}s without the need to create an Iterator. The
- * remaining entries are stored in an overflow map. Iteration over the entries
- * in the map should be done as follows:
+ * A custom map implementation from FieldDescriptor to Object optimized to minimize the number of
+ * memory allocations for instances with a small number of mappings. The implementation stores the
+ * first {@code k} mappings in an array for a configurable value of {@code k}, allowing direct
+ * access to the corresponding {@code Entry}s without the need to create an Iterator. The remaining
+ * entries are stored in an overflow map. Iteration over the entries in the map should be done as
+ * follows:
*
- * <pre> {@code
+ * <pre>{@code
* for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) {
* process(fieldMap.getArrayEntryAt(i));
* }
@@ -60,24 +59,21 @@ import java.util.TreeMap;
* }
* }</pre>
*
- * The resulting iteration is in order of ascending field tag number. The
- * object returned by {@link #entrySet()} adheres to the same contract but is
- * less efficient as it necessarily involves creating an object for iteration.
- * <p>
- * The tradeoff for this memory efficiency is that the worst case running time
- * of the {@code put()} operation is {@code O(k + lg n)}, which happens when
- * entries are added in descending order. {@code k} should be chosen such that
- * it covers enough common cases without adversely affecting larger maps. In
- * practice, the worst case scenario does not happen for extensions because
- * extension fields are serialized and deserialized in order of ascending tag
- * number, but the worst case scenario can happen for DynamicMessages.
- * <p>
- * The running time for all other operations is similar to that of
- * {@code TreeMap}.
- * <p>
- * Instances are not thread-safe until {@link #makeImmutable()} is called,
- * after which any modifying operation will result in an
- * {@link UnsupportedOperationException}.
+ * The resulting iteration is in order of ascending field tag number. The object returned by {@link
+ * #entrySet()} adheres to the same contract but is less efficient as it necessarily involves
+ * creating an object for iteration.
+ *
+ * <p>The tradeoff for this memory efficiency is that the worst case running time of the {@code
+ * put()} operation is {@code O(k + lg n)}, which happens when entries are added in descending
+ * order. {@code k} should be chosen such that it covers enough common cases without adversely
+ * affecting larger maps. In practice, the worst case scenario does not happen for extensions
+ * because extension fields are serialized and deserialized in order of ascending tag number, but
+ * the worst case scenario can happen for DynamicMessages.
+ *
+ * <p>The running time for all other operations is similar to that of {@code TreeMap}.
+ *
+ * <p>Instances are not thread-safe until {@link #makeImmutable()} is called, after which any
+ * modifying operation will result in an {@link UnsupportedOperationException}.
*
* @author darick@google.com Darick Tong
*/
@@ -87,15 +83,14 @@ import java.util.TreeMap;
class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
- * Creates a new instance for mapping FieldDescriptors to their values.
- * The {@link #makeImmutable()} implementation will convert the List values
- * of any repeated fields to unmodifiable lists.
+ * Creates a new instance for mapping FieldDescriptors to their values. The {@link
+ * #makeImmutable()} implementation will convert the List values of any repeated fields to
+ * unmodifiable lists.
*
- * @param arraySize The size of the entry array containing the
- * lexicographically smallest mappings.
+ * @param arraySize The size of the entry array containing the lexicographically smallest
+ * mappings.
*/
- static <FieldDescriptorType extends
- FieldSet.FieldDescriptorLite<FieldDescriptorType>>
+ static <FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>>
SmallSortedMap<FieldDescriptorType, Object> newFieldMap(int arraySize) {
return new SmallSortedMap<FieldDescriptorType, Object>(arraySize) {
@Override
@@ -103,15 +98,13 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
public void makeImmutable() {
if (!isImmutable()) {
for (int i = 0; i < getNumArrayEntries(); i++) {
- final Map.Entry<FieldDescriptorType, Object> entry =
- getArrayEntryAt(i);
+ final Map.Entry<FieldDescriptorType, Object> entry = getArrayEntryAt(i);
if (entry.getKey().isRepeated()) {
final List value = (List) entry.getValue();
entry.setValue(Collections.unmodifiableList(value));
}
}
- for (Map.Entry<FieldDescriptorType, Object> entry :
- getOverflowEntries()) {
+ for (Map.Entry<FieldDescriptorType, Object> entry : getOverflowEntries()) {
if (entry.getKey().isRepeated()) {
final List value = (List) entry.getValue();
entry.setValue(Collections.unmodifiableList(value));
@@ -126,11 +119,10 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
* Creates a new instance for testing.
*
- * @param arraySize The size of the entry array containing the
- * lexicographically smallest mappings.
+ * @param arraySize The size of the entry array containing the lexicographically smallest
+ * mappings.
*/
- static <K extends Comparable<K>, V> SmallSortedMap<K, V> newInstanceForTest(
- int arraySize) {
+ static <K extends Comparable<K>, V> SmallSortedMap<K, V> newInstanceForTest(int arraySize) {
return new SmallSortedMap<K, V>(arraySize);
}
@@ -146,9 +138,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
private volatile EntrySet lazyEntrySet;
/**
- * @code arraySize Size of the array in which the lexicographically smallest
- * mappings are stored. (i.e. the {@code k} referred to in the class
- * documentation).
+ * @code arraySize Size of the array in which the lexicographically smallest mappings are stored.
+ * (i.e. the {@code k} referred to in the class documentation).
*/
private SmallSortedMap(int arraySize) {
this.maxArraySize = arraySize;
@@ -163,9 +154,10 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
// because none of the list's accessors are exposed. The iterator() of
// overflowEntries, on the other hand, is exposed so it must be made
// unmodifiable.
- overflowEntries = overflowEntries.isEmpty() ?
- Collections.<K, V>emptyMap() :
- Collections.unmodifiableMap(overflowEntries);
+ overflowEntries =
+ overflowEntries.isEmpty()
+ ? Collections.<K, V>emptyMap()
+ : Collections.unmodifiableMap(overflowEntries);
isImmutable = true;
}
}
@@ -192,9 +184,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/** @return An iterable over the overflow entries. */
public Iterable<Map.Entry<K, V>> getOverflowEntries() {
- return overflowEntries.isEmpty() ?
- EmptySet.<Map.Entry<K, V>>iterable() :
- overflowEntries.entrySet();
+ return overflowEntries.isEmpty()
+ ? EmptySet.<Map.Entry<K, V>>iterable()
+ : overflowEntries.entrySet();
}
@@ -204,10 +196,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * The implementation throws a {@code ClassCastException} if o is not an
- * object of type {@code K}.
+ * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public boolean containsKey(Object o) {
@@ -217,10 +208,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * The implementation throws a {@code ClassCastException} if o is not an
- * object of type {@code K}.
+ * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public V get(Object o) {
@@ -251,8 +241,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
if (entryList.size() == maxArraySize) {
// Shift the last array entry into overflow.
final Entry lastEntryInArray = entryList.remove(maxArraySize - 1);
- getOverflowEntriesMutable().put(lastEntryInArray.getKey(),
- lastEntryInArray.getValue());
+ getOverflowEntriesMutable().put(lastEntryInArray.getKey(), lastEntryInArray.getValue());
}
entryList.add(insertionPoint, new Entry(key, value));
return null;
@@ -270,10 +259,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * The implementation throws a {@code ClassCastException} if o is not an
- * object of type {@code K}.
+ * The implementation throws a {@code ClassCastException} if o is not an object of type {@code K}.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public V remove(Object o) {
@@ -299,8 +287,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
if (!overflowEntries.isEmpty()) {
// Shift the first entry in the overflow to be the last entry in the
// array.
- final Iterator<Map.Entry<K, V>> iterator =
- getOverflowEntriesMutable().entrySet().iterator();
+ final Iterator<Map.Entry<K, V>> iterator = getOverflowEntriesMutable().entrySet().iterator();
entryList.add(new Entry(iterator.next()));
iterator.remove();
}
@@ -309,8 +296,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
* @param key The key to find in the entry array.
- * @return The returned integer position follows the same semantics as the
- * value returned by {@link java.util.Arrays#binarySearch()}.
+ * @return The returned integer position follows the same semantics as the value returned by
+ * {@link java.util.Arrays#binarySearch()}.
*/
private int binarySearchInArray(K key) {
int left = 0;
@@ -322,7 +309,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
if (right >= 0) {
int cmp = key.compareTo(entryList.get(right).getKey());
if (cmp > 0) {
- return -(right + 2); // Insert point is after "right".
+ return -(right + 2); // Insert point is after "right".
} else if (cmp == 0) {
return right;
}
@@ -343,11 +330,11 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * Similar to the AbstractMap implementation of {@code keySet()} and
- * {@code values()}, the entry set is created the first time this method is
- * called, and returned in response to all subsequent calls.
+ * Similar to the AbstractMap implementation of {@code keySet()} and {@code values()}, the entry
+ * set is created the first time this method is called, and returned in response to all subsequent
+ * calls.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public Set<Map.Entry<K, V>> entrySet() {
@@ -358,10 +345,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
- /**
- * @throws UnsupportedOperationException if {@link #makeImmutable()} has
- * has been called.
- */
+ /** @throws UnsupportedOperationException if {@link #makeImmutable()} has has been called. */
private void checkMutable() {
if (isImmutable) {
throw new UnsupportedOperationException();
@@ -369,10 +353,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * @return a {@link SortedMap} to which overflow entries mappings can be
- * added or removed.
- * @throws UnsupportedOperationException if {@link #makeImmutable()} has been
- * called.
+ * @return a {@link SortedMap} to which overflow entries mappings can be added or removed.
+ * @throws UnsupportedOperationException if {@link #makeImmutable()} has been called.
*/
@SuppressWarnings("unchecked")
private SortedMap<K, V> getOverflowEntriesMutable() {
@@ -383,10 +365,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
return (SortedMap<K, V>) overflowEntries;
}
- /**
- * Lazily creates the entry list. Any code that adds to the list must first
- * call this method.
- */
+ /** Lazily creates the entry list. Any code that adds to the list must first call this method. */
private void ensureEntryArrayMutable() {
checkMutable();
if (entryList.isEmpty() && !(entryList instanceof ArrayList)) {
@@ -395,9 +374,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * Entry implementation that implements Comparable in order to support
- * binary search within the entry array. Also checks mutability in
- * {@link #setValue()}.
+ * Entry implementation that implements Comparable in order to support binary search within the
+ * entry array. Also checks mutability in {@link #setValue()}.
*/
private class Entry implements Map.Entry<K, V>, Comparable<Entry> {
@@ -451,8 +429,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
@Override
public int hashCode() {
- return (key == null ? 0 : key.hashCode()) ^
- (value == null ? 0 : value.hashCode());
+ return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
@Override
@@ -466,9 +443,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
}
- /**
- * Stateless view of the entries in the field map.
- */
+ /** Stateless view of the entries in the field map. */
private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
@@ -484,7 +459,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
* Throws a {@link ClassCastException} if o is not of the expected type.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public boolean contains(Object o) {
@@ -492,8 +467,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
final Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
final V existing = get(entry.getKey());
final V value = entry.getValue();
- return existing == value ||
- (existing != null && existing.equals(value));
+ return existing == value || (existing != null && existing.equals(value));
}
@Override
@@ -508,7 +482,7 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
* Throws a {@link ClassCastException} if o is not of the expected type.
*
- * {@inheritDoc}
+ * <p>{@inheritDoc}
*/
@Override
public boolean remove(Object o) {
@@ -529,8 +503,8 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
/**
- * Iterator implementation that switches from the entry array to the overflow
- * entries appropriately.
+ * Iterator implementation that switches from the entry array to the overflow entries
+ * appropriately.
*/
private class EntryIterator implements Iterator<Map.Entry<K, V>> {
@@ -571,10 +545,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * It is important to create the overflow iterator only after the array
- * entries have been iterated over because the overflow entry set changes
- * when the client calls remove() on the array entries, which invalidates
- * any existing iterators.
+ * It is important to create the overflow iterator only after the array entries have been
+ * iterated over because the overflow entry set changes when the client calls remove() on the
+ * array entries, which invalidates any existing iterators.
*/
private Iterator<Map.Entry<K, V>> getOverflowIterator() {
if (lazyOverflowIterator == null) {
@@ -585,9 +558,9 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
}
/**
- * Helper class that holds immutable instances of an Iterable/Iterator that
- * we return when the overflow entries is empty. This eliminates the creation
- * of an Iterator object when there is nothing to iterate over.
+ * Helper class that holds immutable instances of an Iterable/Iterator that we return when the
+ * overflow entries is empty. This eliminates the creation of an Iterator object when there is
+ * nothing to iterate over.
*/
private static class EmptySet {
@@ -597,10 +570,12 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
public boolean hasNext() {
return false;
}
+
@Override
public Object next() {
throw new NoSuchElementException();
}
+
@Override
public void remove() {
throw new UnsupportedOperationException();
@@ -653,7 +628,6 @@ class SmallSortedMap<K extends Comparable<K>, V> extends AbstractMap<K, V> {
return overflowEntries.equals(other.overflowEntries);
}
-
return true;
}
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 25c3474f..f89768a1 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -46,8 +46,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
- * Provide text parsing and formatting support for proto2 instances.
- * The implementation largely follows google/protobuf/text_format.cc.
+ * Provide text parsing and formatting support for proto2 instances. The implementation largely
+ * follows google/protobuf/text_format.cc.
*
* @author wenboz@google.com Wenbo Zhu
* @author kenton@google.com Kenton Varda
@@ -58,46 +58,36 @@ public final class TextFormat {
private static final Logger logger = Logger.getLogger(TextFormat.class.getName());
/**
- * Outputs a textual representation of the Protocol Message supplied into
- * the parameter output. (This representation is the new version of the
- * classic "ProtocolPrinter" output from the original Protocol Buffer system)
+ * Outputs a textual representation of the Protocol Message supplied into the parameter output.
+ * (This representation is the new version of the classic "ProtocolPrinter" output from the
+ * original Protocol Buffer system)
*/
- public static void print(
- final MessageOrBuilder message, final Appendable output)
+ public static void print(final MessageOrBuilder message, final Appendable output)
throws IOException {
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 {
+ public static void print(final UnknownFieldSet fields, final Appendable output)
+ throws IOException {
Printer.DEFAULT.printUnknownFields(fields, multiLineOutput(output));
}
- /**
- * Same as {@code print()}, except that non-ASCII characters are not
- * escaped.
- */
- public static void printUnicode(
- final MessageOrBuilder message, final Appendable output)
+ /** Same as {@code print()}, except that non-ASCII characters are not escaped. */
+ public static void printUnicode(final MessageOrBuilder message, final Appendable output)
throws IOException {
Printer.UNICODE.print(message, multiLineOutput(output));
}
- /**
- * Same as {@code print()}, except that non-ASCII characters are not
- * escaped.
- */
- public static void printUnicode(final UnknownFieldSet fields,
- final Appendable output)
- throws IOException {
+ /** Same as {@code print()}, except that non-ASCII characters are not escaped. */
+ public static void printUnicode(final UnknownFieldSet fields, final Appendable output)
+ throws IOException {
Printer.UNICODE.printUnknownFields(fields, multiLineOutput(output));
}
/**
- * Generates a human readable form of this message, useful for debugging and
- * other purposes, with no newline characters.
+ * Generates a human readable form of this message, useful for debugging and other purposes, with
+ * no newline characters.
*/
public static String shortDebugString(final MessageOrBuilder message) {
try {
@@ -110,11 +100,10 @@ public final class TextFormat {
}
/**
- * Generates a human readable form of the field, useful for debugging
- * and other purposes, with no newline characters.
+ * Generates a human readable form of the field, useful for debugging and other purposes, with no
+ * newline characters.
*/
- public static String shortDebugString(final FieldDescriptor field,
- final Object value) {
+ public static String shortDebugString(final FieldDescriptor field, final Object value) {
try {
final StringBuilder text = new StringBuilder();
Printer.DEFAULT.printField(field, value, singleLineOutput(text));
@@ -125,8 +114,8 @@ public final class TextFormat {
}
/**
- * Generates a human readable form of the unknown fields, useful for debugging
- * and other purposes, with no newline characters.
+ * Generates a human readable form of the unknown fields, useful for debugging and other purposes,
+ * with no newline characters.
*/
public static String shortDebugString(final UnknownFieldSet fields) {
try {
@@ -138,10 +127,7 @@ public final class TextFormat {
}
}
- /**
- * Like {@code print()}, but writes directly to a {@code String} and
- * returns it.
- */
+ /** Like {@code print()}, but writes directly to a {@code String} and returns it. */
public static String printToString(final MessageOrBuilder message) {
try {
final StringBuilder text = new StringBuilder();
@@ -152,10 +138,7 @@ public final class TextFormat {
}
}
- /**
- * Like {@code print()}, but writes directly to a {@code String} and
- * returns it.
- */
+ /** Like {@code print()}, but writes directly to a {@code String} and returns it. */
public static String printToString(final UnknownFieldSet fields) {
try {
final StringBuilder text = new StringBuilder();
@@ -167,8 +150,8 @@ public final class TextFormat {
}
/**
- * Same as {@code printToString()}, except that non-ASCII characters
- * in string type fields are not escaped in backslash+octals.
+ * Same as {@code printToString()}, except that non-ASCII characters in string type fields are not
+ * escaped in backslash+octals.
*/
public static String printToUnicodeString(final MessageOrBuilder message) {
try {
@@ -181,8 +164,8 @@ public final class TextFormat {
}
/**
- * Same as {@code printToString()}, except that non-ASCII characters
- * in string type fields are not escaped in backslash+octals.
+ * Same as {@code printToString()}, except that non-ASCII characters in string type fields are not
+ * escaped in backslash+octals.
*/
public static String printToUnicodeString(final UnknownFieldSet fields) {
try {
@@ -194,15 +177,12 @@ public final class TextFormat {
}
}
- public static void printField(final FieldDescriptor field,
- final Object value,
- final Appendable output)
- throws IOException {
+ public static void printField(
+ final FieldDescriptor field, final Object value, final Appendable output) throws IOException {
Printer.DEFAULT.printField(field, value, multiLineOutput(output));
}
- public static String printFieldToString(final FieldDescriptor field,
- final Object value) {
+ public static String printFieldToString(final FieldDescriptor field, final Object value) {
try {
final StringBuilder text = new StringBuilder();
printField(field, value, text);
@@ -235,14 +215,11 @@ public final class TextFormat {
* @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 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 printFieldValue(final FieldDescriptor field,
- final Object value,
- final Appendable output)
- throws IOException {
+ public static void printFieldValue(
+ final FieldDescriptor field, final Object value, final Appendable output) throws IOException {
Printer.DEFAULT.printFieldValue(field, value, multiLineOutput(output));
}
@@ -252,28 +229,22 @@ public final class TextFormat {
* @param tag the field's tag number
* @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 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 printUnknownFieldValue(final int tag,
- final Object value,
- final Appendable output)
- throws IOException {
+ public static void printUnknownFieldValue(
+ final int tag, final Object value, final Appendable output) throws IOException {
printUnknownFieldValue(tag, value, multiLineOutput(output));
}
- private static void printUnknownFieldValue(final int tag,
- final Object value,
- final TextGenerator generator)
- throws IOException {
+ private static void printUnknownFieldValue(
+ final int tag, final Object value, final TextGenerator generator) throws IOException {
switch (WireFormat.getTagWireType(tag)) {
case WireFormat.WIRETYPE_VARINT:
generator.print(unsignedToString((Long) value));
break;
case WireFormat.WIRETYPE_FIXED32:
- generator.print(
- String.format((Locale) null, "0x%08x", (Integer) value));
+ generator.print(String.format((Locale) null, "0x%08x", (Integer) value));
break;
case WireFormat.WIRETYPE_FIXED64:
generator.print(String.format((Locale) null, "0x%016x", (Long) value));
@@ -317,18 +288,17 @@ public final class TextFormat {
this.escapeNonAscii = escapeNonAscii;
}
- private void print(
- final MessageOrBuilder message, final TextGenerator generator)
+ private void print(final MessageOrBuilder message, final TextGenerator generator)
throws IOException {
- for (Map.Entry<FieldDescriptor, Object> field
- : message.getAllFields().entrySet()) {
+ for (Map.Entry<FieldDescriptor, Object> field : message.getAllFields().entrySet()) {
printField(field.getKey(), field.getValue(), generator);
}
printUnknownFields(message.getUnknownFields(), generator);
}
- private void printField(final FieldDescriptor field, final Object value,
- final TextGenerator generator) throws IOException {
+ private void printField(
+ final FieldDescriptor field, final Object value, final TextGenerator generator)
+ throws IOException {
if (field.isRepeated()) {
// Repeated field. Print each element.
for (Object element : (List<?>) value) {
@@ -339,10 +309,9 @@ public final class TextFormat {
}
}
- private void printSingleField(final FieldDescriptor field,
- final Object value,
- final TextGenerator generator)
- throws IOException {
+ private void printSingleField(
+ final FieldDescriptor field, final Object value, final TextGenerator generator)
+ throws IOException {
if (field.isExtension()) {
generator.print("[");
// We special-case MessageSet elements for compatibility with proto1.
@@ -382,10 +351,9 @@ public final class TextFormat {
generator.eol();
}
- private void printFieldValue(final FieldDescriptor field,
- final Object value,
- final TextGenerator generator)
- throws IOException {
+ private void printFieldValue(
+ final FieldDescriptor field, final Object value, final TextGenerator generator)
+ throws IOException {
switch (field.getType()) {
case INT32:
case SINT32:
@@ -423,10 +391,10 @@ public final class TextFormat {
case STRING:
generator.print("\"");
- generator.print(escapeNonAscii
- ? TextFormatEscaper.escapeText((String) value)
- : escapeDoubleQuotesAndBackslashes((String) value)
- .replace("\n", "\\n"));
+ generator.print(
+ escapeNonAscii
+ ? TextFormatEscaper.escapeText((String) value)
+ : escapeDoubleQuotesAndBackslashes((String) value).replace("\n", "\\n"));
generator.print("\"");
break;
@@ -451,21 +419,19 @@ public final class TextFormat {
}
}
- private void printUnknownFields(final UnknownFieldSet unknownFields,
- final TextGenerator generator)
- throws IOException {
- for (Map.Entry<Integer, UnknownFieldSet.Field> entry :
- unknownFields.asMap().entrySet()) {
+ private void printUnknownFields(
+ final UnknownFieldSet unknownFields, final TextGenerator generator) throws IOException {
+ for (Map.Entry<Integer, UnknownFieldSet.Field> entry : unknownFields.asMap().entrySet()) {
final int number = entry.getKey();
final UnknownFieldSet.Field field = entry.getValue();
- printUnknownField(number, WireFormat.WIRETYPE_VARINT,
- field.getVarintList(), generator);
- printUnknownField(number, WireFormat.WIRETYPE_FIXED32,
- field.getFixed32List(), generator);
- printUnknownField(number, WireFormat.WIRETYPE_FIXED64,
- field.getFixed64List(), generator);
- printUnknownField(number, WireFormat.WIRETYPE_LENGTH_DELIMITED,
- field.getLengthDelimitedList(), generator);
+ printUnknownField(number, WireFormat.WIRETYPE_VARINT, field.getVarintList(), generator);
+ printUnknownField(number, WireFormat.WIRETYPE_FIXED32, field.getFixed32List(), generator);
+ printUnknownField(number, WireFormat.WIRETYPE_FIXED64, field.getFixed64List(), generator);
+ printUnknownField(
+ number,
+ WireFormat.WIRETYPE_LENGTH_DELIMITED,
+ field.getLengthDelimitedList(),
+ generator);
for (final UnknownFieldSet value : field.getGroupList()) {
generator.print(entry.getKey().toString());
generator.print(" {");
@@ -479,11 +445,9 @@ public final class TextFormat {
}
}
- private void printUnknownField(final int number,
- final int wireType,
- final List<?> values,
- final TextGenerator generator)
- throws IOException {
+ private void printUnknownField(
+ final int number, final int wireType, final List<?> values, final TextGenerator generator)
+ throws IOException {
for (final Object value : values) {
generator.print(String.valueOf(number));
generator.print(": ");
@@ -509,8 +473,7 @@ public final class TextFormat {
} else {
// Pull off the most-significant bit so that BigInteger doesn't think
// the number is negative, then set it again using setBit().
- return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL)
- .setBit(63).toString();
+ return BigInteger.valueOf(value & 0x7FFFFFFFFFFFFFFFL).setBit(63).toString();
}
}
@@ -522,9 +485,7 @@ public final class TextFormat {
return new TextGenerator(output, true);
}
- /**
- * An inner class for writing text to the output stream.
- */
+ /** 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();
@@ -540,23 +501,19 @@ public final class TextFormat {
}
/**
- * 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.
*/
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. */
public void outdent() {
final int length = indent.length();
if (length == 0) {
- throw new IllegalArgumentException(
- " Outdent() without matching Indent().");
+ throw new IllegalArgumentException(" Outdent() without matching Indent().");
}
indent.setLength(length - 2);
}
@@ -592,30 +549,26 @@ public final class TextFormat {
/**
* Represents a stream of tokens parsed from a {@code String}.
*
- * <p>The Java standard library provides many classes that you might think
- * would be useful for implementing this, but aren't. For example:
+ * <p>The Java standard library provides many classes that you might think would be useful for
+ * implementing this, but aren't. For example:
*
* <ul>
- * <li>{@code java.io.StreamTokenizer}: This almost does what we want -- or,
- * at least, something that would get us close to what we want -- except
- * for one fatal flaw: It automatically un-escapes strings using Java
- * escape sequences, which do not include all the escape sequences we
- * need to support (e.g. '\x').
- * <li>{@code java.util.Scanner}: This seems like a great way at least to
- * parse regular expressions out of a stream (so we wouldn't have to load
- * the entire input into a single string before parsing). Sadly,
- * {@code Scanner} requires that tokens be delimited with some delimiter.
- * Thus, although the text "foo:" should parse to two tokens ("foo" and
- * ":"), {@code Scanner} would recognize it only as a single token.
- * Furthermore, {@code Scanner} provides no way to inspect the contents
- * of delimiters, making it impossible to keep track of line and column
- * numbers.
+ * <li>{@code java.io.StreamTokenizer}: This almost does what we want -- or, at least, something
+ * that would get us close to what we want -- except for one fatal flaw: It automatically
+ * un-escapes strings using Java escape sequences, which do not include all the escape
+ * sequences we need to support (e.g. '\x').
+ * <li>{@code java.util.Scanner}: This seems like a great way at least to parse regular
+ * expressions out of a stream (so we wouldn't have to load the entire input into a single
+ * string before parsing). Sadly, {@code Scanner} requires that tokens be delimited with
+ * some delimiter. Thus, although the text "foo:" should parse to two tokens ("foo" and
+ * ":"), {@code Scanner} would recognize it only as a single token. Furthermore, {@code
+ * Scanner} provides no way to inspect the contents of delimiters, making it impossible to
+ * keep track of line and column numbers.
* </ul>
*
- * <p>Luckily, Java's regular expression support does manage to be useful to
- * us. (Barely: We need {@code Matcher.usePattern()}, which is new in
- * Java 1.5.) So, we can use that, at least. Unfortunately, this implies
- * that we need to have the entire input in one contiguous string.
+ * <p>Luckily, Java's regular expression support does manage to be useful to us. (Barely: We need
+ * {@code Matcher.usePattern()}, which is new in Java 1.5.) So, we can use that, at least.
+ * Unfortunately, this implies that we need to have the entire input in one contiguous string.
*/
private static final class Tokenizer {
private final CharSequence text;
@@ -636,24 +589,20 @@ public final class TextFormat {
// We use possessive quantifiers (*+ and ++) because otherwise the Java
// regex matcher has stack overflows on large inputs.
- private static final Pattern WHITESPACE =
- Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE);
- private static final Pattern TOKEN = Pattern.compile(
- "[a-zA-Z_][0-9a-zA-Z_+-]*+|" + // an identifier
- "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" + // a number
- "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" + // a double-quoted string
- "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string
- Pattern.MULTILINE);
-
- private static final Pattern DOUBLE_INFINITY = Pattern.compile(
- "-?inf(inity)?",
- Pattern.CASE_INSENSITIVE);
- private static final Pattern FLOAT_INFINITY = Pattern.compile(
- "-?inf(inity)?f?",
- Pattern.CASE_INSENSITIVE);
- private static final Pattern FLOAT_NAN = Pattern.compile(
- "nanf?",
- Pattern.CASE_INSENSITIVE);
+ private static final Pattern WHITESPACE = Pattern.compile("(\\s|(#.*$))++", Pattern.MULTILINE);
+ private static final Pattern TOKEN =
+ Pattern.compile(
+ "[a-zA-Z_][0-9a-zA-Z_+-]*+|" // an identifier
+ + "[.]?[0-9+-][0-9a-zA-Z_.+-]*+|" // a number
+ + "\"([^\"\n\\\\]|\\\\.)*+(\"|\\\\?$)|" // a double-quoted string
+ + "\'([^\'\n\\\\]|\\\\.)*+(\'|\\\\?$)", // a single-quoted string
+ Pattern.MULTILINE);
+
+ private static final Pattern DOUBLE_INFINITY =
+ Pattern.compile("-?inf(inity)?", Pattern.CASE_INSENSITIVE);
+ private static final Pattern FLOAT_INFINITY =
+ Pattern.compile("-?inf(inity)?f?", Pattern.CASE_INSENSITIVE);
+ private static final Pattern FLOAT_NAN = Pattern.compile("nanf?", Pattern.CASE_INSENSITIVE);
/** Construct a tokenizer that parses tokens from the given text. */
private Tokenizer(final CharSequence text) {
@@ -719,10 +668,7 @@ public final class TextFormat {
}
}
- /**
- * Skip over any whitespace so that the matcher region starts at the next
- * token.
- */
+ /** Skip over any whitespace so that the matcher region starts at the next token. */
private void skipWhitespace() {
matcher.usePattern(WHITESPACE);
if (matcher.lookingAt()) {
@@ -731,8 +677,8 @@ public final class TextFormat {
}
/**
- * If the next token exactly matches {@code token}, consume it and return
- * {@code true}. Otherwise, return {@code false} without doing anything.
+ * If the next token exactly matches {@code token}, consume it and return {@code true}.
+ * Otherwise, return {@code false} without doing anything.
*/
public boolean tryConsume(final String token) {
if (currentToken.equals(token)) {
@@ -744,8 +690,8 @@ public final class TextFormat {
}
/**
- * If the next token exactly matches {@code token}, consume it. Otherwise,
- * throw a {@link ParseException}.
+ * If the next token exactly matches {@code token}, consume it. Otherwise, throw a {@link
+ * ParseException}.
*/
public void consume(final String token) throws ParseException {
if (!tryConsume(token)) {
@@ -753,31 +699,24 @@ public final class TextFormat {
}
}
- /**
- * Returns {@code true} if the next token is an integer, but does
- * not consume it.
- */
+ /** Returns {@code true} if the next token is an integer, but does not consume it. */
public boolean lookingAtInteger() {
if (currentToken.length() == 0) {
return false;
}
final char c = currentToken.charAt(0);
- return ('0' <= c && c <= '9')
- || c == '-' || c == '+';
+ return ('0' <= c && c <= '9') || c == '-' || c == '+';
}
- /**
- * Returns {@code true} if the current token's text is equal to that
- * specified.
- */
+ /** Returns {@code true} if the current token's text is equal to that specified. */
public boolean lookingAt(String text) {
return currentToken.equals(text);
}
/**
- * If the next token is an identifier, consume it and return its value.
- * Otherwise, throw a {@link ParseException}.
+ * If the next token is an identifier, consume it and return its value. Otherwise, throw a
+ * {@link ParseException}.
*/
public String consumeIdentifier() throws ParseException {
for (int i = 0; i < currentToken.length(); i++) {
@@ -785,11 +724,11 @@ public final class TextFormat {
if (('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| ('0' <= c && c <= '9')
- || (c == '_') || (c == '.')) {
+ || (c == '_')
+ || (c == '.')) {
// OK
} else {
- throw parseException(
- "Expected identifier. Found '" + currentToken + "'");
+ throw parseException("Expected identifier. Found '" + currentToken + "'");
}
}
@@ -799,8 +738,8 @@ public final class TextFormat {
}
/**
- * If the next token is an identifier, consume it and return {@code true}.
- * Otherwise, return {@code false} without doing anything.
+ * If the next token is an identifier, consume it and return {@code true}. Otherwise, return
+ * {@code false} without doing anything.
*/
public boolean tryConsumeIdentifier() {
try {
@@ -812,8 +751,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 32-bit signed integer, consume it and return its
- * value. Otherwise, throw a {@link ParseException}.
+ * If the next token is a 32-bit signed integer, consume it and return its value. Otherwise,
+ * throw a {@link ParseException}.
*/
public int consumeInt32() throws ParseException {
try {
@@ -826,8 +765,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 32-bit unsigned integer, consume it and return its
- * value. Otherwise, throw a {@link ParseException}.
+ * If the next token is a 32-bit unsigned integer, consume it and return its value. Otherwise,
+ * throw a {@link ParseException}.
*/
public int consumeUInt32() throws ParseException {
try {
@@ -840,8 +779,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 64-bit signed integer, consume it and return its
- * value. Otherwise, throw a {@link ParseException}.
+ * If the next token is a 64-bit signed integer, consume it and return its value. Otherwise,
+ * throw a {@link ParseException}.
*/
public long consumeInt64() throws ParseException {
try {
@@ -854,8 +793,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 64-bit signed integer, consume it and return
- * {@code true}. Otherwise, return {@code false} without doing anything.
+ * If the next token is a 64-bit signed integer, consume it and return {@code true}. Otherwise,
+ * return {@code false} without doing anything.
*/
public boolean tryConsumeInt64() {
try {
@@ -867,8 +806,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 64-bit unsigned integer, consume it and return its
- * value. Otherwise, throw a {@link ParseException}.
+ * If the next token is a 64-bit unsigned integer, consume it and return its value. Otherwise,
+ * throw a {@link ParseException}.
*/
public long consumeUInt64() throws ParseException {
try {
@@ -881,8 +820,8 @@ public final class TextFormat {
}
/**
- * If the next token is a 64-bit unsigned integer, consume it and return
- * {@code true}. Otherwise, return {@code false} without doing anything.
+ * If the next token is a 64-bit unsigned integer, consume it and return {@code true}.
+ * Otherwise, return {@code false} without doing anything.
*/
public boolean tryConsumeUInt64() {
try {
@@ -894,8 +833,8 @@ public final class TextFormat {
}
/**
- * If the next token is a double, consume it and return its value.
- * Otherwise, throw a {@link ParseException}.
+ * If the next token is a double, consume it and return its value. Otherwise, throw a {@link
+ * ParseException}.
*/
public double consumeDouble() throws ParseException {
// We need to parse infinity and nan separately because
@@ -919,8 +858,8 @@ public final class TextFormat {
}
/**
- * If the next token is a double, consume it and return {@code true}.
- * Otherwise, return {@code false} without doing anything.
+ * If the next token is a double, consume it and return {@code true}. Otherwise, return {@code
+ * false} without doing anything.
*/
public boolean tryConsumeDouble() {
try {
@@ -932,8 +871,8 @@ public final class TextFormat {
}
/**
- * If the next token is a float, consume it and return its value.
- * Otherwise, throw a {@link ParseException}.
+ * If the next token is a float, consume it and return its value. Otherwise, throw a {@link
+ * ParseException}.
*/
public float consumeFloat() throws ParseException {
// We need to parse infinity and nan separately because
@@ -957,8 +896,8 @@ public final class TextFormat {
}
/**
- * If the next token is a float, consume it and return {@code true}.
- * Otherwise, return {@code false} without doing anything.
+ * If the next token is a float, consume it and return {@code true}. Otherwise, return {@code
+ * false} without doing anything.
*/
public boolean tryConsumeFloat() {
try {
@@ -970,8 +909,8 @@ public final class TextFormat {
}
/**
- * If the next token is a boolean, consume it and return its value.
- * Otherwise, throw a {@link ParseException}.
+ * If the next token is a boolean, consume it and return its value. Otherwise, throw a {@link
+ * ParseException}.
*/
public boolean consumeBoolean() throws ParseException {
if (currentToken.equals("true")
@@ -992,17 +931,14 @@ public final class TextFormat {
}
/**
- * If the next token is a string, consume it and return its (unescaped)
- * value. Otherwise, throw a {@link ParseException}.
+ * If the next token is a string, consume it and return its (unescaped) value. Otherwise, throw
+ * a {@link ParseException}.
*/
public String consumeString() throws ParseException {
return consumeByteString().toStringUtf8();
}
- /**
- * If the next token is a string, consume it and return true. Otherwise,
- * return false.
- */
+ /** If the next token is a string, consume it and return true. Otherwise, return false. */
public boolean tryConsumeString() {
try {
consumeString();
@@ -1013,9 +949,8 @@ public final class TextFormat {
}
/**
- * If the next token is a string, consume it, unescape it as a
- * {@link ByteString}, and return it. Otherwise, throw a
- * {@link ParseException}.
+ * If the next token is a string, consume it, unescape it as a {@link ByteString}, and return
+ * it. Otherwise, throw a {@link ParseException}.
*/
public ByteString consumeByteString() throws ParseException {
List<ByteString> list = new ArrayList<ByteString>();
@@ -1027,28 +962,22 @@ public final class TextFormat {
}
/**
- * Like {@link #consumeByteString()} but adds each token of the string to
- * the given list. String literals (whether bytes or text) may come in
- * multiple adjacent tokens which are automatically concatenated, like in
- * C or Python.
+ * Like {@link #consumeByteString()} but adds each token of the string to the given list. String
+ * literals (whether bytes or text) may come in multiple adjacent tokens which are automatically
+ * concatenated, like in C or Python.
*/
- private void consumeByteString(List<ByteString> list)
- throws ParseException {
- final char quote = currentToken.length() > 0
- ? currentToken.charAt(0)
- : '\0';
+ private void consumeByteString(List<ByteString> list) throws ParseException {
+ final char quote = currentToken.length() > 0 ? currentToken.charAt(0) : '\0';
if (quote != '\"' && quote != '\'') {
throw parseException("Expected string.");
}
- if (currentToken.length() < 2
- || currentToken.charAt(currentToken.length() - 1) != quote) {
+ if (currentToken.length() < 2 || currentToken.charAt(currentToken.length() - 1) != quote) {
throw parseException("String missing ending quote.");
}
try {
- final String escaped =
- currentToken.substring(1, currentToken.length() - 1);
+ final String escaped = currentToken.substring(1, currentToken.length() - 1);
final ByteString result = unescapeBytes(escaped);
nextToken();
list.add(result);
@@ -1058,53 +987,48 @@ public final class TextFormat {
}
/**
- * Returns a {@link ParseException} with the current line and column
- * numbers in the description, suitable for throwing.
+ * Returns a {@link ParseException} with the current line and column numbers in the description,
+ * suitable for throwing.
*/
public ParseException parseException(final String description) {
// Note: People generally prefer one-based line and column numbers.
- return new ParseException(
- line + 1, column + 1, description);
+ return new ParseException(line + 1, column + 1, description);
}
/**
- * Returns a {@link ParseException} with the line and column numbers of
- * the previous token in the description, suitable for throwing.
+ * Returns a {@link ParseException} with the line and column numbers of the previous token in
+ * the description, suitable for throwing.
*/
- public ParseException parseExceptionPreviousToken(
- final String description) {
+ public ParseException parseExceptionPreviousToken(final String description) {
// Note: People generally prefer one-based line and column numbers.
- return new ParseException(
- previousLine + 1, previousColumn + 1, description);
+ return new ParseException(previousLine + 1, previousColumn + 1, description);
}
/**
- * Constructs an appropriate {@link ParseException} for the given
- * {@code NumberFormatException} when trying to parse an integer.
+ * Constructs an appropriate {@link ParseException} for the given {@code NumberFormatException}
+ * when trying to parse an integer.
*/
- private ParseException integerParseException(
- final NumberFormatException e) {
+ private ParseException integerParseException(final NumberFormatException e) {
return parseException("Couldn't parse integer: " + e.getMessage());
}
/**
- * Constructs an appropriate {@link ParseException} for the given
- * {@code NumberFormatException} when trying to parse a float or double.
+ * Constructs an appropriate {@link ParseException} for the given {@code NumberFormatException}
+ * when trying to parse a float or double.
*/
private ParseException floatParseException(final NumberFormatException e) {
return parseException("Couldn't parse number: " + e.getMessage());
}
/**
- * Returns a {@link UnknownFieldParseException} with the line and column
- * numbers of the previous token in the description, and the unknown field
- * name, suitable for throwing.
+ * Returns a {@link UnknownFieldParseException} with the line and column numbers of the previous
+ * token in the description, and the unknown field name, suitable for throwing.
*/
public UnknownFieldParseException unknownFieldParseExceptionPreviousToken(
final String unknownField, final String description) {
// Note: People generally prefer one-based line and column numbers.
return new UnknownFieldParseException(
- previousLine + 1, previousColumn + 1, unknownField, description);
+ previousLine + 1, previousColumn + 1, unknownField, description);
}
}
@@ -1123,47 +1047,39 @@ public final class TextFormat {
/**
* Create a new instance
*
- * @param line the line number where the parse error occurred,
- * using 1-offset.
- * @param column the column number where the parser error occurred,
- * using 1-offset.
+ * @param line the line number where the parse error occurred, using 1-offset.
+ * @param column the column number where the parser error occurred, using 1-offset.
*/
- public ParseException(final int line, final int column,
- final String message) {
+ public ParseException(final int line, final int column, final String message) {
super(Integer.toString(line) + ":" + column + ": " + message);
this.line = line;
this.column = column;
}
/**
- * Return the line where the parse exception occurred, or -1 when
- * none is provided. The value is specified as 1-offset, so the first
- * line is line 1.
+ * Return the line where the parse exception occurred, or -1 when none is provided. The value is
+ * specified as 1-offset, so the first line is line 1.
*/
public int getLine() {
return line;
}
/**
- * Return the column where the parse exception occurred, or -1 when
- * none is provided. The value is specified as 1-offset, so the first
- * line is line 1.
+ * Return the column where the parse exception occurred, or -1 when none is provided. The value
+ * is specified as 1-offset, so the first line is line 1.
*/
public int getColumn() {
return column;
}
}
- /**
- * Thrown when encountering an unknown field while parsing
- * a text format message.
- */
+ /** Thrown when encountering an unknown field while parsing a text format message. */
public static class UnknownFieldParseException extends ParseException {
private final String unknownField;
/**
- * Create a new instance, with -1 as the line and column numbers, and an
- * empty unknown field name.
+ * Create a new instance, with -1 as the line and column numbers, and an empty unknown field
+ * name.
*/
public UnknownFieldParseException(final String message) {
this(-1, -1, "", message);
@@ -1172,21 +1088,18 @@ public final class TextFormat {
/**
* Create a new instance
*
- * @param line the line number where the parse error occurred,
- * using 1-offset.
- * @param column the column number where the parser error occurred,
- * using 1-offset.
+ * @param line the line number where the parse error occurred, using 1-offset.
+ * @param column the column number where the parser error occurred, using 1-offset.
* @param unknownField the name of the unknown field found while parsing.
*/
- public UnknownFieldParseException(final int line, final int column,
- final String unknownField, final String message) {
+ public UnknownFieldParseException(
+ final int line, final int column, final String unknownField, final String message) {
super(line, column, message);
this.unknownField = unknownField;
}
/**
- * Return the name of the unknown field encountered while parsing the
- * protocol buffer string.
+ * Return the name of the unknown field encountered while parsing the protocol buffer string.
*/
public String getUnknownField() {
return unknownField;
@@ -1196,30 +1109,21 @@ public final class TextFormat {
private static final Parser PARSER = Parser.newBuilder().build();
/**
- * Return a {@link Parser} instance which can parse text-format
- * messages. The returned instance is thread-safe.
+ * Return a {@link Parser} instance which can parse text-format messages. The returned instance is
+ * thread-safe.
*/
public static Parser getParser() {
return PARSER;
}
- /**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}.
- */
- public static void merge(final Readable input,
- final Message.Builder builder)
- throws IOException {
+ /** Parse a text-format message from {@code input} and merge the contents into {@code builder}. */
+ public static void merge(final Readable input, final Message.Builder builder) throws IOException {
PARSER.merge(input, builder);
}
- /**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}.
- */
- public static void merge(final CharSequence input,
- final Message.Builder builder)
- throws ParseException {
+ /** Parse a text-format message from {@code input} and merge the contents into {@code builder}. */
+ public static void merge(final CharSequence input, final Message.Builder builder)
+ throws ParseException {
PARSER.merge(input, builder);
}
@@ -1228,11 +1132,9 @@ public final class TextFormat {
*
* @return the parsed message, guaranteed initialized
*/
- public static <T extends Message> T parse(final CharSequence input,
- final Class<T> protoClass)
- throws ParseException {
- Message.Builder builder =
- Internal.getDefaultInstance(protoClass).newBuilderForType();
+ public static <T extends Message> T parse(final CharSequence input, final Class<T> protoClass)
+ throws ParseException {
+ Message.Builder builder = Internal.getDefaultInstance(protoClass).newBuilderForType();
merge(input, builder);
@SuppressWarnings("unchecked")
T output = (T) builder.build();
@@ -1240,33 +1142,33 @@ public final class TextFormat {
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}. Extensions will be recognized if they are
- * registered in {@code extensionRegistry}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
+ * Extensions will be recognized if they are registered in {@code extensionRegistry}.
*/
- public static void merge(final Readable input,
- final ExtensionRegistry extensionRegistry,
- final Message.Builder builder)
- throws IOException {
+ public static void merge(
+ final Readable input,
+ final ExtensionRegistry extensionRegistry,
+ final Message.Builder builder)
+ throws IOException {
PARSER.merge(input, extensionRegistry, builder);
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}. Extensions will be recognized if they are
- * registered in {@code extensionRegistry}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
+ * Extensions will be recognized if they are registered in {@code extensionRegistry}.
*/
- public static void merge(final CharSequence input,
- final ExtensionRegistry extensionRegistry,
- final Message.Builder builder)
- throws ParseException {
+ public static void merge(
+ final CharSequence input,
+ final ExtensionRegistry extensionRegistry,
+ final Message.Builder builder)
+ throws ParseException {
PARSER.merge(input, extensionRegistry, builder);
}
/**
- * Parse a text-format message from {@code input}. Extensions will be
- * recognized if they are registered in {@code extensionRegistry}.
+ * Parse a text-format message from {@code input}. Extensions will be recognized if they are
+ * registered in {@code extensionRegistry}.
*
* @return the parsed message, guaranteed initialized
*/
@@ -1275,8 +1177,7 @@ public final class TextFormat {
final ExtensionRegistry extensionRegistry,
final Class<T> protoClass)
throws ParseException {
- Message.Builder builder =
- Internal.getDefaultInstance(protoClass).newBuilderForType();
+ Message.Builder builder = Internal.getDefaultInstance(protoClass).newBuilderForType();
merge(input, extensionRegistry, builder);
@SuppressWarnings("unchecked")
T output = (T) builder.build();
@@ -1285,22 +1186,22 @@ public final class TextFormat {
/**
- * Parser for text-format proto2 instances. This class is thread-safe.
- * The implementation largely follows google/protobuf/text_format.cc.
+ * Parser for text-format proto2 instances. This class is thread-safe. The implementation largely
+ * follows google/protobuf/text_format.cc.
*
- * <p>Use {@link TextFormat#getParser()} to obtain the default parser, or
- * {@link Builder} to control the parser behavior.
+ * <p>Use {@link TextFormat#getParser()} to obtain the default parser, or {@link Builder} to
+ * control the parser behavior.
*/
public static class Parser {
/**
- * Determines if repeated values for non-repeated fields and
- * oneofs are permitted. For example, given required/optional field "foo"
- * and a oneof containing "baz" and "qux":
+ * Determines if repeated values for non-repeated fields and oneofs are permitted. For example,
+ * given required/optional field "foo" and a oneof containing "baz" and "qux":
+ *
* <ul>
- * <li>"foo: 1 foo: 2"
- * <li>"baz: 1 qux: 2"
- * <li>merging "foo: 2" into a proto in which foo is already set, or
- * <li>merging "qux: 2" into a proto in which baz is already set.
+ * <li>"foo: 1 foo: 2"
+ * <li>"baz: 1 qux: 2"
+ * <li>merging "foo: 2" into a proto in which foo is already set, or
+ * <li>merging "qux: 2" into a proto in which baz is already set.
* </ul>
*/
public enum SingularOverwritePolicy {
@@ -1326,16 +1227,12 @@ public final class TextFormat {
this.parseInfoTreeBuilder = parseInfoTreeBuilder;
}
- /**
- * Returns a new instance of {@link Builder}.
- */
+ /** Returns a new instance of {@link Builder}. */
public static Builder newBuilder() {
return new Builder();
}
- /**
- * Builder that can be used to obtain new instances of {@link Parser}.
- */
+ /** Builder that can be used to obtain new instances of {@link Parser}. */
public static class Builder {
private boolean allowUnknownFields = false;
private boolean allowUnknownEnumValues = false;
@@ -1344,16 +1241,13 @@ public final class TextFormat {
private TextFormatParseInfoTree.Builder parseInfoTreeBuilder = null;
- /**
- * Sets parser behavior when a non-repeated field appears more than once.
- */
+ /** Sets parser behavior when a non-repeated field appears more than once. */
public Builder setSingularOverwritePolicy(SingularOverwritePolicy p) {
this.singularOverwritePolicy = p;
return this;
}
- public Builder setParseInfoTreeBuilder(
- TextFormatParseInfoTree.Builder parseInfoTreeBuilder) {
+ public Builder setParseInfoTreeBuilder(TextFormatParseInfoTree.Builder parseInfoTreeBuilder) {
this.parseInfoTreeBuilder = parseInfoTreeBuilder;
return this;
}
@@ -1368,34 +1262,29 @@ public final class TextFormat {
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
*/
- public void merge(final Readable input,
- final Message.Builder builder)
- throws IOException {
+ public void merge(final Readable input, final Message.Builder builder) throws IOException {
merge(input, ExtensionRegistry.getEmptyRegistry(), builder);
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
*/
- public void merge(final CharSequence input,
- final Message.Builder builder)
- throws ParseException {
+ public void merge(final CharSequence input, final Message.Builder builder)
+ throws ParseException {
merge(input, ExtensionRegistry.getEmptyRegistry(), builder);
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}. Extensions will be recognized if they are
- * registered in {@code extensionRegistry}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
+ * Extensions will be recognized if they are registered in {@code extensionRegistry}.
*/
- public void merge(final Readable input,
- final ExtensionRegistry extensionRegistry,
- final Message.Builder builder)
- throws IOException {
+ public void merge(
+ final Readable input,
+ final ExtensionRegistry extensionRegistry,
+ final Message.Builder builder)
+ throws IOException {
// Read the entire input to a String then parse that.
// If StreamTokenizer were not quite so crippled, or if there were a kind
@@ -1412,8 +1301,7 @@ public final class TextFormat {
// TODO(chrisn): See if working around java.io.Reader#read(CharBuffer)
// overhead is worthwhile
- private static StringBuilder toStringBuilder(final Readable input)
- throws IOException {
+ private static StringBuilder toStringBuilder(final Readable input) throws IOException {
final StringBuilder text = new StringBuilder();
final CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE);
while (true) {
@@ -1429,8 +1317,7 @@ public final class TextFormat {
// Check both unknown fields and unknown extensions and log warning messages
// or throw exceptions according to the flag.
- private void checkUnknownFields(final List<String> unknownFields)
- throws ParseException {
+ private void checkUnknownFields(final List<String> unknownFields) throws ParseException {
if (unknownFields.isEmpty()) {
return;
}
@@ -1441,26 +1328,25 @@ public final class TextFormat {
}
if (allowUnknownFields) {
- logger.warning(msg.toString());
+ logger.warning(msg.toString());
} else {
String[] lineColumn = unknownFields.get(0).split(":");
- throw new ParseException(Integer.valueOf(lineColumn[0]),
- Integer.valueOf(lineColumn[1]), msg.toString());
+ throw new ParseException(
+ Integer.parseInt(lineColumn[0]), Integer.parseInt(lineColumn[1]), msg.toString());
}
}
/**
- * Parse a text-format message from {@code input} and merge the contents
- * into {@code builder}. Extensions will be recognized if they are
- * registered in {@code extensionRegistry}.
+ * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
+ * Extensions will be recognized if they are registered in {@code extensionRegistry}.
*/
- public void merge(final CharSequence input,
- final ExtensionRegistry extensionRegistry,
- final Message.Builder builder)
- throws ParseException {
+ public void merge(
+ final CharSequence input,
+ final ExtensionRegistry extensionRegistry,
+ final Message.Builder builder)
+ throws ParseException {
final Tokenizer tokenizer = new Tokenizer(input);
- MessageReflection.BuilderAdapter target =
- new MessageReflection.BuilderAdapter(builder);
+ MessageReflection.BuilderAdapter target = new MessageReflection.BuilderAdapter(builder);
List<String> unknownFields = new ArrayList<String>();
@@ -1472,29 +1358,24 @@ public final class TextFormat {
}
- /**
- * Parse a single field from {@code tokenizer} and merge it into
- * {@code builder}.
- */
- private void mergeField(final Tokenizer tokenizer,
- final ExtensionRegistry extensionRegistry,
- final MessageReflection.MergeTarget target,
- List<String> unknownFields)
- throws ParseException {
- mergeField(tokenizer, extensionRegistry, target, parseInfoTreeBuilder,
- unknownFields);
+ /** Parse a single field from {@code tokenizer} and merge it into {@code builder}. */
+ private void mergeField(
+ final Tokenizer tokenizer,
+ final ExtensionRegistry extensionRegistry,
+ final MessageReflection.MergeTarget target,
+ List<String> unknownFields)
+ throws ParseException {
+ mergeField(tokenizer, extensionRegistry, target, parseInfoTreeBuilder, unknownFields);
}
- /**
- * Parse a single field from {@code tokenizer} and merge it into
- * {@code target}.
- */
- private void mergeField(final Tokenizer tokenizer,
- final ExtensionRegistry extensionRegistry,
- final MessageReflection.MergeTarget target,
- TextFormatParseInfoTree.Builder parseTreeBuilder,
- List<String> unknownFields)
- throws ParseException {
+ /** Parse a single field from {@code tokenizer} and merge it into {@code target}. */
+ private void mergeField(
+ final Tokenizer tokenizer,
+ final ExtensionRegistry extensionRegistry,
+ final MessageReflection.MergeTarget target,
+ TextFormatParseInfoTree.Builder parseTreeBuilder,
+ List<String> unknownFields)
+ throws ParseException {
FieldDescriptor field = null;
int startLine = tokenizer.getLine();
int startColumn = tokenizer.getColumn();
@@ -1503,15 +1384,13 @@ public final class TextFormat {
if (tokenizer.tryConsume("[")) {
// An extension.
- final StringBuilder name =
- new StringBuilder(tokenizer.consumeIdentifier());
+ final StringBuilder name = new StringBuilder(tokenizer.consumeIdentifier());
while (tokenizer.tryConsume(".")) {
name.append('.');
name.append(tokenizer.consumeIdentifier());
}
- extension = target.findExtensionByName(
- extensionRegistry, name.toString());
+ extension = target.findExtensionByName(extensionRegistry, name.toString());
if (extension == null) {
unknownFields.add(
@@ -1526,8 +1405,11 @@ public final class TextFormat {
} else {
if (extension.descriptor.getContainingType() != type) {
throw tokenizer.parseExceptionPreviousToken(
- "Extension \"" + name + "\" does not extend message type \""
- + type.getFullName() + "\".");
+ "Extension \""
+ + name
+ + "\" does not extend message type \""
+ + type.getFullName()
+ + "\".");
}
field = extension.descriptor;
}
@@ -1551,7 +1433,8 @@ public final class TextFormat {
}
}
// Again, special-case group names as described above.
- if (field != null && field.getType() == FieldDescriptor.Type.GROUP
+ if (field != null
+ && field.getType() == FieldDescriptor.Type.GROUP
&& !field.getMessageType().getName().equals(name)) {
field = null;
}
@@ -1576,9 +1459,7 @@ public final class TextFormat {
// start with "{" or "<" which indicates the beginning of a message body.
// If there is no ":" or there is a "{" or "<" after ":", this field has
// to be a message or the input is ill-formed.
- if (tokenizer.tryConsume(":")
- && !tokenizer.lookingAt("{")
- && !tokenizer.lookingAt("<")) {
+ if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("{") && !tokenizer.lookingAt("<")) {
skipFieldValue(tokenizer);
} else {
skipFieldMessage(tokenizer);
@@ -1588,25 +1469,42 @@ public final class TextFormat {
// Handle potential ':'.
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
- tokenizer.tryConsume(":"); // optional
+ tokenizer.tryConsume(":"); // optional
if (parseTreeBuilder != null) {
TextFormatParseInfoTree.Builder childParseTreeBuilder =
parseTreeBuilder.getBuilderForSubMessageField(field);
- consumeFieldValues(tokenizer, extensionRegistry, target, field, extension,
- childParseTreeBuilder, unknownFields);
+ consumeFieldValues(
+ tokenizer,
+ extensionRegistry,
+ target,
+ field,
+ extension,
+ childParseTreeBuilder,
+ unknownFields);
} else {
- consumeFieldValues(tokenizer, extensionRegistry, target, field, extension,
- parseTreeBuilder, unknownFields);
+ consumeFieldValues(
+ tokenizer,
+ extensionRegistry,
+ target,
+ field,
+ extension,
+ parseTreeBuilder,
+ unknownFields);
}
} else {
- tokenizer.consume(":"); // required
- consumeFieldValues(tokenizer, extensionRegistry, target, field,
- extension, parseTreeBuilder, unknownFields);
+ tokenizer.consume(":"); // required
+ consumeFieldValues(
+ tokenizer,
+ extensionRegistry,
+ target,
+ field,
+ extension,
+ parseTreeBuilder,
+ unknownFields);
}
if (parseTreeBuilder != null) {
- parseTreeBuilder.setLocation(
- field, TextFormatParseLocation.create(startLine, startColumn));
+ parseTreeBuilder.setLocation(field, TextFormatParseLocation.create(startLine, startColumn));
}
// For historical reasons, fields may optionally be separated by commas or
@@ -1617,8 +1515,7 @@ public final class TextFormat {
}
/**
- * Parse a one or more field values from {@code tokenizer} and merge it into
- * {@code builder}.
+ * Parse a one or more field values from {@code tokenizer} and merge it into {@code builder}.
*/
private void consumeFieldValues(
final Tokenizer tokenizer,
@@ -1632,7 +1529,7 @@ public final class TextFormat {
// Support specifying repeated field values as a comma-separated list.
// Ex."foo: [1, 2, 3]"
if (field.isRepeated() && tokenizer.tryConsume("[")) {
- if (!tokenizer.tryConsume("]")) { // Allow "foo: []" to be treated as empty.
+ if (!tokenizer.tryConsume("]")) { // Allow "foo: []" to be treated as empty.
while (true) {
consumeFieldValue(
tokenizer,
@@ -1650,15 +1547,18 @@ public final class TextFormat {
}
}
} else {
- consumeFieldValue(tokenizer, extensionRegistry, target, field,
- extension, parseTreeBuilder, unknownFields);
+ consumeFieldValue(
+ tokenizer,
+ extensionRegistry,
+ target,
+ field,
+ extension,
+ parseTreeBuilder,
+ unknownFields);
}
}
- /**
- * Parse a single field value from {@code tokenizer} and merge it into
- * {@code builder}.
- */
+ /** Parse a single field value from {@code tokenizer} and merge it into {@code builder}. */
private void consumeFieldValue(
final Tokenizer tokenizer,
final ExtensionRegistry extensionRegistry,
@@ -1680,16 +1580,15 @@ public final class TextFormat {
}
final MessageReflection.MergeTarget subField;
- subField = target.newMergeTargetForField(field,
- (extension == null) ? null : extension.defaultInstance);
+ subField =
+ target.newMergeTargetForField(
+ field, (extension == null) ? null : extension.defaultInstance);
while (!tokenizer.tryConsume(endToken)) {
if (tokenizer.atEnd()) {
- throw tokenizer.parseException(
- "Expected \"" + endToken + "\".");
+ throw tokenizer.parseException("Expected \"" + endToken + "\".");
}
- mergeField(tokenizer, extensionRegistry, subField, parseTreeBuilder,
- unknownFields);
+ mergeField(tokenizer, extensionRegistry, subField, parseTreeBuilder, unknownFields);
}
value = subField.finish();
@@ -1794,28 +1693,28 @@ public final class TextFormat {
// 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)
+ } else if ((singularOverwritePolicy == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
&& target.hasField(field)) {
- throw tokenizer.parseExceptionPreviousToken("Non-repeated field \""
- + field.getFullName() + "\" cannot be overwritten.");
- } else if ((singularOverwritePolicy
- == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
+ throw tokenizer.parseExceptionPreviousToken(
+ "Non-repeated field \"" + field.getFullName() + "\" cannot be overwritten.");
+ } else if ((singularOverwritePolicy == SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
&& field.getContainingOneof() != null
&& target.hasOneof(field.getContainingOneof())) {
Descriptors.OneofDescriptor oneof = field.getContainingOneof();
- throw tokenizer.parseExceptionPreviousToken("Field \""
- + field.getFullName() + "\" is specified along with field \""
- + target.getOneofFieldDescriptor(oneof).getFullName()
- + "\", another member of oneof \"" + oneof.getName() + "\".");
+ throw tokenizer.parseExceptionPreviousToken(
+ "Field \""
+ + field.getFullName()
+ + "\" is specified along with field \""
+ + target.getOneofFieldDescriptor(oneof).getFullName()
+ + "\", another member of oneof \""
+ + oneof.getName()
+ + "\".");
} else {
target.setField(field, value);
}
}
- /**
- * Skips the next field including the field's name and value.
- */
+ /** Skips the next field including the field's name and value. */
private void skipField(Tokenizer tokenizer) throws ParseException {
if (tokenizer.tryConsume("[")) {
// Extension name.
@@ -1833,9 +1732,7 @@ public final class TextFormat {
// start with "{" or "<" which indicates the beginning of a message body.
// If there is no ":" or there is a "{" or "<" after ":", this field has
// to be a message or the input is ill-formed.
- if (tokenizer.tryConsume(":")
- && !tokenizer.lookingAt("<")
- && !tokenizer.lookingAt("{")) {
+ if (tokenizer.tryConsume(":") && !tokenizer.lookingAt("<") && !tokenizer.lookingAt("{")) {
skipFieldValue(tokenizer);
} else {
skipFieldMessage(tokenizer);
@@ -1848,8 +1745,7 @@ public final class TextFormat {
}
/**
- * Skips the whole body of a message including the beginning delimiter and
- * the ending delimiter.
+ * Skips the whole body of a message including the beginning delimiter and the ending delimiter.
*/
private void skipFieldMessage(Tokenizer tokenizer) throws ParseException {
final String delimiter;
@@ -1865,21 +1761,18 @@ public final class TextFormat {
tokenizer.consume(delimiter);
}
- /**
- * Skips a field value.
- */
+ /** Skips a field value. */
private void skipFieldValue(Tokenizer tokenizer) throws ParseException {
if (tokenizer.tryConsumeString()) {
while (tokenizer.tryConsumeString()) {}
return;
}
- if (!tokenizer.tryConsumeIdentifier() // includes enum & boolean
- && !tokenizer.tryConsumeInt64() // includes int32
- && !tokenizer.tryConsumeUInt64() // includes uint32
+ if (!tokenizer.tryConsumeIdentifier() // includes enum & boolean
+ && !tokenizer.tryConsumeInt64() // includes int32
+ && !tokenizer.tryConsumeUInt64() // includes uint32
&& !tokenizer.tryConsumeDouble()
&& !tokenizer.tryConsumeFloat()) {
- throw tokenizer.parseException(
- "Invalid field value: " + tokenizer.currentToken);
+ throw tokenizer.parseException("Invalid field value: " + tokenizer.currentToken);
}
}
}
@@ -1891,28 +1784,23 @@ public final class TextFormat {
// them.
/**
- * Escapes bytes in the format used in protocol buffer text format, which
- * is the same as the format used for C string literals. All bytes
- * that are not printable 7-bit ASCII characters are escaped, as well as
- * backslash, single-quote, and double-quote characters. Characters for
- * which no defined short-hand escape sequence is defined will be escaped
- * using 3-digit octal sequences.
+ * Escapes bytes in the format used in protocol buffer text format, which is the same as the
+ * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are
+ * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which
+ * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences.
*/
public static String escapeBytes(ByteString input) {
return TextFormatEscaper.escapeBytes(input);
}
- /**
- * Like {@link #escapeBytes(ByteString)}, but used for byte array.
- */
+ /** Like {@link #escapeBytes(ByteString)}, but used for byte array. */
public static String escapeBytes(byte[] input) {
return TextFormatEscaper.escapeBytes(input);
}
/**
- * Un-escape a byte sequence as escaped using
- * {@link #escapeBytes(ByteString)}. Two-digit hex escapes (starting with
- * "\x") are also recognized.
+ * Un-escape a byte sequence as escaped using {@link #escapeBytes(ByteString)}. Two-digit hex
+ * escapes (starting with "\x") are also recognized.
*/
public static ByteString unescapeBytes(final CharSequence charString)
throws InvalidEscapeSequenceException {
@@ -1948,16 +1836,36 @@ public final class TextFormat {
result[pos++] = (byte) code;
} else {
switch (c) {
- case 'a' : result[pos++] = 0x07; break;
- case 'b' : result[pos++] = '\b'; break;
- case 'f' : result[pos++] = '\f'; break;
- case 'n' : result[pos++] = '\n'; break;
- case 'r' : result[pos++] = '\r'; break;
- case 't' : result[pos++] = '\t'; break;
- case 'v' : result[pos++] = 0x0b; break;
- case '\\': result[pos++] = '\\'; break;
- case '\'': result[pos++] = '\''; break;
- case '"' : result[pos++] = '\"'; break;
+ case 'a':
+ result[pos++] = 0x07;
+ break;
+ case 'b':
+ result[pos++] = '\b';
+ break;
+ case 'f':
+ result[pos++] = '\f';
+ break;
+ case 'n':
+ result[pos++] = '\n';
+ break;
+ case 'r':
+ result[pos++] = '\r';
+ break;
+ case 't':
+ result[pos++] = '\t';
+ break;
+ case 'v':
+ result[pos++] = 0x0b;
+ break;
+ case '\\':
+ result[pos++] = '\\';
+ break;
+ case '\'':
+ result[pos++] = '\'';
+ break;
+ case '"':
+ result[pos++] = '\"';
+ break;
case 'x':
// hex escape
@@ -1991,13 +1899,13 @@ public final class TextFormat {
}
return result.length == pos
- ? ByteString.wrap(result) // This reference has not been out of our control.
+ ? ByteString.wrap(result) // This reference has not been out of our control.
: ByteString.copyFrom(result, 0, pos);
}
/**
- * Thrown by {@link TextFormat#unescapeBytes} and
- * {@link TextFormat#unescapeText} when an invalid escape sequence is seen.
+ * Thrown by {@link TextFormat#unescapeBytes} and {@link TextFormat#unescapeText} when an invalid
+ * escape sequence is seen.
*/
public static class InvalidEscapeSequenceException extends IOException {
private static final long serialVersionUID = -8164033650142593304L;
@@ -2008,27 +1916,24 @@ public final class TextFormat {
}
/**
- * Like {@link #escapeBytes(ByteString)}, but escapes a text string.
- * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped
- * individually as a 3-digit octal escape. Yes, it's weird.
+ * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are
+ * first encoded as UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes,
+ * it's weird.
*/
static String escapeText(final String input) {
return escapeBytes(ByteString.copyFromUtf8(input));
}
- /**
- * Escape double quotes and backslashes in a String for unicode output of a message.
- */
+ /** Escape double quotes and backslashes in a String for unicode output of a message. */
public static String escapeDoubleQuotesAndBackslashes(final String input) {
return TextFormatEscaper.escapeDoubleQuotesAndBackslashes(input);
}
/**
- * Un-escape a text string as escaped using {@link #escapeText(String)}.
- * Two-digit hex escapes (starting with "\x") are also recognized.
+ * Un-escape a text string as escaped using {@link #escapeText(String)}. Two-digit hex escapes
+ * (starting with "\x") are also recognized.
*/
- static String unescapeText(final String input)
- throws InvalidEscapeSequenceException {
+ static String unescapeText(final String input) throws InvalidEscapeSequenceException {
return unescapeBytes(input).toStringUtf8();
}
@@ -2039,15 +1944,12 @@ public final class TextFormat {
/** Is this a hex digit? */
private static boolean isHex(final byte c) {
- return ('0' <= c && c <= '9')
- || ('a' <= c && c <= 'f')
- || ('A' <= c && c <= 'F');
+ return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F');
}
/**
- * Interpret a character as a digit (in any base up to 36) and return the
- * numeric value. This is like {@code Character.digit()} but we don't accept
- * non-ASCII digits.
+ * Interpret a character as a digit (in any base up to 36) and return the numeric value. This is
+ * like {@code Character.digit()} but we don't accept non-ASCII digits.
*/
private static int digitValue(final byte c) {
if ('0' <= c && c <= '9') {
@@ -2060,49 +1962,45 @@ public final class TextFormat {
}
/**
- * Parse a 32-bit signed integer from the text. Unlike the Java standard
- * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
- * and "0" to signify hexadecimal and octal numbers, respectively.
+ * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code
+ * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal
+ * and octal numbers, respectively.
*/
static int parseInt32(final String text) throws NumberFormatException {
return (int) parseInteger(text, true, false);
}
/**
- * Parse a 32-bit unsigned integer from the text. Unlike the Java standard
- * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
- * and "0" to signify hexadecimal and octal numbers, respectively. The
- * result is coerced to a (signed) {@code int} when returned since Java has
- * no unsigned integer type.
+ * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code
+ * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal
+ * and octal numbers, respectively. The result is coerced to a (signed) {@code int} when returned
+ * since Java has no unsigned integer type.
*/
static int parseUInt32(final String text) throws NumberFormatException {
return (int) parseInteger(text, false, false);
}
/**
- * Parse a 64-bit signed integer from the text. Unlike the Java standard
- * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
- * and "0" to signify hexadecimal and octal numbers, respectively.
+ * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code
+ * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal
+ * and octal numbers, respectively.
*/
static long parseInt64(final String text) throws NumberFormatException {
return parseInteger(text, true, true);
}
/**
- * Parse a 64-bit unsigned integer from the text. Unlike the Java standard
- * {@code Integer.parseInt()}, this function recognizes the prefixes "0x"
- * and "0" to signify hexadecimal and octal numbers, respectively. The
- * result is coerced to a (signed) {@code long} when returned since Java has
- * no unsigned long type.
+ * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code
+ * Integer.parseInt()}, this function recognizes the prefixes "0x" and "0" to signify hexadecimal
+ * and octal numbers, respectively. The result is coerced to a (signed) {@code long} when returned
+ * since Java has no unsigned long type.
*/
static long parseUInt64(final String text) throws NumberFormatException {
return parseInteger(text, false, true);
}
- private static long parseInteger(final String text,
- final boolean isSigned,
- final boolean isLong)
- throws NumberFormatException {
+ private static long parseInteger(final String text, final boolean isSigned, final boolean isLong)
+ throws NumberFormatException {
int pos = 0;
boolean negative = false;
@@ -2139,12 +2037,12 @@ public final class TextFormat {
if (isSigned) {
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
throw new NumberFormatException(
- "Number out of range for 32-bit signed integer: " + text);
+ "Number out of range for 32-bit signed integer: " + text);
}
} else {
if (result >= (1L << 32) || result < 0) {
throw new NumberFormatException(
- "Number out of range for 32-bit unsigned integer: " + text);
+ "Number out of range for 32-bit unsigned integer: " + text);
}
}
}
@@ -2159,24 +2057,24 @@ public final class TextFormat {
if (isSigned) {
if (bigValue.bitLength() > 31) {
throw new NumberFormatException(
- "Number out of range for 32-bit signed integer: " + text);
+ "Number out of range for 32-bit signed integer: " + text);
}
} else {
if (bigValue.bitLength() > 32) {
throw new NumberFormatException(
- "Number out of range for 32-bit unsigned integer: " + text);
+ "Number out of range for 32-bit unsigned integer: " + text);
}
}
} else {
if (isSigned) {
if (bigValue.bitLength() > 63) {
throw new NumberFormatException(
- "Number out of range for 64-bit signed integer: " + text);
+ "Number out of range for 64-bit signed integer: " + text);
}
} else {
if (bigValue.bitLength() > 64) {
throw new NumberFormatException(
- "Number out of range for 64-bit unsigned integer: " + text);
+ "Number out of range for 64-bit unsigned integer: " + text);
}
}
}
diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java b/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java
index da9ceadd..2501ec93 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java
@@ -30,41 +30,58 @@
package com.google.protobuf;
-/**
- * Provide text format escaping support for proto2 instances.
- */
+/** Provide text format escaping support for proto2 instances. */
final class TextFormatEscaper {
private TextFormatEscaper() {}
private interface ByteSequence {
int size();
+
byte byteAt(int offset);
}
/**
- * Escapes bytes in the format used in protocol buffer text format, which
- * is the same as the format used for C string literals. All bytes
- * that are not printable 7-bit ASCII characters are escaped, as well as
- * backslash, single-quote, and double-quote characters. Characters for
- * which no defined short-hand escape sequence is defined will be escaped
- * using 3-digit octal sequences.
+ * Escapes bytes in the format used in protocol buffer text format, which is the same as the
+ * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are
+ * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which
+ * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences.
*/
static String escapeBytes(final ByteSequence input) {
final StringBuilder builder = new StringBuilder(input.size());
for (int i = 0; i < input.size(); i++) {
final byte b = input.byteAt(i);
switch (b) {
- // Java does not recognize \a or \v, apparently.
- case 0x07: builder.append("\\a"); break;
- case '\b': builder.append("\\b"); break;
- case '\f': builder.append("\\f"); break;
- case '\n': builder.append("\\n"); break;
- case '\r': builder.append("\\r"); break;
- case '\t': builder.append("\\t"); break;
- case 0x0b: builder.append("\\v"); break;
- case '\\': builder.append("\\\\"); break;
- case '\'': builder.append("\\\'"); break;
- case '"' : builder.append("\\\""); break;
+ // Java does not recognize \a or \v, apparently.
+ case 0x07:
+ builder.append("\\a");
+ break;
+ case '\b':
+ builder.append("\\b");
+ break;
+ case '\f':
+ builder.append("\\f");
+ break;
+ case '\n':
+ builder.append("\\n");
+ break;
+ case '\r':
+ builder.append("\\r");
+ break;
+ case '\t':
+ builder.append("\\t");
+ break;
+ case 0x0b:
+ builder.append("\\v");
+ break;
+ case '\\':
+ builder.append("\\\\");
+ break;
+ case '\'':
+ builder.append("\\\'");
+ break;
+ case '"':
+ builder.append("\\\"");
+ break;
default:
// Only ASCII characters between 0x20 (space) and 0x7e (tilde) are
// printable. Other byte values must be escaped.
@@ -83,54 +100,52 @@ final class TextFormatEscaper {
}
/**
- * Escapes bytes in the format used in protocol buffer text format, which
- * is the same as the format used for C string literals. All bytes
- * that are not printable 7-bit ASCII characters are escaped, as well as
- * backslash, single-quote, and double-quote characters. Characters for
- * which no defined short-hand escape sequence is defined will be escaped
- * using 3-digit octal sequences.
+ * Escapes bytes in the format used in protocol buffer text format, which is the same as the
+ * format used for C string literals. All bytes that are not printable 7-bit ASCII characters are
+ * escaped, as well as backslash, single-quote, and double-quote characters. Characters for which
+ * no defined short-hand escape sequence is defined will be escaped using 3-digit octal sequences.
*/
static String escapeBytes(final ByteString input) {
- return escapeBytes(new ByteSequence() {
- @Override
- public int size() {
- return input.size();
- }
- @Override
- public byte byteAt(int offset) {
- return input.byteAt(offset);
- }
- });
+ return escapeBytes(
+ new ByteSequence() {
+ @Override
+ public int size() {
+ return input.size();
+ }
+
+ @Override
+ public byte byteAt(int offset) {
+ return input.byteAt(offset);
+ }
+ });
}
- /**
- * Like {@link #escapeBytes(ByteString)}, but used for byte array.
- */
+ /** Like {@link #escapeBytes(ByteString)}, but used for byte array. */
static String escapeBytes(final byte[] input) {
- return escapeBytes(new ByteSequence() {
- @Override
- public int size() {
- return input.length;
- }
- @Override
- public byte byteAt(int offset) {
- return input[offset];
- }
- });
+ return escapeBytes(
+ new ByteSequence() {
+ @Override
+ public int size() {
+ return input.length;
+ }
+
+ @Override
+ public byte byteAt(int offset) {
+ return input[offset];
+ }
+ });
}
/**
- * Like {@link #escapeBytes(ByteString)}, but escapes a text string.
- * Non-ASCII characters are first encoded as UTF-8, then each byte is escaped
- * individually as a 3-digit octal escape. Yes, it's weird.
+ * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are
+ * first encoded as UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes,
+ * it's weird.
*/
static String escapeText(final String input) {
return escapeBytes(ByteString.copyFromUtf8(input));
}
- /**
- * Escape double quotes and backslashes in a String for unicode output of a message.
- */
+ /** Escape double quotes and backslashes in a String for unicode output of a message. */
static String escapeDoubleQuotesAndBackslashes(final String input) {
return input.replace("\\", "\\\\").replace("\"", "\\\"");
}
diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
index 0127ce92..6ce9f783 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
@@ -31,7 +31,6 @@
package com.google.protobuf;
import com.google.protobuf.Descriptors.FieldDescriptor;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -39,14 +38,12 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
/**
* Data structure which is populated with the locations of each field value parsed from the text.
*
- * <p>The locations of primary fields values are retrieved by {@code getLocation} or
- * {@code getLocations}. The locations of sub message values are within nested
- * {@code TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or
- * {@code getNestedTrees}.
+ * <p>The locations of primary fields values are retrieved by {@code getLocation} or {@code
+ * getLocations}. The locations of sub message values are within nested {@code
+ * TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or {@code getNestedTrees}.
*
* <p>The {@code TextFormatParseInfoTree} is created by a Builder.
*/
@@ -90,13 +87,13 @@ public class TextFormatParseInfoTree {
this.subtreesFromField = Collections.unmodifiableMap(subs);
}
- /**
- * Retrieve all the locations of a field.
- *
- * @param fieldDescriptor the the @{link FieldDescriptor} of the desired field
- * @return a list of the locations of values of the field. If there are not values
- * or the field doesn't exist, an empty list is returned.
- */
+ /**
+ * Retrieve all the locations of a field.
+ *
+ * @param fieldDescriptor the @{link FieldDescriptor} of the desired field
+ * @return a list of the locations of values of the field. If there are not values or the field
+ * doesn't exist, an empty list is returned.
+ */
public List<TextFormatParseLocation> getLocations(final FieldDescriptor fieldDescriptor) {
List<TextFormatParseLocation> result = locationsFromField.get(fieldDescriptor);
return (result == null) ? Collections.<TextFormatParseLocation>emptyList() : result;
@@ -134,7 +131,7 @@ public class TextFormatParseInfoTree {
* @param fieldDescriptor the @{link FieldDescriptor} of the desired sub message
* @param index the index of message value.
* @return the {@code ParseInfoTree} of the message value. {@code null} is returned if the field
- * doesn't exist or the index is out of range.
+ * doesn't exist or the index is out of range.
* @throws IllegalArgumentException if index is out of range
*/
public TextFormatParseInfoTree getNestedTree(final FieldDescriptor fieldDescriptor, int index) {
@@ -151,16 +148,16 @@ public class TextFormatParseInfoTree {
}
private static <T> T getFromList(List<T> list, int index, FieldDescriptor fieldDescriptor) {
- if (index >= list.size() || index < 0) {
- throw new IllegalArgumentException(String.format("Illegal index field: %s, index %d",
- fieldDescriptor == null ? "<null>" : fieldDescriptor.getName(), index));
+ if (index >= list.size() || index < 0) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Illegal index field: %s, index %d",
+ fieldDescriptor == null ? "<null>" : fieldDescriptor.getName(), index));
}
return list.get(index);
}
- /**
- * Builder for a {@link TextFormatParseInfoTree}.
- */
+ /** Builder for a {@link TextFormatParseInfoTree}. */
public static class Builder {
private Map<FieldDescriptor, List<TextFormatParseLocation>> locationsFromField;
@@ -169,9 +166,7 @@ public class TextFormatParseInfoTree {
// sub message location information.
private Map<FieldDescriptor, List<Builder>> subtreeBuildersFromField;
- /**
- * Create a root level {@ParseInfoTree} builder.
- */
+ /** Create a root level {@ParseInfoTree} builder. */
private Builder() {
locationsFromField = new HashMap<FieldDescriptor, List<TextFormatParseLocation>>();
subtreeBuildersFromField = new HashMap<FieldDescriptor, List<Builder>>();
diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java b/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java
index cce286e1..eebfb1b5 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormatParseLocation.java
@@ -39,9 +39,7 @@ import java.util.Arrays;
*/
public final class TextFormatParseLocation {
- /**
- * The empty location.
- */
+ /** The empty location. */
public static final TextFormatParseLocation EMPTY = new TextFormatParseLocation(-1, -1);
/**
@@ -92,8 +90,7 @@ public final class TextFormatParseLocation {
return false;
}
TextFormatParseLocation that = (TextFormatParseLocation) o;
- return (this.line == that.getLine())
- && (this.column == that.getColumn());
+ return (this.line == that.getLine()) && (this.column == that.getColumn());
}
@Override
diff --git a/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java b/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java
index 5714c063..c633a4e8 100644
--- a/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java
+++ b/java/core/src/main/java/com/google/protobuf/UninitializedMessageException.java
@@ -34,15 +34,13 @@ import java.util.Collections;
import java.util.List;
/**
- * Thrown when attempting to build a protocol message that is missing required
- * fields. This is a {@code RuntimeException} because it normally represents
- * a programming error: it happens when some code which constructs a message
- * fails to set all the fields. {@code parseFrom()} methods <b>do not</b>
- * throw this; they throw an {@link InvalidProtocolBufferException} if
- * required fields are missing, because it is not a programming error to
- * receive an incomplete message. In other words,
- * {@code UninitializedMessageException} should never be thrown by correct
- * code, but {@code InvalidProtocolBufferException} might be.
+ * Thrown when attempting to build a protocol message that is missing required fields. This is a
+ * {@code RuntimeException} because it normally represents a programming error: it happens when some
+ * code which constructs a message fails to set all the fields. {@code parseFrom()} methods <b>do
+ * not</b> throw this; they throw an {@link InvalidProtocolBufferException} if required fields are
+ * missing, because it is not a programming error to receive an incomplete message. In other words,
+ * {@code UninitializedMessageException} should never be thrown by correct code, but {@code
+ * InvalidProtocolBufferException} might be.
*
* @author kenton@google.com Kenton Varda
*/
@@ -50,8 +48,9 @@ public class UninitializedMessageException extends RuntimeException {
private static final long serialVersionUID = -7466929953374883507L;
public UninitializedMessageException(final MessageLite message) {
- super("Message was missing required fields. (Lite runtime could not " +
- "determine which fields were missing).");
+ super(
+ "Message was missing required fields. (Lite runtime could not "
+ + "determine which fields were missing).");
missingFields = null;
}
@@ -63,19 +62,18 @@ public class UninitializedMessageException extends RuntimeException {
private final List<String> missingFields;
/**
- * Get a list of human-readable names of required fields missing from this
- * message. Each name is a full path to a field, e.g. "foo.bar[5].baz".
- * Returns null if the lite runtime was used, since it lacks the ability to
- * find missing fields.
+ * Get a list of human-readable names of required fields missing from this message. Each name is a
+ * full path to a field, e.g. "foo.bar[5].baz". Returns null if the lite runtime was used, since
+ * it lacks the ability to find missing fields.
*/
public List<String> getMissingFields() {
return Collections.unmodifiableList(missingFields);
}
/**
- * Converts this exception to an {@link InvalidProtocolBufferException}.
- * When a parsed message is missing required fields, this should be thrown
- * instead of {@code UninitializedMessageException}.
+ * Converts this exception to an {@link InvalidProtocolBufferException}. When a parsed message is
+ * missing required fields, this should be thrown instead of {@code
+ * UninitializedMessageException}.
*/
public InvalidProtocolBufferException asInvalidProtocolBufferException() {
return new InvalidProtocolBufferException(getMessage());
@@ -83,8 +81,7 @@ public class UninitializedMessageException extends RuntimeException {
/** Construct the description string for this exception. */
private static String buildDescription(final List<String> missingFields) {
- final StringBuilder description =
- new StringBuilder("Message missing required fields: ");
+ final StringBuilder description = new StringBuilder("Message missing required fields: ");
boolean first = true;
for (final String field : missingFields) {
if (first) {
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 37d64633..39deec04 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
@@ -43,14 +43,13 @@ import java.util.Map;
import java.util.TreeMap;
/**
- * {@code UnknownFieldSet} is used to keep track of fields which were seen when
- * parsing a protocol message but whose field numbers or types are unrecognized.
- * This most frequently occurs when new fields are added to a message type
- * and then messages containing those fields are read by old software that was
- * compiled before the new types were added.
+ * {@code UnknownFieldSet} is used to keep track of fields which were seen when parsing a protocol
+ * message but whose field numbers or types are unrecognized. This most frequently occurs when new
+ * fields are added to a message type and then messages containing those fields are read by old
+ * software that was compiled before the new types were added.
*
- * <p>Every {@link Message} contains an {@code UnknownFieldSet} (and every
- * {@link Message.Builder} contains an {@link Builder}).
+ * <p>Every {@link Message} contains an {@code UnknownFieldSet} (and every {@link Message.Builder}
+ * contains an {@link Builder}).
*
* <p>Most users will never need to use this class.
*
@@ -67,10 +66,7 @@ public final class UnknownFieldSet implements MessageLite {
return Builder.create();
}
- /**
- * Create a new {@link Builder} and initialize it to be a copy
- * of {@code copyFrom}.
- */
+ /** Create a new {@link Builder} and initialize it to be a copy of {@code copyFrom}. */
public static Builder newBuilder(final UnknownFieldSet copyFrom) {
return newBuilder().mergeFrom(copyFrom);
}
@@ -79,22 +75,23 @@ public final class UnknownFieldSet implements MessageLite {
public static UnknownFieldSet getDefaultInstance() {
return defaultInstance;
}
+
@Override
public UnknownFieldSet getDefaultInstanceForType() {
return defaultInstance;
}
+
private static final UnknownFieldSet defaultInstance =
- new UnknownFieldSet(Collections.<Integer, Field>emptyMap(),
- 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.
+ * Construct an {@code UnknownFieldSet} around the given map. The map is expected to be immutable.
*/
- UnknownFieldSet(final Map<Integer, Field> fields,
- final Map<Integer, Field> fieldsDescending) {
+ UnknownFieldSet(final Map<Integer, Field> fields, final Map<Integer, Field> fieldsDescending) {
this.fields = fields;
}
+
private final Map<Integer, Field> fields;
@@ -103,8 +100,7 @@ public final class UnknownFieldSet implements MessageLite {
if (this == other) {
return true;
}
- return (other instanceof UnknownFieldSet) &&
- fields.equals(((UnknownFieldSet) other).fields);
+ return (other instanceof UnknownFieldSet) && fields.equals(((UnknownFieldSet) other).fields);
}
@Override
@@ -122,10 +118,7 @@ public final class UnknownFieldSet implements MessageLite {
return fields.containsKey(number);
}
- /**
- * Get a field by number. Returns an empty field if not present. Never
- * returns {@code null}.
- */
+ /** Get a field by number. Returns an empty field if not present. Never returns {@code null}. */
public Field getField(final int number) {
final Field result = fields.get(number);
return (result == null) ? Field.getDefaultInstance() : result;
@@ -141,9 +134,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Converts the set to a string in protocol buffer text format. This is
- * just a trivial wrapper around
- * {@link TextFormat#printToString(UnknownFieldSet)}.
+ * Converts the set to a string in protocol buffer text format. This is just a trivial wrapper
+ * around {@link TextFormat#printToString(UnknownFieldSet)}.
*/
@Override
public String toString() {
@@ -151,26 +143,24 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Serializes the message to a {@code ByteString} and returns it. This is
- * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}.
+ * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper
+ * around {@link #writeTo(CodedOutputStream)}.
*/
@Override
public ByteString toByteString() {
try {
- final ByteString.CodedBuilder out =
- ByteString.newCodedBuilder(getSerializedSize());
+ final ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize());
writeTo(out.getCodedOutput());
return out.build();
} catch (final IOException e) {
throw new RuntimeException(
- "Serializing to a ByteString threw an IOException (should " +
- "never happen).", e);
+ "Serializing to a ByteString threw an IOException (should never happen).", e);
}
}
/**
- * Serializes the message to a {@code byte} array and returns it. This is
- * just a trivial wrapper around {@link #writeTo(CodedOutputStream)}.
+ * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper
+ * around {@link #writeTo(CodedOutputStream)}.
*/
@Override
public byte[] toByteArray() {
@@ -182,14 +172,13 @@ public final class UnknownFieldSet implements MessageLite {
return result;
} catch (final IOException e) {
throw new RuntimeException(
- "Serializing to a byte array threw an IOException " +
- "(should never happen).", e);
+ "Serializing to a byte array threw an IOException (should never happen).", e);
}
}
/**
- * Serializes the message and writes it to {@code output}. This is just a
- * trivial wrapper around {@link #writeTo(CodedOutputStream)}.
+ * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around
+ * {@link #writeTo(CodedOutputStream)}.
*/
@Override
public void writeTo(final OutputStream output) throws IOException {
@@ -216,15 +205,10 @@ public final class UnknownFieldSet implements MessageLite {
return result;
}
- /**
- * Serializes the set and writes it to {@code output} using
- * {@code MessageSet} wire format.
- */
- public void writeAsMessageSetTo(final CodedOutputStream output)
- throws IOException {
+ /** Serializes the set and writes it to {@code output} using {@code MessageSet} wire format. */
+ public void writeAsMessageSetTo(final CodedOutputStream output) throws IOException {
for (final Map.Entry<Integer, Field> entry : fields.entrySet()) {
- entry.getValue().writeAsMessageSetExtensionTo(
- entry.getKey(), output);
+ entry.getValue().writeAsMessageSetExtensionTo(entry.getKey(), output);
}
}
@@ -233,8 +217,7 @@ public final class UnknownFieldSet implements MessageLite {
public int getSerializedSizeAsMessageSet() {
int result = 0;
for (final Map.Entry<Integer, Field> entry : fields.entrySet()) {
- result += entry.getValue().getSerializedSizeAsMessageSetExtension(
- entry.getKey());
+ result += entry.getValue().getSerializedSizeAsMessageSetExtension(entry.getKey());
}
return result;
}
@@ -247,8 +230,7 @@ public final class UnknownFieldSet implements MessageLite {
}
/** Parse an {@code UnknownFieldSet} from the given input stream. */
- public static UnknownFieldSet parseFrom(final CodedInputStream input)
- throws IOException {
+ public static UnknownFieldSet parseFrom(final CodedInputStream input) throws IOException {
return newBuilder().mergeFrom(input).build();
}
@@ -259,14 +241,12 @@ public final class UnknownFieldSet implements MessageLite {
}
/** Parse {@code data} as an {@code UnknownFieldSet} and return it. */
- public static UnknownFieldSet parseFrom(final byte[] data)
- throws InvalidProtocolBufferException {
+ public static UnknownFieldSet parseFrom(final byte[] data) throws InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).build();
}
/** Parse an {@code UnknownFieldSet} from {@code input} and return it. */
- public static UnknownFieldSet parseFrom(final InputStream input)
- throws IOException {
+ public static UnknownFieldSet parseFrom(final InputStream input) throws IOException {
return newBuilder().mergeFrom(input).build();
}
@@ -283,12 +263,11 @@ public final class UnknownFieldSet implements MessageLite {
/**
* Builder for {@link UnknownFieldSet}s.
*
- * <p>Note that this class maintains {@link Field.Builder}s for all fields
- * in the set. Thus, adding one element to an existing {@link Field} does not
- * require making a copy. This is important for efficient parsing of
- * unknown repeated fields. However, it implies that {@link Field}s cannot
- * be constructed independently, nor can two {@link UnknownFieldSet}s share
- * the same {@code Field} object.
+ * <p>Note that this class maintains {@link Field.Builder}s for all fields in the set. Thus,
+ * adding one element to an existing {@link Field} does not require making a copy. This is
+ * important for efficient parsing of unknown repeated fields. However, it implies that {@link
+ * Field}s cannot be constructed independently, nor can two {@link UnknownFieldSet}s share the
+ * same {@code Field} object.
*
* <p>Use {@link UnknownFieldSet#newBuilder()} to construct a {@code Builder}.
*/
@@ -311,8 +290,7 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Get a field builder for the given field number which includes any
- * values that already exist.
+ * Get a field builder for the given field number which includes any values that already exist.
*/
private Field.Builder getFieldBuilder(final int number) {
if (lastField != null) {
@@ -338,10 +316,9 @@ public final class UnknownFieldSet implements MessageLite {
/**
* Build the {@link UnknownFieldSet} and return it.
*
- * <p>Once {@code build()} has been called, the {@code Builder} will no
- * longer be usable. Calling any method after {@code build()} will result
- * in undefined behavior and can cause a {@code NullPointerException} to be
- * thrown.
+ * <p>Once {@code build()} has been called, the {@code Builder} will no longer be usable.
+ * Calling any method after {@code build()} will result in undefined behavior and can cause a
+ * {@code NullPointerException} to be thrown.
*/
@Override
public UnknownFieldSet build() {
@@ -365,10 +342,9 @@ public final class UnknownFieldSet implements MessageLite {
@Override
public Builder clone() {
- getFieldBuilder(0); // Force lastField to be built.
+ getFieldBuilder(0); // Force lastField to be built.
Map<Integer, Field> descendingFields = null;
- return UnknownFieldSet.newBuilder().mergeFrom(
- new UnknownFieldSet(fields, descendingFields));
+ return UnknownFieldSet.newBuilder().mergeFrom(new UnknownFieldSet(fields, descendingFields));
}
@Override
@@ -388,7 +364,7 @@ public final class UnknownFieldSet implements MessageLite {
reinitialize();
return this;
}
-
+
/** Clear fields from the set with a given field number. */
public Builder clearField(final int number) {
if (number == 0) {
@@ -406,9 +382,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Merge the fields from {@code other} into this set. If a field number
- * exists in both sets, {@code other}'s values for that field will be
- * appended to the values in this set.
+ * Merge the fields from {@code other} into this set. If a field number exists in both sets,
+ * {@code other}'s values for that field will be appended to the values in this set.
*/
public Builder mergeFrom(final UnknownFieldSet other) {
if (other != getDefaultInstance()) {
@@ -420,8 +395,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Add a field to the {@code UnknownFieldSet}. If a field with the same
- * number already exists, the two are merged.
+ * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists,
+ * the two are merged.
*/
public Builder mergeField(final int number, final Field field) {
if (number == 0) {
@@ -439,9 +414,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Convenience method for merging a new field containing a single varint
- * value. This is used in particular when an unknown enum value is
- * encountered.
+ * Convenience method for merging a new field containing a single varint value. This is used in
+ * particular when an unknown enum value is encountered.
*/
public Builder mergeVarintField(final int number, final int value) {
if (number == 0) {
@@ -451,14 +425,12 @@ public final class UnknownFieldSet implements MessageLite {
return this;
}
-
/**
* Convenience method for merging a length-delimited field.
*
* <p>For use by generated code only.
*/
- public Builder mergeLengthDelimitedField(
- final int number, final ByteString value) {
+ public Builder mergeLengthDelimitedField(final int number, final ByteString value) {
if (number == 0) {
throw new IllegalArgumentException("Zero is not a valid field number.");
}
@@ -475,8 +447,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Add a field to the {@code UnknownFieldSet}. If a field with the same
- * number already exists, it is removed.
+ * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists,
+ * it is removed.
*/
public Builder addField(final int number, final Field field) {
if (number == 0) {
@@ -488,25 +460,22 @@ public final class UnknownFieldSet implements MessageLite {
lastFieldNumber = 0;
}
if (fields.isEmpty()) {
- fields = new TreeMap<Integer,Field>();
+ fields = new TreeMap<Integer, Field>();
}
fields.put(number, field);
return this;
}
/**
- * Get all present {@code Field}s as an immutable {@code Map}. If more
- * fields are added, the changes may or may not be reflected in this map.
+ * Get all present {@code Field}s as an immutable {@code Map}. If more fields are added, the
+ * changes may or may not be reflected in this map.
*/
public Map<Integer, Field> asMap() {
- getFieldBuilder(0); // Force lastField to be built.
+ getFieldBuilder(0); // Force lastField to be built.
return Collections.unmodifiableMap(fields);
}
- /**
- * Parse an entire message from {@code input} and merge its fields into
- * this set.
- */
+ /** Parse an entire message from {@code input} and merge its fields into this set. */
@Override
public Builder mergeFrom(final CodedInputStream input) throws IOException {
while (true) {
@@ -520,11 +489,11 @@ public final class UnknownFieldSet implements MessageLite {
/**
* Parse a single field from {@code input} and merge it into this set.
+ *
* @param tag The field's tag number, which was already parsed.
* @return {@code false} if the tag is an end group tag.
*/
- public boolean mergeFieldFrom(final int tag, final CodedInputStream input)
- throws IOException {
+ public boolean mergeFieldFrom(final int tag, final CodedInputStream input) throws IOException {
final int number = WireFormat.getTagFieldNumber(tag);
switch (WireFormat.getTagWireType(tag)) {
case WireFormat.WIRETYPE_VARINT:
@@ -538,8 +507,7 @@ public final class UnknownFieldSet implements MessageLite {
return true;
case WireFormat.WIRETYPE_START_GROUP:
final Builder subBuilder = newBuilder();
- input.readGroup(number, subBuilder,
- ExtensionRegistry.getEmptyRegistry());
+ input.readGroup(number, subBuilder, ExtensionRegistry.getEmptyRegistry());
getFieldBuilder(number).addGroup(subBuilder.build());
return true;
case WireFormat.WIRETYPE_END_GROUP:
@@ -553,9 +521,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the
- * set being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*/
@Override
public Builder mergeFrom(final ByteString data) throws InvalidProtocolBufferException {
@@ -568,15 +535,13 @@ public final class UnknownFieldSet implements MessageLite {
throw e;
} catch (final IOException e) {
throw new RuntimeException(
- "Reading from a ByteString threw an IOException (should " +
- "never happen).", e);
+ "Reading from a ByteString threw an IOException (should never happen).", e);
}
}
/**
- * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the
- * set being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This
+ * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*/
@Override
public Builder mergeFrom(final byte[] data) throws InvalidProtocolBufferException {
@@ -589,15 +554,13 @@ public final class UnknownFieldSet implements MessageLite {
throw e;
} catch (final IOException e) {
throw new RuntimeException(
- "Reading from a byte array threw an IOException (should " +
- "never happen).", e);
+ "Reading from a byte array threw an IOException (should never happen).", e);
}
}
/**
- * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the
- * set being built. This is just a small wrapper around
- * {@link #mergeFrom(CodedInputStream)}.
+ * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the set being built.
+ * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*/
@Override
public Builder mergeFrom(final InputStream input) throws IOException {
@@ -643,8 +606,7 @@ public final class UnknownFieldSet implements MessageLite {
@Override
public Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException {
try {
- final CodedInputStream input =
- CodedInputStream.newInstance(data, off, len);
+ final CodedInputStream input = CodedInputStream.newInstance(data, off, len);
mergeFrom(input);
input.checkLastTagWas(0);
return this;
@@ -652,8 +614,7 @@ public final class UnknownFieldSet implements MessageLite {
throw e;
} catch (IOException e) {
throw new RuntimeException(
- "Reading from a byte array threw an IOException (should " +
- "never happen).", e);
+ "Reading from a byte array threw an IOException (should never happen).", e);
}
}
@@ -698,19 +659,15 @@ public final class UnknownFieldSet implements MessageLite {
/**
* Represents a single field in an {@code UnknownFieldSet}.
*
- * <p>A {@code Field} consists of five lists of values. The lists correspond
- * to the five "wire types" used in the protocol buffer binary format.
- * The wire type of each field can be determined from the encoded form alone,
- * without knowing the field's declared type. So, we are able to parse
- * unknown values at least this far and separate them. Normally, only one
- * of the five lists will contain any values, since it is impossible to
- * define a valid message type that declares two different types for the
- * same field number. However, the code is designed to allow for the case
- * where the same unknown field number is encountered using multiple different
- * wire types.
+ * <p>A {@code Field} consists of five lists of values. The lists correspond to the five "wire
+ * types" used in the protocol buffer binary format. The wire type of each field can be determined
+ * from the encoded form alone, without knowing the field's declared type. So, we are able to
+ * parse unknown values at least this far and separate them. Normally, only one of the five lists
+ * will contain any values, since it is impossible to define a valid message type that declares
+ * two different types for the same field number. However, the code is designed to allow for the
+ * case where the same unknown field number is encountered using multiple different wire types.
*
- * <p>{@code Field} is an immutable class. To construct one, you must use a
- * {@link Builder}.
+ * <p>{@code Field} is an immutable class. To construct one, you must use a {@link Builder}.
*
* @see UnknownFieldSet
*/
@@ -722,10 +679,7 @@ public final class UnknownFieldSet implements MessageLite {
return Builder.create();
}
- /**
- * Construct a new {@link Builder} and initialize it to a copy of
- * {@code copyFrom}.
- */
+ /** Construct a new {@link Builder} and initialize it to a copy of {@code copyFrom}. */
public static Builder newBuilder(final Field copyFrom) {
return newBuilder().mergeFrom(copyFrom);
}
@@ -734,26 +688,36 @@ public final class UnknownFieldSet implements MessageLite {
public static Field getDefaultInstance() {
return fieldDefaultInstance;
}
+
private static final Field fieldDefaultInstance = newBuilder().build();
/** Get the list of varint values for this field. */
- public List<Long> getVarintList() { return varint; }
+ public List<Long> getVarintList() {
+ return varint;
+ }
/** Get the list of fixed32 values for this field. */
- public List<Integer> getFixed32List() { return fixed32; }
+ public List<Integer> getFixed32List() {
+ return fixed32;
+ }
/** Get the list of fixed64 values for this field. */
- public List<Long> getFixed64List() { return fixed64; }
+ public List<Long> getFixed64List() {
+ return fixed64;
+ }
/** Get the list of length-delimited values for this field. */
- public List<ByteString> getLengthDelimitedList() { return lengthDelimited; }
+ public List<ByteString> getLengthDelimitedList() {
+ return lengthDelimited;
+ }
/**
- * Get the list of embedded group values for this field. These are
- * represented using {@link UnknownFieldSet}s rather than {@link Message}s
- * since the group's type is presumably unknown.
+ * Get the list of embedded group values for this field. These are represented using {@link
+ * UnknownFieldSet}s rather than {@link Message}s since the group's type is presumably unknown.
*/
- public List<UnknownFieldSet> getGroupList() { return group; }
+ public List<UnknownFieldSet> getGroupList() {
+ return group;
+ }
@Override
public boolean equals(final Object other) {
@@ -763,8 +727,7 @@ public final class UnknownFieldSet implements MessageLite {
if (!(other instanceof Field)) {
return false;
}
- return Arrays.equals(getIdentityArray(),
- ((Field) other).getIdentityArray());
+ return Arrays.equals(getIdentityArray(), ((Field) other).getIdentityArray());
}
@Override
@@ -772,25 +735,30 @@ public final class UnknownFieldSet implements MessageLite {
return Arrays.hashCode(getIdentityArray());
}
- /**
- * Returns the array of objects to be used to uniquely identify this
- * {@link Field} instance.
- */
+ /** Returns the array of objects to be used to uniquely identify this {@link Field} instance. */
private Object[] getIdentityArray() {
- return new Object[] {
- varint,
- fixed32,
- fixed64,
- lengthDelimited,
- group};
+ return new Object[] {varint, fixed32, fixed64, lengthDelimited, group};
}
/**
- * Serializes the field, including field number, and writes it to
- * {@code output}.
+ * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper
+ * around {@link #writeTo(int, CodedOutputStream)}.
*/
- public void writeTo(final int fieldNumber, final CodedOutputStream output)
- throws IOException {
+ public ByteString toByteString(int fieldNumber) {
+ try {
+ // TODO(lukes): consider caching serialized size in a volatile long
+ final ByteString.CodedBuilder out =
+ ByteString.newCodedBuilder(getSerializedSize(fieldNumber));
+ writeTo(fieldNumber, out.getCodedOutput());
+ return out.build();
+ } catch (IOException e) {
+ throw new RuntimeException(
+ "Serializing to a ByteString should never fail with an IOException", e);
+ }
+ }
+
+ /** Serializes the field, including field number, and writes it to {@code output}. */
+ public void writeTo(final int fieldNumber, final CodedOutputStream output) throws IOException {
for (final long value : varint) {
output.writeUInt64(fieldNumber, value);
}
@@ -808,10 +776,7 @@ public final class UnknownFieldSet implements MessageLite {
}
}
- /**
- * Get the number of bytes required to encode this field, including field
- * number.
- */
+ /** Get the number of bytes required to encode this field, including field number. */
public int getSerializedSize(final int fieldNumber) {
int result = 0;
for (final long value : varint) {
@@ -833,12 +798,10 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Serializes the field, including field number, and writes it to
- * {@code output}, using {@code MessageSet} wire format.
+ * Serializes the field, including field number, and writes it to {@code output}, using {@code
+ * MessageSet} wire format.
*/
- public void writeAsMessageSetExtensionTo(
- final int fieldNumber,
- final CodedOutputStream output)
+ public void writeAsMessageSetExtensionTo(final int fieldNumber, final CodedOutputStream output)
throws IOException {
for (final ByteString value : lengthDelimited) {
output.writeRawMessageSetExtension(fieldNumber, value);
@@ -853,8 +816,7 @@ public final class UnknownFieldSet implements MessageLite {
public int getSerializedSizeAsMessageSetExtension(final int fieldNumber) {
int result = 0;
for (final ByteString value : lengthDelimited) {
- result += CodedOutputStream.computeRawMessageSetExtensionSize(
- fieldNumber, value);
+ result += CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, value);
}
return result;
}
@@ -883,10 +845,9 @@ public final class UnknownFieldSet implements MessageLite {
private Field result;
/**
- * Build the field. After {@code build()} has been called, the
- * {@code Builder} is no longer usable. Calling any other method will
- * result in undefined behavior and can cause a
- * {@code NullPointerException} to be thrown.
+ * Build the field. After {@code build()} has been called, the {@code Builder} is no longer
+ * usable. Calling any other method will result in undefined behavior and can cause a {@code
+ * NullPointerException} to be thrown.
*/
public Field build() {
if (result.varint == null) {
@@ -907,8 +868,7 @@ public final class UnknownFieldSet implements MessageLite {
if (result.lengthDelimited == null) {
result.lengthDelimited = Collections.emptyList();
} else {
- result.lengthDelimited =
- Collections.unmodifiableList(result.lengthDelimited);
+ result.lengthDelimited = Collections.unmodifiableList(result.lengthDelimited);
}
if (result.group == null) {
result.group = Collections.emptyList();
@@ -928,9 +888,8 @@ public final class UnknownFieldSet implements MessageLite {
}
/**
- * Merge the values in {@code other} into this field. For each list
- * of values, {@code other}'s values are append to the ones in this
- * field.
+ * Merge the values in {@code other} into this field. For each list of values, {@code other}'s
+ * values are append to the ones in this field.
*/
public Builder mergeFrom(final Field other) {
if (!other.varint.isEmpty()) {
@@ -1013,9 +972,7 @@ public final class UnknownFieldSet implements MessageLite {
}
}
- /**
- * Parser to implement MessageLite interface.
- */
+ /** Parser to implement MessageLite interface. */
public static final class Parser extends AbstractParser<UnknownFieldSet> {
@Override
public UnknownFieldSet parsePartialFrom(
@@ -1027,14 +984,14 @@ public final class UnknownFieldSet implements MessageLite {
} catch (InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (IOException e) {
- throw new InvalidProtocolBufferException(e)
- .setUnfinishedMessage(builder.buildPartial());
+ throw new InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
}
private static final Parser PARSER = new Parser();
+
@Override
public final Parser getParserForType() {
return PARSER;
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 f0b919ad..7c5ec6e9 100644
--- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
+++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
@@ -34,24 +34,23 @@ import java.io.IOException;
import java.util.Arrays;
/**
- * {@code UnknownFieldSetLite} is used to keep track of fields which were seen
- * when parsing a protocol message but whose field numbers or types are
- * unrecognized. This most frequently occurs when new fields are added to a
- * message type and then messages containing those fields are read by old
- * software that was compiled before the new types were added.
+ * {@code UnknownFieldSetLite} is used to keep track of fields which were seen when parsing a
+ * protocol message but whose field numbers or types are unrecognized. This most frequently occurs
+ * when new fields are added to a message type and then messages containing those fields are read by
+ * old software that was compiled before the new types were added.
*
* <p>For use by generated code only.
*
* @author dweis@google.com (Daniel Weis)
*/
public final class UnknownFieldSetLite {
-
+
// Arbitrarily chosen.
// TODO(dweis): Tune this number?
private static final int MIN_CAPACITY = 8;
private static final UnknownFieldSetLite DEFAULT_INSTANCE =
- new UnknownFieldSetLite(0, new int[0], new Object[0], false /* isMutable */);
+ new UnknownFieldSetLite(0, new int[0], new Object[0], /* isMutable= */ false);
/**
* Get an empty {@code UnknownFieldSetLite}.
@@ -61,17 +60,15 @@ public final class UnknownFieldSetLite {
public static UnknownFieldSetLite getDefaultInstance() {
return DEFAULT_INSTANCE;
}
-
- /**
- * Returns a new mutable instance.
- */
+
+ /** Returns a new mutable instance. */
static UnknownFieldSetLite newInstance() {
return new UnknownFieldSetLite();
}
/**
- * Returns a mutable {@code UnknownFieldSetLite} that is the composite of {@code first} and
- * {@code second}.
+ * Returns a mutable {@code UnknownFieldSetLite} that is the composite of {@code first} and {@code
+ * second}.
*/
static UnknownFieldSetLite mutableCopyOf(UnknownFieldSetLite first, UnknownFieldSetLite second) {
int count = first.count + second.count;
@@ -79,66 +76,50 @@ public final class UnknownFieldSetLite {
System.arraycopy(second.tags, 0, tags, first.count, second.count);
Object[] objects = Arrays.copyOf(first.objects, count);
System.arraycopy(second.objects, 0, objects, first.count, second.count);
- return new UnknownFieldSetLite(count, tags, objects, true /* isMutable */);
+ return new UnknownFieldSetLite(count, tags, objects, /* isMutable= */ true);
}
- /**
- * The number of elements in the set.
- */
+ /** The number of elements in the set. */
private int count;
-
- /**
- * The tag numbers for the elements in the set.
- */
+
+ /** The tag numbers for the elements in the set. */
private int[] tags;
-
- /**
- * The boxed values of the elements in the set.
- */
+
+ /** The boxed values of the elements in the set. */
private Object[] objects;
-
- /**
- * The lazily computed serialized size of the set.
- */
+
+ /** The lazily computed serialized size of the set. */
private int memoizedSerializedSize = -1;
-
- /**
- * Indicates that this object is mutable.
- */
+
+ /** Indicates that this object is mutable. */
private boolean isMutable;
- /**
- * Constructs a mutable {@code UnknownFieldSetLite}.
- */
+ /** Constructs a mutable {@code UnknownFieldSetLite}. */
private UnknownFieldSetLite() {
- this(0, new int[MIN_CAPACITY], new Object[MIN_CAPACITY], true /* isMutable */);
+ this(0, new int[MIN_CAPACITY], new Object[MIN_CAPACITY], /* isMutable= */ true);
}
-
- /**
- * Constructs the {@code UnknownFieldSetLite}.
- */
+
+ /** Constructs the {@code UnknownFieldSetLite}. */
private UnknownFieldSetLite(int count, int[] tags, Object[] objects, boolean isMutable) {
this.count = count;
this.tags = tags;
this.objects = objects;
this.isMutable = isMutable;
}
-
+
/**
* Marks this object as immutable.
- *
+ *
* <p>Future calls to methods that attempt to modify this object will throw.
*/
public void makeImmutable() {
this.isMutable = false;
}
-
- /**
- * Throws an {@link UnsupportedOperationException} if immutable.
- */
+
+ /** Throws an {@link UnsupportedOperationException} if immutable. */
void checkMutable() {
if (!isMutable) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException();
}
}
@@ -197,17 +178,17 @@ public final class UnknownFieldSetLite {
if (size != -1) {
return size;
}
-
+
size = 0;
for (int i = 0; i < count; i++) {
int tag = tags[i];
int fieldNumber = WireFormat.getTagFieldNumber(tag);
- size += CodedOutputStream.computeRawMessageSetExtensionSize(
- fieldNumber, (ByteString) objects[i]);
+ size +=
+ CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, (ByteString) objects[i]);
}
-
+
memoizedSerializedSize = size;
-
+
return size;
}
@@ -221,7 +202,7 @@ public final class UnknownFieldSetLite {
if (size != -1) {
return size;
}
-
+
size = 0;
for (int i = 0; i < count; i++) {
int tag = tags[i];
@@ -240,19 +221,20 @@ public final class UnknownFieldSetLite {
size += CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) objects[i]);
break;
case WireFormat.WIRETYPE_START_GROUP:
- size += CodedOutputStream.computeTagSize(fieldNumber) * 2
- + ((UnknownFieldSetLite) objects[i]).getSerializedSize();
+ size +=
+ CodedOutputStream.computeTagSize(fieldNumber) * 2
+ + ((UnknownFieldSetLite) objects[i]).getSerializedSize();
break;
default:
throw new IllegalStateException(InvalidProtocolBufferException.invalidWireType());
}
}
-
+
memoizedSerializedSize = size;
-
+
return size;
}
-
+
private static boolean equals(int[] tags1, int[] tags2, int count) {
for (int i = 0; i < count; ++i) {
if (tags1[i] != tags2[i]) {
@@ -284,8 +266,8 @@ public final class UnknownFieldSetLite {
if (!(obj instanceof UnknownFieldSetLite)) {
return false;
}
-
- UnknownFieldSetLite other = (UnknownFieldSetLite) obj;
+
+ UnknownFieldSetLite other = (UnknownFieldSetLite) obj;
if (count != other.count
|| !equals(tags, other.tags, count)
|| !equals(objects, other.objects, count)) {
@@ -341,25 +323,23 @@ public final class UnknownFieldSetLite {
void storeField(int tag, Object value) {
checkMutable();
ensureCapacity();
-
+
tags[count] = tag;
objects[count] = value;
count++;
}
-
- /**
- * Ensures that our arrays are long enough to store more metadata.
- */
+
+ /** Ensures that our arrays are long enough to store more metadata. */
private void ensureCapacity() {
- if (count == tags.length) {
+ if (count == tags.length) {
int increment = count < (MIN_CAPACITY / 2) ? MIN_CAPACITY : count >> 1;
int newLength = count + increment;
-
+
tags = Arrays.copyOf(tags, newLength);
objects = Arrays.copyOf(objects, newLength);
}
}
-
+
/**
* Parse a single field from {@code input} and merge it into this set.
*
@@ -387,8 +367,7 @@ public final class UnknownFieldSetLite {
case WireFormat.WIRETYPE_START_GROUP:
final UnknownFieldSetLite subFieldSet = new UnknownFieldSetLite();
subFieldSet.mergeFrom(input);
- input.checkLastTagWas(
- WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ input.checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
storeField(tag, subFieldSet);
return true;
case WireFormat.WIRETYPE_END_GROUP:
@@ -399,9 +378,8 @@ public final class UnknownFieldSetLite {
}
/**
- * Convenience method for merging a new field containing a single varint
- * value. This is used in particular when an unknown enum value is
- * encountered.
+ * Convenience method for merging a new field containing a single varint value. This is used in
+ * particular when an unknown enum value is encountered.
*
* <p>For use by generated code only.
*/
@@ -412,7 +390,7 @@ public final class UnknownFieldSetLite {
}
storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_VARINT), (long) value);
-
+
return this;
}
@@ -421,21 +399,18 @@ public final class UnknownFieldSetLite {
*
* <p>For use by generated code only.
*/
- UnknownFieldSetLite mergeLengthDelimitedField(final int fieldNumber, final ByteString value) {
+ UnknownFieldSetLite mergeLengthDelimitedField(final int fieldNumber, final ByteString value) {
checkMutable();
if (fieldNumber == 0) {
throw new IllegalArgumentException("Zero is not a valid field number.");
}
storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED), value);
-
+
return this;
}
-
- /**
- * Parse an entire message from {@code input} and merge its fields into
- * this set.
- */
+
+ /** Parse an entire message from {@code input} and merge its fields into this set. */
private UnknownFieldSetLite mergeFrom(final CodedInputStream input) throws IOException {
// Ensures initialization in mergeFieldFrom.
while (true) {
diff --git a/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java b/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java
index 30e87911..415b2cde 100644
--- a/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java
+++ b/java/core/src/main/java/com/google/protobuf/UnmodifiableLazyStringList.java
@@ -39,8 +39,8 @@ import java.util.ListIterator;
import java.util.RandomAccess;
/**
- * An implementation of {@link LazyStringList} that wraps another
- * {@link LazyStringList} such that it cannot be modified via the wrapper.
+ * An implementation of {@link LazyStringList} that wraps another {@link LazyStringList} such that
+ * it cannot be modified via the wrapper.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -57,7 +57,7 @@ public class UnmodifiableLazyStringList extends AbstractList<String>
public String get(int index) {
return list.get(index);
}
-
+
@Override
public Object getRaw(int index) {
return list.getRaw(index);
@@ -97,7 +97,7 @@ public class UnmodifiableLazyStringList extends AbstractList<String>
public void add(byte[] element) {
throw new UnsupportedOperationException();
}
-
+
@Override
public void set(int index, byte[] element) {
throw new UnsupportedOperationException();
diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
index 878c7758..bcaf1d2f 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
@@ -39,23 +39,24 @@ import java.nio.ByteBuffer;
* potentially expose the backing buffer of a {@link ByteString} to the application.
*
* <p><strong>DISCLAIMER:</strong> The methods in this class should only be called if it is
- * guaranteed that the buffer backing the {@link ByteString} will never change! Mutation of a
- * {@link ByteString} can lead to unexpected and undesirable consequences in your application,
- * and will likely be difficult to debug. Proceed with caution!
+ * guaranteed that the buffer backing the {@link ByteString} will never change! Mutation of a {@link
+ * ByteString} can lead to unexpected and undesirable consequences in your application, and will
+ * likely be difficult to debug. Proceed with caution!
+ *
+ * <p>This can have a number of significant side affects that have spooky-action-at-a-distance-like
+ * behavior. In particular, if the bytes value changes out from under a Protocol Buffer:
*
- * <p>This can have a number of significant side affects that have
- * spooky-action-at-a-distance-like behavior. In particular, if the bytes value changes out from
- * under a Protocol Buffer:
* <ul>
- * <li>serialization may throw
- * <li>serialization may succeed but the wrong bytes may be written out
- * <li>messages are no longer threadsafe
- * <li>hashCode may be incorrect
- * <ul>
- * <li>can result in a permanent memory leak when used as a key in a long-lived HashMap
- * <li> the semantics of many programs may be violated if this is the case
- * </ul>
+ * <li>serialization may throw
+ * <li>serialization may succeed but the wrong bytes may be written out
+ * <li>messages are no longer threadsafe
+ * <li>hashCode may be incorrect
+ * <ul>
+ * <li>can result in a permanent memory leak when used as a key in a long-lived HashMap
+ * <li>the semantics of many programs may be violated if this is the case
+ * </ul>
* </ul>
+ *
* Each of these issues will occur in parts of the code base that are entirely distinct from the
* parts of the code base modifying the buffer. In fact, both parts of the code base may be correct
* - it is the bridging with the unsafe operations that was in error!
@@ -99,19 +100,19 @@ public final class UnsafeByteOperations {
/**
* Writes the given {@link ByteString} to the provided {@link ByteOutput}. Calling this method may
- * result in multiple operations on the target {@link ByteOutput}
- * (i.e. for roped {@link ByteString}s).
+ * result in multiple operations on the target {@link ByteOutput} (i.e. for roped {@link
+ * ByteString}s).
*
* <p>This method exposes the internal backing buffer(s) of the {@link ByteString} to the {@link
* ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious
* {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution!
*
- * <p> NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing
- * so may result in corrupted data, which would be difficult to debug.
+ * <p>NOTE: The {@link ByteOutput} <strong>MUST NOT</strong> modify the provided buffers. Doing so
+ * may result in corrupted data, which would be difficult to debug.
*
* @param bytes the {@link ByteString} to be written
- * @param output the output to receive the bytes
- * @throws IOException if an I/O error occurs
+ * @param output the output to receive the bytes
+ * @throws IOException if an I/O error occurs
*/
public static void unsafeWriteTo(ByteString bytes, ByteOutput output) throws IOException {
bytes.writeTo(output);
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 c9e2904b..50bc911d 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
@@ -72,8 +72,6 @@ final class UnsafeUtil {
private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(bufferAddressField());
- private static final long STRING_VALUE_OFFSET = fieldOffset(stringValueField());
-
private UnsafeUtil() {}
static boolean hasUnsafeArrayOperations() {
@@ -228,7 +226,7 @@ final class UnsafeUtil {
}
static void copyMemory(byte[] src, long srcIndex, byte[] target, long targetIndex, long length) {
- System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length);
+ System.arraycopy(src, (int) srcIndex, target, (int) targetIndex, (int) length);
}
static byte getByte(long address) {
@@ -255,33 +253,11 @@ final class UnsafeUtil {
MEMORY_ACCESSOR.putLong(address, value);
}
- /**
- * Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}.
- */
+ /** Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}. */
static long addressOffset(ByteBuffer buffer) {
return MEMORY_ACCESSOR.getLong(buffer, BUFFER_ADDRESS_OFFSET);
}
- /**
- * Returns a new {@link String} backed by the given {@code chars}. The char array should not
- * be mutated any more after calling this function.
- */
- static String moveToString(char[] chars) {
- if (STRING_VALUE_OFFSET == -1) {
- // In the off-chance that this JDK does not implement String as we'd expect, just do a copy.
- return new String(chars);
- }
- final String str;
- try {
- str = (String) UNSAFE.allocateInstance(String.class);
- } catch (InstantiationException e) {
- // This should never happen, but return a copy as a fallback just in case.
- return new String(chars);
- }
- putObject(str, STRING_VALUE_OFFSET, chars);
- return str;
- }
-
static Object getStaticObject(Field field) {
return MEMORY_ACCESSOR.getStaticObject(field);
}
@@ -397,12 +373,6 @@ final class UnsafeUtil {
return field != null && field.getType() == long.class ? field : null;
}
- /** Finds the value field within a {@link String}. */
- private static Field stringValueField() {
- Field field = field(String.class, "value");
- return field != null && field.getType() == char[].class ? field : null;
- }
-
/**
* Returns the offset of the provided field, or {@code -1} if {@code sun.misc.Unsafe} is not
* available.
@@ -500,9 +470,9 @@ final class UnsafeUtil {
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);
}
@@ -581,12 +551,12 @@ final class UnsafeUtil {
public void putDouble(Object target, long offset, double value) {
unsafe.putDouble(target, offset, value);
}
-
- @Override
+
+ @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);
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 6968abb3..4512bf9b 100644
--- a/java/core/src/main/java/com/google/protobuf/Utf8.java
+++ b/java/core/src/main/java/com/google/protobuf/Utf8.java
@@ -42,39 +42,33 @@ import static java.lang.Character.isSurrogatePair;
import static java.lang.Character.toCodePoint;
import java.nio.ByteBuffer;
-import java.util.Arrays;
/**
- * A set of low-level, high-performance static utility methods related
- * to the UTF-8 character encoding. This class has no dependencies
- * outside of the core JDK libraries.
+ * A set of low-level, high-performance static utility methods related to the UTF-8 character
+ * encoding. This class has no dependencies outside of the core JDK libraries.
*
- * <p>There are several variants of UTF-8. The one implemented by
- * this class is the restricted definition of UTF-8 introduced in
- * Unicode 3.1, which mandates the rejection of "overlong" byte
- * sequences as well as rejection of 3-byte surrogate codepoint byte
- * sequences. Note that the UTF-8 decoder included in Oracle's JDK
- * has been modified to also reject "overlong" byte sequences, but (as
- * of 2011) still accepts 3-byte surrogate codepoint byte sequences.
+ * <p>There are several variants of UTF-8. The one implemented by this class is the restricted
+ * definition of UTF-8 introduced in Unicode 3.1, which mandates the rejection of "overlong" byte
+ * sequences as well as rejection of 3-byte surrogate codepoint byte sequences. Note that the UTF-8
+ * decoder included in Oracle's JDK has been modified to also reject "overlong" byte sequences, but
+ * (as of 2011) still accepts 3-byte surrogate codepoint byte sequences.
*
- * <p>The byte sequences considered valid by this class are exactly
- * those that can be roundtrip converted to Strings and back to bytes
- * using the UTF-8 charset, without loss: <pre> {@code
+ * <p>The byte sequences considered valid by this class are exactly those that can be roundtrip
+ * converted to Strings and back to bytes using the UTF-8 charset, without loss:
+ *
+ * <pre>{@code
* Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8))
* }</pre>
*
- * <p>See the Unicode Standard,</br>
- * Table 3-6. <em>UTF-8 Bit Distribution</em>,</br>
- * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>.
+ * <p>See the Unicode Standard,</br> Table 3-6. <em>UTF-8 Bit Distribution</em>,</br> Table 3-7.
+ * <em>Well Formed UTF-8 Byte Sequences</em>.
*
- * <p>This class supports decoding of partial byte sequences, so that the
- * bytes in a complete UTF-8 byte sequences can be stored in multiple
- * segments. Methods typically return {@link #MALFORMED} if the partial
- * byte sequence is definitely not well-formed, {@link #COMPLETE} if it is
- * well-formed in the absence of additional input, or if the byte sequence
- * apparently terminated in the middle of a character, an opaque integer
- * "state" value containing enough information to decode the character when
- * passed to a subsequent invocation of a partial decoding method.
+ * <p>This class supports decoding of partial byte sequences, so that the bytes in a complete UTF-8
+ * byte sequences can be stored in multiple segments. Methods typically return {@link #MALFORMED} if
+ * the partial byte sequence is definitely not well-formed, {@link #COMPLETE} if it is well-formed
+ * in the absence of additional input, or if the byte sequence apparently terminated in the middle
+ * of a character, an opaque integer "state" value containing enough information to decode the
+ * character when passed to a subsequent invocation of a partial decoding method.
*
* @author martinrb@google.com (Martin Buchholz)
*/
@@ -87,7 +81,9 @@ final class Utf8 {
* delegate for which all methods are delegated directly to.
*/
private static final Processor processor =
- UnsafeProcessor.isAvailable() ? new UnsafeProcessor() : new SafeProcessor();
+ (UnsafeProcessor.isAvailable() && !Android.isOnAndroidDevice())
+ ? new UnsafeProcessor()
+ : new SafeProcessor();
/**
* A mask used when performing unsafe reads to determine if a long value contains any non-ASCII
@@ -97,31 +93,28 @@ final class Utf8 {
/**
* Maximum number of bytes per Java UTF-16 char in UTF-8.
+ *
* @see java.nio.charset.CharsetEncoder#maxBytesPerChar()
*/
static final int MAX_BYTES_PER_CHAR = 3;
/**
- * State value indicating that the byte sequence is well-formed and
- * complete (no further bytes are needed to complete a character).
+ * State value indicating that the byte sequence is well-formed and complete (no further bytes are
+ * needed to complete a character).
*/
public static final int COMPLETE = 0;
- /**
- * State value indicating that the byte sequence is definitely not
- * well-formed.
- */
+ /** State value indicating that the byte sequence is definitely not well-formed. */
public static final int MALFORMED = -1;
/**
* Used by {@code Unsafe} UTF-8 string validation logic to determine the minimum string length
* above which to employ an optimized algorithm for counting ASCII characters. The reason for this
* threshold is that for small strings, the optimization may not be beneficial or may even
- * negatively impact performance since it requires additional logic to avoid unaligned reads
- * (when calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial
- * offset is unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()}
- * which provides a performance improvement that entirely subsumes the cost of the additional
- * logic.
+ * negatively impact performance since it requires additional logic to avoid unaligned reads (when
+ * calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial offset is
+ * unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} which
+ * provides a performance improvement that entirely subsumes the cost of the additional logic.
*/
private static final int UNSAFE_COUNT_ASCII_THRESHOLD = 16;
@@ -145,76 +138,69 @@ final class Utf8 {
// are valid trailing bytes.
/**
- * Returns {@code true} if the given byte array is a well-formed
- * UTF-8 byte sequence.
+ * Returns {@code true} if the given byte array is a well-formed UTF-8 byte sequence.
*
- * <p>This is a convenience method, equivalent to a call to {@code
- * isValidUtf8(bytes, 0, bytes.length)}.
+ * <p>This is a convenience method, equivalent to a call to {@code isValidUtf8(bytes, 0,
+ * bytes.length)}.
*/
public static boolean isValidUtf8(byte[] bytes) {
return processor.isValidUtf8(bytes, 0, bytes.length);
}
/**
- * Returns {@code true} if the given byte array slice is a
- * well-formed UTF-8 byte sequence. The range of bytes to be
- * checked extends from index {@code index}, inclusive, to {@code
- * limit}, exclusive.
+ * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The
+ * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit},
+ * exclusive.
*
- * <p>This is a convenience method, equivalent to {@code
- * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}.
+ * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit)
+ * == Utf8.COMPLETE}.
*/
public static boolean isValidUtf8(byte[] bytes, int index, int limit) {
return processor.isValidUtf8(bytes, index, limit);
}
/**
- * Tells whether the given byte array slice is a well-formed,
- * malformed, or incomplete UTF-8 byte sequence. The range of bytes
- * to be checked extends from index {@code index}, inclusive, to
+ * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 byte
+ * sequence. The range of bytes to be checked extends from index {@code index}, inclusive, to
* {@code limit}, exclusive.
*
- * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding
- * operation) or the value returned from a call to a partial decoding method
- * for the previous bytes
- *
- * @return {@link #MALFORMED} if the partial byte sequence is
- * definitely not well-formed, {@link #COMPLETE} if it is well-formed
- * (no additional input needed), or if the byte sequence is
- * "incomplete", i.e. apparently terminated in the middle of a character,
- * an opaque integer "state" value containing enough information to
- * decode the character when passed to a subsequent invocation of a
- * partial decoding method.
+ * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the
+ * value returned from a call to a partial decoding method for the previous bytes
+ * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link
+ * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is
+ * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer
+ * "state" value containing enough information to decode the character when passed to a
+ * subsequent invocation of a partial decoding method.
*/
public static int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) {
return processor.partialIsValidUtf8(state, bytes, index, limit);
}
private static int incompleteStateFor(int byte1) {
- return (byte1 > (byte) 0xF4) ?
- MALFORMED : byte1;
+ return (byte1 > (byte) 0xF4) ? MALFORMED : byte1;
}
private static int incompleteStateFor(int byte1, int byte2) {
- return (byte1 > (byte) 0xF4 ||
- byte2 > (byte) 0xBF) ?
- MALFORMED : byte1 ^ (byte2 << 8);
+ return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8);
}
private static int incompleteStateFor(int byte1, int byte2, int byte3) {
- return (byte1 > (byte) 0xF4 ||
- byte2 > (byte) 0xBF ||
- byte3 > (byte) 0xBF) ?
- MALFORMED : byte1 ^ (byte2 << 8) ^ (byte3 << 16);
+ return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF || byte3 > (byte) 0xBF)
+ ? MALFORMED
+ : byte1 ^ (byte2 << 8) ^ (byte3 << 16);
}
private static int incompleteStateFor(byte[] bytes, int index, int limit) {
int byte1 = bytes[index - 1];
switch (limit - index) {
- case 0: return incompleteStateFor(byte1);
- case 1: return incompleteStateFor(byte1, bytes[index]);
- case 2: return incompleteStateFor(byte1, bytes[index], bytes[index + 1]);
- default: throw new AssertionError();
+ case 0:
+ return incompleteStateFor(byte1);
+ case 1:
+ return incompleteStateFor(byte1, bytes[index]);
+ case 2:
+ return incompleteStateFor(byte1, bytes[index], bytes[index + 1]);
+ default:
+ throw new AssertionError();
}
}
@@ -235,7 +221,7 @@ final class Utf8 {
// These UTF-8 handling methods are copied from Guava's Utf8 class with a modification to throw
// a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can
// fallback to more lenient behavior.
-
+
static class UnpairedSurrogateException extends IllegalArgumentException {
UnpairedSurrogateException(int index, int length) {
super("Unpaired surrogate at index " + index + " of " + length);
@@ -243,9 +229,9 @@ final class Utf8 {
}
/**
- * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string,
- * this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in
- * both time and space.
+ * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this
+ * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both
+ * time and space.
*
* @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
* surrogates)
@@ -265,7 +251,7 @@ final class Utf8 {
for (; i < utf16Length; i++) {
char c = sequence.charAt(i);
if (c < 0x800) {
- utf8Length += ((0x7f - c) >>> 31); // branch free!
+ utf8Length += ((0x7f - c) >>> 31); // branch free!
} else {
utf8Length += encodedLengthGeneral(sequence, i);
break;
@@ -274,8 +260,8 @@ final class Utf8 {
if (utf8Length < utf16Length) {
// Necessary and sufficient condition for overflow because of maximum 3x expansion
- throw new IllegalArgumentException("UTF-8 length does not fit in int: "
- + (utf8Length + (1L << 32)));
+ throw new IllegalArgumentException(
+ "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32)));
}
return utf8Length;
}
@@ -369,15 +355,15 @@ final class Utf8 {
}
/**
- * Counts (approximately) the number of consecutive ASCII characters in the given buffer.
- * The byte order of the {@link ByteBuffer} does not matter, so performance can be improved if
- * native byte order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}).
+ * Counts (approximately) the number of consecutive ASCII characters in the given buffer. The byte
+ * order of the {@link ByteBuffer} does not matter, so performance can be improved if native byte
+ * order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}).
*
* @param buffer the buffer to be scanned for ASCII chars
* @param index the starting index of the scan
* @param limit the limit within buffer for the scan
- * @return the number of ASCII characters found. The stopping position will be at or
- * before the first non-ASCII byte.
+ * @return the number of ASCII characters found. The stopping position will be at or before the
+ * first non-ASCII byte.
*/
private static int estimateConsecutiveAscii(ByteBuffer buffer, int index, int limit) {
int i = index;
@@ -389,52 +375,43 @@ final class Utf8 {
return i - index;
}
- /**
- * A processor of UTF-8 strings, providing methods for checking validity and encoding.
- */
+ /** A processor of UTF-8 strings, providing methods for checking validity and encoding. */
// TODO(nathanmittler): Add support for Memory/MemoryBlock on Android.
abstract static class Processor {
/**
- * Returns {@code true} if the given byte array slice is a
- * well-formed UTF-8 byte sequence. The range of bytes to be
- * checked extends from index {@code index}, inclusive, to {@code
- * limit}, exclusive.
+ * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The
+ * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit},
+ * exclusive.
*
- * <p>This is a convenience method, equivalent to {@code
- * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}.
+ * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit)
+ * == Utf8.COMPLETE}.
*/
final boolean isValidUtf8(byte[] bytes, int index, int limit) {
return partialIsValidUtf8(COMPLETE, bytes, index, limit) == COMPLETE;
}
/**
- * Tells whether the given byte array slice is a well-formed,
- * malformed, or incomplete UTF-8 byte sequence. The range of bytes
- * to be checked extends from index {@code index}, inclusive, to
- * {@code limit}, exclusive.
- *
- * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding
- * operation) or the value returned from a call to a partial decoding method
- * for the previous bytes
+ * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8
+ * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive,
+ * to {@code limit}, exclusive.
*
- * @return {@link #MALFORMED} if the partial byte sequence is
- * definitely not well-formed, {@link #COMPLETE} if it is well-formed
- * (no additional input needed), or if the byte sequence is
- * "incomplete", i.e. apparently terminated in the middle of a character,
- * an opaque integer "state" value containing enough information to
- * decode the character when passed to a subsequent invocation of a
- * partial decoding method.
+ * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the
+ * value returned from a call to a partial decoding method for the previous bytes
+ * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link
+ * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is
+ * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer
+ * "state" value containing enough information to decode the character when passed to a
+ * subsequent invocation of a partial decoding method.
*/
abstract int partialIsValidUtf8(int state, byte[] bytes, int index, int limit);
/**
- * Returns {@code true} if the given portion of the {@link ByteBuffer} is a
- * well-formed UTF-8 byte sequence. The range of bytes to be
- * checked extends from index {@code index}, inclusive, to {@code
- * limit}, exclusive.
+ * Returns {@code true} if the given portion of the {@link ByteBuffer} is a well-formed UTF-8
+ * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive,
+ * to {@code limit}, exclusive.
*
- * <p>This is a convenience method, equivalent to {@code
- * partialIsValidUtf8(bytes, index, limit) == Utf8.COMPLETE}.
+ * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit)
+ * == Utf8.COMPLETE}.
*/
final boolean isValidUtf8(ByteBuffer buffer, int index, int limit) {
return partialIsValidUtf8(COMPLETE, buffer, index, limit) == COMPLETE;
@@ -451,22 +428,20 @@ final class Utf8 {
if (buffer.hasArray()) {
final int offset = buffer.arrayOffset();
return partialIsValidUtf8(state, buffer.array(), offset + index, offset + limit);
- } else if (buffer.isDirect()){
+ } else if (buffer.isDirect()) {
return partialIsValidUtf8Direct(state, buffer, index, limit);
}
return partialIsValidUtf8Default(state, buffer, index, limit);
}
- /**
- * Performs validation for direct {@link ByteBuffer} instances.
- */
+ /** Performs validation for direct {@link ByteBuffer} instances. */
abstract int partialIsValidUtf8Direct(
final int state, final ByteBuffer buffer, int index, final int limit);
/**
* Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather
- * than potentially faster approaches. This first completes validation for the current
- * character (provided by {@code state}) and then finishes validation for the sequence.
+ * than potentially faster approaches. This first completes validation for the current character
+ * (provided by {@code state}) and then finishes validation for the sequence.
*/
final int partialIsValidUtf8Default(
final int state, final ByteBuffer buffer, int index, final int limit) {
@@ -565,7 +540,7 @@ final class Utf8 {
private static int partialIsValidUtf8(final ByteBuffer buffer, int index, final int limit) {
index += estimateConsecutiveAscii(buffer, index, limit);
- for (;;) {
+ for (; ; ) {
// Optimize for interior runs of ASCII bytes.
// TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold?
// Maybe after seeing a few in a row that are ASCII, go back to fast mode?
@@ -657,15 +632,13 @@ final class Utf8 {
return decodeUtf8Default(buffer, index, size);
}
- /**
- * Decodes direct {@link ByteBuffer} instances into {@link String}.
- */
+ /** Decodes direct {@link ByteBuffer} instances into {@link String}. */
abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size)
throws InvalidProtocolBufferException;
/**
- * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than
- * potentially faster approaches.
+ * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than potentially
+ * faster approaches.
*/
final String decodeUtf8Default(ByteBuffer buffer, int index, int size)
throws InvalidProtocolBufferException {
@@ -746,21 +719,22 @@ final class Utf8 {
/**
* Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}).
* For a string, this method is similar to
+ *
* <pre>{@code
* byte[] a = string.getBytes(UTF_8);
* System.arraycopy(a, 0, bytes, offset, a.length);
* return offset + a.length;
* }</pre>
*
- * but is more efficient in both time and space. One key difference is that this method
- * requires paired surrogates, and therefore does not support chunking.
- * While {@code String.getBytes(UTF_8)} replaces unpaired surrogates with the default
- * replacement character, this method throws {@link UnpairedSurrogateException}.
+ * but is more efficient in both time and space. One key difference is that this method requires
+ * paired surrogates, and therefore does not support chunking. While {@code
+ * String.getBytes(UTF_8)} replaces unpaired surrogates with the default replacement character,
+ * this method throws {@link UnpairedSurrogateException}.
*
* <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
- * compute the exact amount needed, or leave room for
- * {@code Utf8.MAX_BYTES_PER_CHAR * sequence.length()}, which is the largest possible number
- * of bytes that any input can be encoded to.
+ * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR *
+ * sequence.length()}, which is the largest possible number of bytes that any input can be
+ * encoded to.
*
* @param in the input character sequence to be encoded
* @param out the target array
@@ -777,26 +751,24 @@ final class Utf8 {
/**
* Encodes an input character sequence ({@code in}) to UTF-8 in the target buffer ({@code out}).
* Upon returning from this method, the {@code out} position will point to the position after
- * the last encoded byte. This method requires paired surrogates, and therefore does not
- * support chunking.
+ * the last encoded byte. This method requires paired surrogates, and therefore does not support
+ * chunking.
*
* <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
- * compute the exact amount needed, or leave room for
- * {@code Utf8.MAX_BYTES_PER_CHAR * in.length()}, which is the largest possible number
- * of bytes that any input can be encoded to.
+ * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR *
+ * in.length()}, which is the largest possible number of bytes that any input can be encoded to.
*
* @param in the source character sequence to be encoded
* @param out the target buffer
* @throws UnpairedSurrogateException if {@code in} contains ill-formed UTF-16 (unpaired
* surrogates)
- * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than
- * {@code out.remaining()}
+ * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than {@code
+ * out.remaining()}
*/
final void encodeUtf8(CharSequence in, ByteBuffer out) {
if (out.hasArray()) {
final int offset = out.arrayOffset();
- int endIndex =
- Utf8.encode(in, out.array(), offset + out.position(), out.remaining());
+ int endIndex = Utf8.encode(in, out.array(), offset + out.position(), out.remaining());
out.position(endIndex - offset);
} else if (out.isDirect()) {
encodeUtf8Direct(in, out);
@@ -805,9 +777,7 @@ final class Utf8 {
}
}
- /**
- * Encodes the input character sequence to a direct {@link ByteBuffer} instance.
- */
+ /** Encodes the input character sequence to a direct {@link ByteBuffer} instance. */
abstract void encodeUtf8Direct(CharSequence in, ByteBuffer out);
/**
@@ -886,9 +856,7 @@ final class Utf8 {
}
}
- /**
- * {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods.
- */
+ /** {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. */
static final class SafeProcessor extends Processor {
@Override
int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) {
@@ -900,7 +868,7 @@ final class Utf8 {
//
// We expect such "straddler characters" to be rare.
- if (index >= limit) { // No bytes? No progress.
+ if (index >= limit) { // No bytes? No progress.
return state;
}
int byte1 = (byte) state;
@@ -1097,8 +1065,7 @@ final class Utf8 {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
final char low;
- if (i + 1 == in.length()
- || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) {
+ if (i + 1 == in.length() || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) {
throw new UnpairedSurrogateException((i - 1), utf16Length);
}
int codePoint = Character.toCodePoint(c, low);
@@ -1110,8 +1077,7 @@ final class Utf8 {
// If we are surrogates and we're not a surrogate pair, always throw an
// UnpairedSurrogateException instead of an ArrayOutOfBoundsException.
if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE)
- && (i + 1 == in.length()
- || !Character.isSurrogatePair(c, in.charAt(i + 1)))) {
+ && (i + 1 == in.length() || !Character.isSurrogatePair(c, in.charAt(i + 1)))) {
throw new UnpairedSurrogateException(i, utf16Length);
}
throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j);
@@ -1137,7 +1103,7 @@ final class Utf8 {
}
private static int partialIsValidUtf8NonAscii(byte[] bytes, int index, int limit) {
- for (;;) {
+ for (; ; ) {
int byte1, byte2;
// Optimize for interior runs of ASCII bytes.
@@ -1157,8 +1123,7 @@ final class Utf8 {
// Simultaneously checks for illegal trailing-byte in
// leading position and overlong 2-byte form.
- if (byte1 < (byte) 0xC2
- || bytes[index++] > (byte) 0xBF) {
+ if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) {
return MALFORMED;
}
} else if (byte1 < (byte) 0xF0) {
@@ -1179,7 +1144,7 @@ final class Utf8 {
} else {
// four-byte form
- if (index >= limit - 2) { // incomplete sequence
+ if (index >= limit - 2) { // incomplete sequence
return incompleteStateFor(bytes, index, limit);
}
if ((byte2 = bytes[index++]) > (byte) 0xBF
@@ -1199,13 +1164,9 @@ final class Utf8 {
}
}
- /**
- * {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance.
- */
+ /** {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. */
static final class UnsafeProcessor extends Processor {
- /**
- * Indicates whether or not all required unsafe operations are supported on this platform.
- */
+ /** Indicates whether or not all required unsafe operations are supported on this platform. */
static boolean isAvailable() {
return hasUnsafeArrayOperations() && hasUnsafeByteBufferOperations();
}
@@ -1227,7 +1188,7 @@ final class Utf8 {
//
// We expect such "straddler characters" to be rare.
- if (offset >= offsetLimit) { // No bytes? No progress.
+ if (offset >= offsetLimit) { // No bytes? No progress.
return state;
}
int byte1 = (byte) state;
@@ -1474,10 +1435,7 @@ final class Utf8 {
}
}
- if (resultPos < resultArr.length) {
- resultArr = Arrays.copyOf(resultArr, resultPos);
- }
- return UnsafeUtil.moveToString(resultArr);
+ return new String(resultArr, 0, resultPos);
}
@Override
@@ -1553,10 +1511,7 @@ final class Utf8 {
}
}
- if (resultPos < resultArr.length) {
- resultArr = Arrays.copyOf(resultArr, resultPos);
- }
- return UnsafeUtil.moveToString(resultArr);
+ return new String(resultArr, 0, resultPos);
}
@Override
@@ -1690,8 +1645,8 @@ final class Utf8 {
* @param bytes the array containing the character sequence
* @param offset the offset position of the index (same as index + arrayBaseOffset)
* @param maxChars the maximum number of characters to count
- * @return the number of ASCII characters found. The stopping position will be at or
- * before the first non-ASCII byte.
+ * @return the number of ASCII characters found. The stopping position will be at or before the
+ * first non-ASCII byte.
*/
private static int unsafeEstimateConsecutiveAscii(
byte[] bytes, long offset, final int maxChars) {
@@ -1733,24 +1688,24 @@ final class Utf8 {
// 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(address) & ASCII_MASK_LONG) == 0;
+ for (;
+ remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0;
address += 8, remaining -= 8) {}
return maxChars - remaining;
}
private static int partialIsValidUtf8(final byte[] bytes, long offset, int remaining) {
- // Skip past ASCII characters as quickly as possible.
+ // Skip past ASCII characters as quickly as possible.
final int skipped = unsafeEstimateConsecutiveAscii(bytes, offset, remaining);
remaining -= skipped;
offset += skipped;
- for (;;) {
+ for (; ; ) {
// Optimize for interior runs of ASCII bytes.
// TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold?
// Maybe after seeing a few in a row that are ASCII, go back to fast mode?
int byte1 = 0;
- for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {
- }
+ for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {}
if (remaining == 0) {
return COMPLETE;
}
@@ -1767,8 +1722,7 @@ final class Utf8 {
// Simultaneously checks for illegal trailing-byte in
// leading position and overlong 2-byte form.
- if (byte1 < (byte) 0xC2
- || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) {
+ if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) {
return MALFORMED;
}
} else if (byte1 < (byte) 0xF0) {
@@ -1820,13 +1774,12 @@ final class Utf8 {
address += skipped;
remaining -= skipped;
- for (;;) {
+ for (; ; ) {
// Optimize for interior runs of ASCII bytes.
// TODO(nathanmittler): Consider checking 8 bytes at a time after some threshold?
// Maybe after seeing a few in a row that are ASCII, go back to fast mode?
int byte1 = 0;
- for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {
- }
+ for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {}
if (remaining == 0) {
return COMPLETE;
}
@@ -1891,40 +1844,32 @@ final class Utf8 {
}
}
- private static int unsafeIncompleteStateFor(byte[] bytes, int byte1, long offset,
- int remaining) {
+ private static int unsafeIncompleteStateFor(
+ byte[] bytes, int byte1, long offset, int remaining) {
switch (remaining) {
- case 0: {
+ case 0:
return incompleteStateFor(byte1);
- }
- case 1: {
+ case 1:
return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset));
- }
- case 2: {
- return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset),
- UnsafeUtil.getByte(bytes, offset + 1));
- }
- default: {
+ case 2:
+ return incompleteStateFor(
+ byte1, UnsafeUtil.getByte(bytes, offset), UnsafeUtil.getByte(bytes, offset + 1));
+ default:
throw new AssertionError();
- }
}
}
private static int unsafeIncompleteStateFor(long address, final int byte1, int remaining) {
switch (remaining) {
- case 0: {
+ case 0:
return incompleteStateFor(byte1);
- }
- case 1: {
+ case 1:
return incompleteStateFor(byte1, UnsafeUtil.getByte(address));
- }
- case 2: {
- return incompleteStateFor(byte1, UnsafeUtil.getByte(address),
- UnsafeUtil.getByte(address + 1));
- }
- default: {
+ case 2:
+ return incompleteStateFor(
+ byte1, UnsafeUtil.getByte(address), UnsafeUtil.getByte(address + 1));
+ default:
throw new AssertionError();
- }
}
}
}
@@ -1936,23 +1881,17 @@ final class Utf8 {
*/
private static class DecodeUtil {
- /**
- * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'.
- */
+ /** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */
private static boolean isOneByte(byte b) {
return b >= 0;
}
- /**
- * Returns whether this is a two-byte codepoint with the form '10XXXXXX'.
- */
+ /** Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */
private static boolean isTwoBytes(byte b) {
return b < (byte) 0xE0;
}
- /**
- * Returns whether this is a three-byte codepoint with the form '110XXXXX'.
- */
+ /** Returns whether this is a three-byte codepoint with the form '110XXXXX'. */
private static boolean isThreeBytes(byte b) {
return b < (byte) 0xF0;
}
@@ -1961,13 +1900,11 @@ final class Utf8 {
resultArr[resultPos] = (char) byte1;
}
- private static void handleTwoBytes(
- byte byte1, byte byte2, char[] resultArr, int resultPos)
+ private static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos)
throws InvalidProtocolBufferException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
- if (byte1 < (byte) 0xC2
- || isNotTrailingByte(byte2)) {
+ if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) {
throw InvalidProtocolBufferException.invalidUtf8();
}
resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2));
@@ -1984,13 +1921,14 @@ final class Utf8 {
|| isNotTrailingByte(byte3)) {
throw InvalidProtocolBufferException.invalidUtf8();
}
- resultArr[resultPos] = (char)
- (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
+ resultArr[resultPos] =
+ (char)
+ (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
}
private static void handleFourBytes(
byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos)
- throws InvalidProtocolBufferException{
+ throws InvalidProtocolBufferException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
@@ -2004,31 +1942,28 @@ final class Utf8 {
|| isNotTrailingByte(byte4)) {
throw InvalidProtocolBufferException.invalidUtf8();
}
- int codepoint = ((byte1 & 0x07) << 18)
- | (trailingByteValue(byte2) << 12)
- | (trailingByteValue(byte3) << 6)
- | trailingByteValue(byte4);
+ int codepoint =
+ ((byte1 & 0x07) << 18)
+ | (trailingByteValue(byte2) << 12)
+ | (trailingByteValue(byte3) << 6)
+ | trailingByteValue(byte4);
resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint);
resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint);
}
- /**
- * Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
- */
+ /** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */
private static boolean isNotTrailingByte(byte b) {
return b > (byte) 0xBF;
}
- /**
- * Returns the actual value of the trailing byte (removes the prefix '10') for composition.
- */
+ /** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */
private static int trailingByteValue(byte b) {
return b & 0x3F;
}
private static char highSurrogate(int codePoint) {
- return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))
- + (codePoint >>> 10));
+ return (char)
+ ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10));
}
private static char lowSurrogate(int codePoint) {
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 8b837ee5..3c6e8dda 100644
--- a/java/core/src/main/java/com/google/protobuf/WireFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/WireFormat.java
@@ -33,13 +33,12 @@ package com.google.protobuf;
import java.io.IOException;
/**
- * This class is used internally by the Protocol Buffer library and generated
- * message implementations. It is public only because those generated messages
- * do not reside in the {@code protobuf} package. Others should not use this
- * class directly.
+ * This class is used internally by the Protocol Buffer library and generated message
+ * implementations. It is public only because those generated messages do not reside in the {@code
+ * protobuf} package. Others should not use this class directly.
*
- * This class contains constants and helper functions useful for dealing with
- * the Protocol Buffer wire format.
+ * <p>This class contains constants and helper functions useful for dealing with the Protocol Buffer
+ * wire format.
*
* @author kenton@google.com Kenton Varda
*/
@@ -53,12 +52,12 @@ public final class WireFormat {
static final int MAX_VARINT64_SIZE = 10;
static final int MAX_VARINT_SIZE = 10;
- public static final int WIRETYPE_VARINT = 0;
- public static final int WIRETYPE_FIXED64 = 1;
+ public static final int WIRETYPE_VARINT = 0;
+ public static final int WIRETYPE_FIXED64 = 1;
public static final int WIRETYPE_LENGTH_DELIMITED = 2;
- public static final int WIRETYPE_START_GROUP = 3;
- public static final int WIRETYPE_END_GROUP = 4;
- public static final int WIRETYPE_FIXED32 = 5;
+ public static final int WIRETYPE_START_GROUP = 3;
+ public static final int WIRETYPE_END_GROUP = 4;
+ public static final int WIRETYPE_FIXED32 = 5;
static final int TAG_TYPE_BITS = 3;
static final int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1;
@@ -79,8 +78,8 @@ public final class WireFormat {
}
/**
- * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is
- * only here to support the lite runtime and should not be used by users.
+ * Lite equivalent to {@link Descriptors.FieldDescriptor.JavaType}. This is only here to support
+ * the lite runtime and should not be used by users.
*/
public enum JavaType {
INT(0),
@@ -97,10 +96,7 @@ public final class WireFormat {
this.defaultDefault = defaultDefault;
}
- /**
- * The default default value for fields of this type, if it's a primitive
- * type.
- */
+ /** The default default value for fields of this type, if it's a primitive type. */
Object getDefaultDefault() {
return defaultDefault;
}
@@ -109,44 +105,48 @@ public final class WireFormat {
}
/**
- * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is
- * only here to support the lite runtime and should not be used by users.
+ * Lite equivalent to {@link Descriptors.FieldDescriptor.Type}. This is only here to support the
+ * lite runtime and should not be used by users.
*/
public enum FieldType {
- DOUBLE (JavaType.DOUBLE , WIRETYPE_FIXED64 ),
- FLOAT (JavaType.FLOAT , WIRETYPE_FIXED32 ),
- INT64 (JavaType.LONG , WIRETYPE_VARINT ),
- UINT64 (JavaType.LONG , WIRETYPE_VARINT ),
- INT32 (JavaType.INT , WIRETYPE_VARINT ),
- FIXED64 (JavaType.LONG , WIRETYPE_FIXED64 ),
- FIXED32 (JavaType.INT , WIRETYPE_FIXED32 ),
- BOOL (JavaType.BOOLEAN , WIRETYPE_VARINT ),
- STRING (JavaType.STRING , WIRETYPE_LENGTH_DELIMITED) {
+ DOUBLE(JavaType.DOUBLE, WIRETYPE_FIXED64),
+ FLOAT(JavaType.FLOAT, WIRETYPE_FIXED32),
+ INT64(JavaType.LONG, WIRETYPE_VARINT),
+ UINT64(JavaType.LONG, WIRETYPE_VARINT),
+ INT32(JavaType.INT, WIRETYPE_VARINT),
+ FIXED64(JavaType.LONG, WIRETYPE_FIXED64),
+ FIXED32(JavaType.INT, WIRETYPE_FIXED32),
+ BOOL(JavaType.BOOLEAN, WIRETYPE_VARINT),
+ STRING(JavaType.STRING, WIRETYPE_LENGTH_DELIMITED) {
@Override
public boolean isPackable() {
- return false; }
+ return false;
+ }
},
- GROUP (JavaType.MESSAGE , WIRETYPE_START_GROUP ) {
+ GROUP(JavaType.MESSAGE, WIRETYPE_START_GROUP) {
@Override
public boolean isPackable() {
- return false; }
+ return false;
+ }
},
- MESSAGE (JavaType.MESSAGE , WIRETYPE_LENGTH_DELIMITED) {
+ MESSAGE(JavaType.MESSAGE, WIRETYPE_LENGTH_DELIMITED) {
@Override
public boolean isPackable() {
- return false; }
+ return false;
+ }
},
- BYTES (JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) {
+ BYTES(JavaType.BYTE_STRING, WIRETYPE_LENGTH_DELIMITED) {
@Override
public boolean isPackable() {
- return false; }
+ return false;
+ }
},
- UINT32 (JavaType.INT , WIRETYPE_VARINT ),
- ENUM (JavaType.ENUM , WIRETYPE_VARINT ),
- SFIXED32(JavaType.INT , WIRETYPE_FIXED32 ),
- SFIXED64(JavaType.LONG , WIRETYPE_FIXED64 ),
- SINT32 (JavaType.INT , WIRETYPE_VARINT ),
- SINT64 (JavaType.LONG , WIRETYPE_VARINT );
+ UINT32(JavaType.INT, WIRETYPE_VARINT),
+ ENUM(JavaType.ENUM, WIRETYPE_VARINT),
+ SFIXED32(JavaType.INT, WIRETYPE_FIXED32),
+ SFIXED64(JavaType.LONG, WIRETYPE_FIXED64),
+ SINT32(JavaType.INT, WIRETYPE_VARINT),
+ SINT64(JavaType.LONG, WIRETYPE_VARINT);
FieldType(final JavaType javaType, final int wireType) {
this.javaType = javaType;
@@ -156,30 +156,34 @@ public final class WireFormat {
private final JavaType javaType;
private final int wireType;
- public JavaType getJavaType() { return javaType; }
- public int getWireType() { return wireType; }
+ public JavaType getJavaType() {
+ return javaType;
+ }
- public boolean isPackable() { return true; }
+ public int getWireType() {
+ return wireType;
+ }
+
+ public boolean isPackable() {
+ return true;
+ }
}
// Field numbers for fields in MessageSet wire format.
- static final int MESSAGE_SET_ITEM = 1;
+ static final int MESSAGE_SET_ITEM = 1;
static final int MESSAGE_SET_TYPE_ID = 2;
static final int MESSAGE_SET_MESSAGE = 3;
// Tag numbers.
- static final int MESSAGE_SET_ITEM_TAG =
- makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP);
- static final int MESSAGE_SET_ITEM_END_TAG =
- makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP);
- static final int MESSAGE_SET_TYPE_ID_TAG =
- makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT);
+ static final int MESSAGE_SET_ITEM_TAG = makeTag(MESSAGE_SET_ITEM, WIRETYPE_START_GROUP);
+ static final int MESSAGE_SET_ITEM_END_TAG = makeTag(MESSAGE_SET_ITEM, WIRETYPE_END_GROUP);
+ static final int MESSAGE_SET_TYPE_ID_TAG = makeTag(MESSAGE_SET_TYPE_ID, WIRETYPE_VARINT);
static final int MESSAGE_SET_MESSAGE_TAG =
- makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED);
+ makeTag(MESSAGE_SET_MESSAGE, WIRETYPE_LENGTH_DELIMITED);
/**
- * Validation level for handling incoming string field data which potentially
- * contain non-UTF8 bytes.
+ * Validation level for handling incoming string field data which potentially contain non-UTF8
+ * bytes.
*/
enum Utf8Validation {
/** Eagerly parses to String; silently accepts invalid UTF8 bytes. */
@@ -209,54 +213,59 @@ public final class WireFormat {
}
/**
- * Read a field of any primitive type for immutable messages from a
- * CodedInputStream. Enums, groups, and embedded messages are not handled by
- * this method.
+ * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums,
+ * groups, and embedded messages are not handled by this method.
*
* @param input The stream from which to read.
* @param type Declared type of the field.
- * @param utf8Validation Different string UTF8 validation level for handling
- * string fields.
- * @return An object representing the field's value, of the exact
- * type which would be returned by
- * {@link Message#getField(Descriptors.FieldDescriptor)} for
- * this field.
+ * @param utf8Validation Different string UTF8 validation level for handling string fields.
+ * @return An object representing the field's value, of the exact type which would be returned by
+ * {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
*/
static Object readPrimitiveField(
- CodedInputStream input,
- FieldType type,
- Utf8Validation utf8Validation) throws IOException {
+ CodedInputStream input, FieldType type, Utf8Validation utf8Validation) throws IOException {
switch (type) {
- case DOUBLE : return input.readDouble ();
- case FLOAT : return input.readFloat ();
- case INT64 : return input.readInt64 ();
- case UINT64 : return input.readUInt64 ();
- case INT32 : return input.readInt32 ();
- case FIXED64 : return input.readFixed64 ();
- case FIXED32 : return input.readFixed32 ();
- case BOOL : return input.readBool ();
- case BYTES : return input.readBytes ();
- case UINT32 : return input.readUInt32 ();
- case SFIXED32: return input.readSFixed32();
- case SFIXED64: return input.readSFixed64();
- case SINT32 : return input.readSInt32 ();
- case SINT64 : return input.readSInt64 ();
+ case DOUBLE:
+ return input.readDouble();
+ case FLOAT:
+ return input.readFloat();
+ case INT64:
+ return input.readInt64();
+ case UINT64:
+ return input.readUInt64();
+ case INT32:
+ return input.readInt32();
+ case FIXED64:
+ return input.readFixed64();
+ case FIXED32:
+ return input.readFixed32();
+ case BOOL:
+ return input.readBool();
+ case BYTES:
+ return input.readBytes();
+ case UINT32:
+ return input.readUInt32();
+ case SFIXED32:
+ return input.readSFixed32();
+ case SFIXED64:
+ return input.readSFixed64();
+ case SINT32:
+ return input.readSInt32();
+ case SINT64:
+ return input.readSInt64();
- case STRING : return utf8Validation.readString(input);
+ case STRING:
+ return utf8Validation.readString(input);
case GROUP:
- throw new IllegalArgumentException(
- "readPrimitiveField() cannot handle nested groups.");
+ throw new IllegalArgumentException("readPrimitiveField() cannot handle nested groups.");
case MESSAGE:
- throw new IllegalArgumentException(
- "readPrimitiveField() cannot handle embedded messages.");
+ throw new IllegalArgumentException("readPrimitiveField() cannot handle embedded messages.");
case ENUM:
// We don't handle enums because we don't know what to do if the
// value is not recognized.
- throw new IllegalArgumentException(
- "readPrimitiveField() cannot handle enums.");
+ throw new IllegalArgumentException("readPrimitiveField() cannot handle enums.");
}
- throw new RuntimeException(
- "There is no way to get here, but the compiler thinks otherwise.");
+ throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
index cb2d34eb..1020c69c 100644
--- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
@@ -53,10 +53,9 @@ import junit.framework.TestCase;
*/
public class AbstractMessageTest extends TestCase {
/**
- * Extends AbstractMessage and wraps some other message object. The methods
- * of the Message interface which aren't explicitly implemented by
- * AbstractMessage are forwarded to the wrapped object. This allows us to
- * test that AbstractMessage's implementations work even if the wrapped
+ * Extends AbstractMessage and wraps some other message object. The methods of the Message
+ * interface which aren't explicitly implemented by AbstractMessage are forwarded to the wrapped
+ * object. This allows us to test that AbstractMessage's implementations work even if the wrapped
* object does not use them.
*/
private static class AbstractMessageWrapper extends AbstractMessage {
@@ -70,39 +69,47 @@ public class AbstractMessageTest extends TestCase {
public Descriptors.Descriptor getDescriptorForType() {
return wrappedMessage.getDescriptorForType();
}
+
@Override
public AbstractMessageWrapper getDefaultInstanceForType() {
- return new AbstractMessageWrapper(
- wrappedMessage.getDefaultInstanceForType());
+ return new AbstractMessageWrapper(wrappedMessage.getDefaultInstanceForType());
}
+
@Override
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedMessage.getAllFields();
}
+
@Override
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedMessage.hasField(field);
}
+
@Override
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedMessage.getField(field);
}
+
@Override
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedMessage.getRepeatedFieldCount(field);
}
+
@Override
public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) {
return wrappedMessage.getRepeatedField(field, index);
}
+
@Override
public UnknownFieldSet getUnknownFields() {
return wrappedMessage.getUnknownFields();
}
+
@Override
public Builder newBuilderForType() {
return new Builder(wrappedMessage.newBuilderForType());
}
+
@Override
public Builder toBuilder() {
return new Builder(wrappedMessage.toBuilder());
@@ -119,85 +126,103 @@ public class AbstractMessageTest extends TestCase {
public AbstractMessageWrapper build() {
return new AbstractMessageWrapper(wrappedBuilder.build());
}
+
@Override
public AbstractMessageWrapper buildPartial() {
return new AbstractMessageWrapper(wrappedBuilder.buildPartial());
}
+
@Override
public Builder clone() {
return new Builder(wrappedBuilder.clone());
}
+
@Override
public boolean isInitialized() {
return clone().buildPartial().isInitialized();
}
+
@Override
public Descriptors.Descriptor getDescriptorForType() {
return wrappedBuilder.getDescriptorForType();
}
+
@Override
public AbstractMessageWrapper getDefaultInstanceForType() {
- return new AbstractMessageWrapper(
- wrappedBuilder.getDefaultInstanceForType());
+ return new AbstractMessageWrapper(wrappedBuilder.getDefaultInstanceForType());
}
+
@Override
public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
return wrappedBuilder.getAllFields();
}
+
@Override
public Builder newBuilderForField(Descriptors.FieldDescriptor field) {
return new Builder(wrappedBuilder.newBuilderForField(field));
}
+
@Override
public boolean hasField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.hasField(field);
}
+
@Override
public Object getField(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getField(field);
}
+
@Override
public Builder setField(Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.setField(field, value);
return this;
}
+
@Override
public Builder clearField(Descriptors.FieldDescriptor field) {
wrappedBuilder.clearField(field);
return this;
}
+
@Override
public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
return wrappedBuilder.getRepeatedFieldCount(field);
}
+
@Override
public Object getRepeatedField(Descriptors.FieldDescriptor field, int index) {
return wrappedBuilder.getRepeatedField(field, index);
}
+
@Override
public Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value) {
wrappedBuilder.setRepeatedField(field, index, value);
return this;
}
+
@Override
public Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value) {
wrappedBuilder.addRepeatedField(field, value);
return this;
}
+
@Override
public UnknownFieldSet getUnknownFields() {
return wrappedBuilder.getUnknownFields();
}
+
@Override
public Builder setUnknownFields(UnknownFieldSet unknownFields) {
wrappedBuilder.setUnknownFields(unknownFields);
return this;
}
+
@Override
public Message.Builder getFieldBuilder(FieldDescriptor field) {
return wrappedBuilder.getFieldBuilder(field);
}
}
+
@Override
public Parser<? extends Message> getParserForType() {
return wrappedMessage.getParserForType();
@@ -207,24 +232,25 @@ public class AbstractMessageTest extends TestCase {
// =================================================================
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
- new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
- TestUtil.getExtensionRegistry());
+ new TestUtil.ReflectionTester(
+ TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
public void testClear() throws Exception {
AbstractMessageWrapper message =
- new AbstractMessageWrapper.Builder(
- TestAllTypes.newBuilder(TestUtil.getAllSet()))
- .clear().build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(TestUtil.getAllSet()))
+ .clear()
+ .build();
TestUtil.assertClear((TestAllTypes) message.wrappedMessage);
}
public void testCopy() throws Exception {
AbstractMessageWrapper message =
- new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
- .mergeFrom(TestUtil.getAllSet()).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
+ .mergeFrom(TestUtil.getAllSet())
+ .build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
@@ -232,25 +258,21 @@ public class AbstractMessageTest extends TestCase {
TestAllTypes message = TestUtil.getAllSet();
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
- assertEquals(message.getSerializedSize(),
- abstractMessage.getSerializedSize());
+ assertEquals(message.getSerializedSize(), abstractMessage.getSerializedSize());
}
public void testSerialization() throws Exception {
Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());
- TestUtil.assertAllFieldsSet(
- TestAllTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertAllFieldsSet(TestAllTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getAllSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getAllSet().toByteString(), abstractMessage.toByteString());
}
public void testParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
- AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
+ AbstractMessageWrapper message = builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
}
@@ -270,8 +292,8 @@ public class AbstractMessageTest extends TestCase {
}
// test DynamicMessage directly.
- Message.Builder dynamicMessageBuilder = DynamicMessage.newBuilder(
- TestRequiredForeign.getDescriptor());
+ Message.Builder dynamicMessageBuilder =
+ DynamicMessage.newBuilder(TestRequiredForeign.getDescriptor());
// mergeFrom() should not throw initialization error.
dynamicMessageBuilder.mergeFrom(bytes).buildPartial();
try {
@@ -283,65 +305,56 @@ public class AbstractMessageTest extends TestCase {
}
public void testPackedSerialization() throws Exception {
- Message abstractMessage =
- new AbstractMessageWrapper(TestUtil.getPackedSet());
+ Message abstractMessage = new AbstractMessageWrapper(TestUtil.getPackedSet());
- TestUtil.assertPackedFieldsSet(
- TestPackedTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertPackedFieldsSet(TestPackedTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getPackedSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getPackedSet().toByteString(), abstractMessage.toByteString());
}
public void testPackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedSerialization() throws Exception {
- Message abstractMessage =
- new AbstractMessageWrapper(TestUtil.getUnpackedSet());
+ Message abstractMessage = new AbstractMessageWrapper(TestUtil.getUnpackedSet());
- TestUtil.assertUnpackedFieldsSet(
- TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));
+ TestUtil.assertUnpackedFieldsSet(TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));
- assertEquals(TestUtil.getUnpackedSet().toByteString(),
- abstractMessage.toByteString());
+ assertEquals(TestUtil.getUnpackedSet().toByteString(), abstractMessage.toByteString());
}
public void testParsePackedToUnpacked() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
- TestUtil.assertUnpackedFieldsSet(
- (TestUnpackedTypes) message.wrappedMessage);
+ builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage);
}
public void testParseUnpackedToPacked() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
}
public void testUnpackedParsing() throws Exception {
AbstractMessageWrapper.Builder builder =
- new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
+ new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
AbstractMessageWrapper message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
- TestUtil.assertUnpackedFieldsSet(
- (TestUnpackedTypes) message.wrappedMessage);
+ builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ TestUtil.assertUnpackedFieldsSet((TestUnpackedTypes) message.wrappedMessage);
}
public void testOptimizedForSize() throws Exception {
// We're mostly only checking that this class was compiled successfully.
- TestOptimizedForSize message =
- TestOptimizedForSize.newBuilder().setI(1).build();
+ TestOptimizedForSize message = TestOptimizedForSize.newBuilder().setI(1).build();
message = TestOptimizedForSize.parseFrom(message.toByteString());
assertEquals(2, message.getSerializedSize());
}
@@ -351,8 +364,7 @@ public class AbstractMessageTest extends TestCase {
public void testIsInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
- AbstractMessageWrapper.Builder abstractBuilder =
- new AbstractMessageWrapper.Builder(builder);
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
assertFalse(abstractBuilder.isInitialized());
assertEquals("a, b, c", abstractBuilder.getInitializationErrorString());
@@ -369,8 +381,7 @@ public class AbstractMessageTest extends TestCase {
public void testForeignIsInitialized() throws Exception {
TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
- AbstractMessageWrapper.Builder abstractBuilder =
- new AbstractMessageWrapper.Builder(builder);
+ AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
assertTrue(abstractBuilder.isInitialized());
assertEquals("", abstractBuilder.getInitializationErrorString());
@@ -378,8 +389,7 @@ public class AbstractMessageTest extends TestCase {
builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
assertFalse(abstractBuilder.isInitialized());
assertEquals(
- "optional_message.b, optional_message.c",
- abstractBuilder.getInitializationErrorString());
+ "optional_message.b, optional_message.c", abstractBuilder.getInitializationErrorString());
builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
assertTrue(abstractBuilder.isInitialized());
@@ -400,36 +410,37 @@ public class AbstractMessageTest extends TestCase {
// Tests for mergeFrom
static final TestAllTypes MERGE_SOURCE =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .build();
static final TestAllTypes MERGE_DEST =
- TestAllTypes.newBuilder()
- .setOptionalInt64(2)
- .setOptionalString("baz")
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
- .addRepeatedString("qux")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt64(2)
+ .setOptionalString("baz")
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
+ .addRepeatedString("qux")
+ .build();
static final String MERGE_RESULT_TEXT =
- "optional_int32: 1\n" +
- "optional_int64: 2\n" +
- "optional_string: \"foo\"\n" +
- "optional_foreign_message {\n" +
- " c: 3\n" +
- "}\n" +
- "repeated_string: \"qux\"\n" +
- "repeated_string: \"bar\"\n";
+ ""
+ + "optional_int32: 1\n"
+ + "optional_int64: 2\n"
+ + "optional_string: \"foo\"\n"
+ + "optional_foreign_message {\n"
+ + " c: 3\n"
+ + "}\n"
+ + "repeated_string: \"qux\"\n"
+ + "repeated_string: \"bar\"\n";
public void testMergeFrom() throws Exception {
AbstractMessageWrapper result =
- new AbstractMessageWrapper.Builder(
- TestAllTypes.newBuilder(MERGE_DEST))
- .mergeFrom(MERGE_SOURCE).build();
+ new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(MERGE_DEST))
+ .mergeFrom(MERGE_SOURCE)
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -443,8 +454,10 @@ public class AbstractMessageTest extends TestCase {
TestAllTypes c = TestAllTypes.newBuilder(b).addRepeatedString("x").build();
TestAllTypes d = TestAllTypes.newBuilder(c).addRepeatedString("y").build();
TestAllExtensions e = TestUtil.getAllExtensionsSet();
- TestAllExtensions f = TestAllExtensions.newBuilder(e)
- .addExtension(UnittestProto.repeatedInt32Extension, 999).build();
+ TestAllExtensions f =
+ TestAllExtensions.newBuilder(e)
+ .addExtension(UnittestProto.repeatedInt32Extension, 999)
+ .build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
@@ -489,9 +502,7 @@ public class AbstractMessageTest extends TestCase {
checkEqualsIsConsistent(eUnknownFields, eUnknownFields2);
}
- /**
- * Asserts that the given proto has symmetric equals and hashCode methods.
- */
+ /** Asserts that the given proto has symmetric equals and hashCode methods. */
private void checkEqualsIsConsistent(Message message) {
// Object should be equal to itself.
assertEquals(message, message);
@@ -501,9 +512,7 @@ public class AbstractMessageTest extends TestCase {
checkEqualsIsConsistent(message, dynamic);
}
- /**
- * Asserts that the given protos are equal and have the same hash code.
- */
+ /** Asserts that the given protos are equal and have the same hash code. */
private void checkEqualsIsConsistent(Message message1, Message message2) {
assertEquals(message1, message2);
assertEquals(message2, message1);
@@ -513,9 +522,8 @@ public class AbstractMessageTest extends TestCase {
/**
* Asserts that the given protos are not equal and have different hash codes.
*
- * @warning It's valid for non-equal objects to have the same hash code, so
- * this test is stricter than it needs to be. However, this should happen
- * relatively rarely.
+ * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter
+ * than it needs to be. However, this should happen relatively rarely.
*/
private void checkNotEqual(Message m1, Message m2) {
String equalsError = String.format("%s should not be equal to %s", m1, m2);
@@ -535,7 +543,7 @@ public class AbstractMessageTest extends TestCase {
public void testCheckByteStringIsUtf8OnNonUtf8() {
ByteString byteString =
- ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte.
+ ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte.
try {
AbstractMessageLite.checkByteStringIsUtf8(byteString);
fail("Expected AbstractMessageLite.checkByteStringIsUtf8 to throw IllegalArgumentException");
@@ -543,5 +551,4 @@ public class AbstractMessageTest extends TestCase {
assertEquals("Byte string is not UTF-8.", exception.getMessage());
}
}
-
}
diff --git a/java/core/src/test/java/com/google/protobuf/AnyTest.java b/java/core/src/test/java/com/google/protobuf/AnyTest.java
index cf91ed91..2fe04a94 100644
--- a/java/core/src/test/java/com/google/protobuf/AnyTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AnyTest.java
@@ -32,7 +32,7 @@ package com.google.protobuf;
import any_test.AnyTestProto.TestAny;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
+import java.util.Objects;
import junit.framework.TestCase;
/**
@@ -56,7 +56,7 @@ public class AnyTest extends TestCase {
// Unpacking to a wrong type will throw an exception.
try {
- TestAny wrongMessage = container.getValue().unpack(TestAny.class);
+ container.getValue().unpack(TestAny.class);
fail("Exception is expected.");
} catch (InvalidProtocolBufferException e) {
// expected.
@@ -68,7 +68,7 @@ public class AnyTest extends TestCase {
ByteString.copyFrom(new byte[]{0x11}));
container = containerBuilder.build();
try {
- TestAllTypes parsingFailed = container.getValue().unpack(TestAllTypes.class);
+ container.getValue().unpack(TestAllTypes.class);
fail("Exception is expected.");
} catch (InvalidProtocolBufferException e) {
// expected.
@@ -132,6 +132,6 @@ public class AnyTest extends TestCase {
TestAllTypes result1 = container.getValue().unpack(TestAllTypes.class);
TestAllTypes result2 = container.getValue().unpack(TestAllTypes.class);
- assertTrue(result1 == result2);
+ assertTrue(Objects.equals(result1, result2));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
index 4906763c..8ef8edd2 100644
--- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
@@ -45,8 +45,7 @@ import junit.framework.TestCase;
*/
public class BooleanArrayListTest extends TestCase {
- private static final BooleanArrayList UNARY_LIST =
- newImmutableBooleanArrayList(true);
+ private static final BooleanArrayList UNARY_LIST = newImmutableBooleanArrayList(true);
private static final BooleanArrayList TERTIARY_LIST =
newImmutableBooleanArrayList(true, false, true);
@@ -78,10 +77,10 @@ public class BooleanArrayListTest extends TestCase {
list.addAll(asList(true, false, true, false));
Iterator<Boolean> iterator = list.iterator();
assertEquals(4, list.size());
- assertEquals(true, (boolean) list.get(0));
- assertEquals(true, (boolean) iterator.next());
+ assertTrue(list.get(0));
+ assertTrue(iterator.next());
list.set(0, true);
- assertEquals(false, (boolean) iterator.next());
+ assertFalse(iterator.next());
list.remove(0);
try {
@@ -102,9 +101,9 @@ public class BooleanArrayListTest extends TestCase {
}
public void testGet() {
- assertEquals(true, (boolean) TERTIARY_LIST.get(0));
- assertEquals(false, (boolean) TERTIARY_LIST.get(1));
- assertEquals(true, (boolean) TERTIARY_LIST.get(2));
+ assertTrue(TERTIARY_LIST.get(0));
+ assertFalse(TERTIARY_LIST.get(1));
+ assertTrue(TERTIARY_LIST.get(2));
try {
TERTIARY_LIST.get(-1);
@@ -122,9 +121,9 @@ public class BooleanArrayListTest extends TestCase {
}
public void testGetBoolean() {
- assertEquals(true, TERTIARY_LIST.getBoolean(0));
- assertEquals(false, TERTIARY_LIST.getBoolean(1));
- assertEquals(true, TERTIARY_LIST.getBoolean(2));
+ assertTrue(TERTIARY_LIST.getBoolean(0));
+ assertFalse(TERTIARY_LIST.getBoolean(1));
+ assertTrue(TERTIARY_LIST.getBoolean(2));
try {
TERTIARY_LIST.get(-1);
@@ -163,11 +162,11 @@ public class BooleanArrayListTest extends TestCase {
list.addBoolean(false);
list.addBoolean(false);
- assertEquals(false, (boolean) list.set(0, true));
- assertEquals(true, list.getBoolean(0));
+ assertFalse(list.set(0, true));
+ assertTrue(list.getBoolean(0));
- assertEquals(false, (boolean) list.set(1, false));
- assertEquals(false, list.getBoolean(1));
+ assertFalse(list.set(1, false));
+ assertFalse(list.getBoolean(1));
try {
list.set(-1, false);
@@ -188,11 +187,11 @@ public class BooleanArrayListTest extends TestCase {
list.addBoolean(true);
list.addBoolean(true);
- assertEquals(true, list.setBoolean(0, false));
- assertEquals(false, list.getBoolean(0));
+ assertTrue(list.setBoolean(0, false));
+ assertFalse(list.getBoolean(0));
- assertEquals(true, list.setBoolean(1, false));
- assertEquals(false, list.getBoolean(1));
+ assertTrue(list.setBoolean(1, false));
+ assertFalse(list.getBoolean(1));
try {
list.setBoolean(-1, false);
@@ -226,8 +225,7 @@ public class BooleanArrayListTest extends TestCase {
list.add(i % 2 == 0);
}
assertEquals(
- asList(false, true, false, false, true, true, false, true, false, true, false),
- list);
+ asList(false, true, false, false, true, true, false, true, false, true, false), list);
try {
list.add(-1, true);
@@ -257,8 +255,8 @@ public class BooleanArrayListTest extends TestCase {
assertTrue(list.addAll(Collections.singleton(true)));
assertEquals(1, list.size());
- assertEquals(true, (boolean) list.get(0));
- assertEquals(true, list.getBoolean(0));
+ assertTrue(list.get(0));
+ assertTrue(list.getBoolean(0));
assertTrue(list.addAll(asList(false, true, false, true, false)));
assertEquals(asList(true, false, true, false, true, false), list);
@@ -272,7 +270,7 @@ public class BooleanArrayListTest extends TestCase {
public void testRemove() {
list.addAll(TERTIARY_LIST);
- assertEquals(true, (boolean) list.remove(0));
+ assertTrue(list.remove(0));
assertEquals(asList(false, true), list);
assertTrue(list.remove(Boolean.TRUE));
@@ -281,7 +279,7 @@ public class BooleanArrayListTest extends TestCase {
assertFalse(list.remove(Boolean.TRUE));
assertEquals(asList(false), list);
- assertEquals(false, (boolean) list.remove(0));
+ assertFalse(list.remove(0));
assertEquals(asList(), list);
try {
@@ -312,7 +310,7 @@ public class BooleanArrayListTest extends TestCase {
assertEquals(0, toRemove.size());
}
- private void assertImmutable(BooleanArrayList list) {
+ private void assertImmutable(BooleanList list) {
try {
list.add(true);
diff --git a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
index db10ee74..654d62bc 100644
--- a/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
@@ -38,9 +38,9 @@ import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
/**
- * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString},
- * by inheriting the tests from {@link LiteralByteStringTest}. The only method which
- * is strange enough that it needs to be overridden here is {@link #testToString()}.
+ * This class tests {@link BoundedByteString}, which extends {@link LiteralByteString}, by
+ * inheriting the tests from {@link LiteralByteStringTest}. The only method which is strange enough
+ * that it needs to be overridden here is {@link #testToString()}.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -63,12 +63,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest {
String testString = "I love unicode \u1234\u5678 characters";
ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
ByteString chopped = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + ".substring() must have the expected type",
- classUnderTest, getActualClassName(chopped));
+ assertEquals(
+ classUnderTest + ".substring() must have the expected type",
+ classUnderTest,
+ getActualClassName(chopped));
String roundTripString = chopped.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString.substring(2, testString.length() - 6), roundTripString);
+ assertEquals(
+ classUnderTest + " unicode bytes must match",
+ testString.substring(2, testString.length() - 6),
+ roundTripString);
}
@Override
@@ -76,12 +80,16 @@ public class BoundedByteStringTest extends LiteralByteStringTest {
String testString = "I love unicode \u1234\u5678 characters";
ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
ByteString chopped = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + ".substring() must have the expected type",
- classUnderTest, getActualClassName(chopped));
+ assertEquals(
+ classUnderTest + ".substring() must have the expected type",
+ classUnderTest,
+ getActualClassName(chopped));
String roundTripString = chopped.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString.substring(2, testString.length() - 6), roundTripString);
+ assertEquals(
+ classUnderTest + " unicode bytes must match",
+ testString.substring(2, testString.length() - 6),
+ roundTripString);
}
@Override
diff --git a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
index 6b1cfe78..5f0ef620 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
@@ -37,9 +37,7 @@ import java.util.Arrays;
import java.util.Random;
import junit.framework.TestCase;
-/**
- * Tests for {@link ByteBufferWriter}.
- */
+/** Tests for {@link ByteBufferWriter}. */
public class ByteBufferWriterTest extends TestCase {
public void testHeapBuffer() throws IOException {
diff --git a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
index be71f1f5..83b343ad 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
@@ -41,6 +41,7 @@ import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
@@ -86,25 +87,61 @@ public class ByteStringTest extends TestCase {
return left.length == right.length && isArrayRange(left, right, 0, left.length);
}
+ public void testCompare_equalByteStrings_compareEqual() throws Exception {
+ byte[] referenceBytes = getTestBytes();
+ ByteString string1 = ByteString.copyFrom(referenceBytes);
+ ByteString string2 = ByteString.copyFrom(referenceBytes);
+
+ assertEquals(
+ "ByteString instances containing the same data must compare equal.",
+ 0,
+ ByteString.unsignedLexicographicalComparator().compare(string1, string2));
+ }
+
+ public void testCompare_byteStringsSortLexicographically() throws Exception {
+ ByteString app = ByteString.copyFromUtf8("app");
+ ByteString apple = ByteString.copyFromUtf8("apple");
+ ByteString banana = ByteString.copyFromUtf8("banana");
+
+ Comparator<ByteString> comparator = ByteString.unsignedLexicographicalComparator();
+
+ assertTrue("ByteString(app) < ByteString(apple)", comparator.compare(app, apple) < 0);
+ assertTrue("ByteString(app) < ByteString(banana)", comparator.compare(app, banana) < 0);
+ assertTrue("ByteString(apple) < ByteString(banana)", comparator.compare(apple, banana) < 0);
+ }
+
+ public void testCompare_interpretsByteValuesAsUnsigned() throws Exception {
+ // Two's compliment of `-1` == 0b11111111 == 255
+ ByteString twoHundredFiftyFive = ByteString.copyFrom(new byte[] {-1});
+ // 0b00000001 == 1
+ ByteString one = ByteString.copyFrom(new byte[] {1});
+
+ assertTrue(
+ "ByteString comparison treats bytes as unsigned values",
+ ByteString.unsignedLexicographicalComparator().compare(one, twoHundredFiftyFive) < 0);
+ }
+
public void testSubstring_BeginIndex() {
byte[] bytes = getTestBytes();
ByteString substring = ByteString.copyFrom(bytes).substring(500);
- assertTrue("substring must contain the tail of the string",
+ assertTrue(
+ "substring must contain the tail of the string",
isArrayRange(substring.toByteArray(), bytes, 500, bytes.length - 500));
}
public void testCopyFrom_BytesOffsetSize() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes, 500, 200);
- assertTrue("copyFrom sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
public void testCopyFrom_Bytes() {
byte[] bytes = getTestBytes();
ByteString byteString = ByteString.copyFrom(bytes);
- assertTrue("copyFrom must contain the expected bytes",
- isArray(byteString.toByteArray(), bytes));
+ assertTrue(
+ "copyFrom must contain the expected bytes", isArray(byteString.toByteArray(), bytes));
}
public void testCopyFrom_ByteBufferSize() {
@@ -113,7 +150,8 @@ public class ByteStringTest extends TestCase {
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer, 200);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, 200));
}
@@ -123,7 +161,8 @@ public class ByteStringTest extends TestCase {
byteBuffer.put(bytes);
byteBuffer.position(500);
ByteString byteString = ByteString.copyFrom(byteBuffer);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(byteString.toByteArray(), bytes, 500, bytes.length - 500));
}
@@ -131,7 +170,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFrom(testString, UTF_16);
byte[] testBytes = testString.getBytes(UTF_16);
- assertTrue("copyFrom string must respect the charset",
+ assertTrue(
+ "copyFrom string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
@@ -139,7 +179,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
ByteString byteString = ByteString.copyFromUtf8(testString);
byte[] testBytes = testString.getBytes(Internal.UTF_8);
- assertTrue("copyFromUtf8 string must respect the charset",
+ assertTrue(
+ "copyFromUtf8 string must respect the charset",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
}
@@ -148,17 +189,48 @@ public class ByteStringTest extends TestCase {
final List<ByteString> pieces = makeConcretePieces(testBytes);
// Call copyFrom() on a Collection
ByteString byteString = ByteString.copyFrom(pieces);
- assertTrue("copyFrom a List must contain the expected bytes",
+ assertTrue(
+ "copyFrom a List must contain the expected bytes",
isArrayRange(byteString.toByteArray(), testBytes, 0, testBytes.length));
// Call copyFrom on an iteration that's not a collection
- ByteString byteStringAlt = ByteString.copyFrom(new Iterable<ByteString>() {
- @Override
- public Iterator<ByteString> iterator() {
- return pieces.iterator();
- }
- });
- assertEquals("copyFrom from an Iteration must contain the expected bytes",
- byteString, byteStringAlt);
+ ByteString byteStringAlt =
+ ByteString.copyFrom(
+ new Iterable<ByteString>() {
+ @Override
+ public Iterator<ByteString> iterator() {
+ return pieces.iterator();
+ }
+ });
+ assertEquals(
+ "copyFrom from an Iteration must contain the expected bytes", byteString, byteStringAlt);
+ }
+
+ public void testCopyFrom_LengthTooBig() {
+ byte[] testBytes = getTestBytes(100);
+ try {
+ ByteString.copyFrom(testBytes, 0, 200);
+ fail("Should throw");
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ ByteString.copyFrom(testBytes, 99, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ ByteBuffer buf = ByteBuffer.wrap(testBytes);
+ try {
+ ByteString.copyFrom(buf, 101);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ ByteString.copyFrom(testBytes, -1, 10);
+ fail("Should throw");
+ } catch (IndexOutOfBoundsException expected) {
+ }
}
public void testCopyTo_TargetOffset() {
@@ -166,15 +238,17 @@ public class ByteStringTest extends TestCase {
ByteString byteString = ByteString.copyFrom(bytes);
byte[] target = new byte[bytes.length + 1000];
byteString.copyTo(target, 400);
- assertTrue("copyFrom byteBuffer sub-range must contain the expected bytes",
+ assertTrue(
+ "copyFrom byteBuffer sub-range must contain the expected bytes",
isArrayRange(bytes, target, 400, bytes.length));
}
public void testReadFrom_emptyStream() throws IOException {
- ByteString byteString =
- ByteString.readFrom(new ByteArrayInputStream(new byte[0]));
- assertSame("reading an empty stream must result in the EMPTY constant "
- + "byte string", ByteString.EMPTY, byteString);
+ ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(new byte[0]));
+ assertSame(
+ "reading an empty stream must result in the EMPTY constant byte string",
+ ByteString.EMPTY,
+ byteString);
}
public void testReadFrom_smallStream() throws IOException {
@@ -182,18 +256,18 @@ public class ByteStringTest extends TestCase {
}
public void testReadFrom_mutating() throws IOException {
- byte[] capturedArray = null;
EvilInputStream eis = new EvilInputStream();
ByteString byteString = ByteString.readFrom(eis);
+ byte[] capturedArray = eis.capturedArray;
- capturedArray = eis.capturedArray;
byte[] originalValue = byteString.toByteArray();
for (int x = 0; x < capturedArray.length; ++x) {
capturedArray[x] = (byte) 0;
}
byte[] newValue = byteString.toByteArray();
- assertTrue("copyFrom byteBuffer must not grant access to underlying array",
+ assertTrue(
+ "copyFrom byteBuffer must not grant access to underlying array",
Arrays.equals(originalValue, newValue));
}
@@ -255,8 +329,8 @@ public class ByteStringTest extends TestCase {
fail("readFrom must throw the underlying IOException");
} catch (IOException e) {
- assertEquals("readFrom must throw the expected exception",
- "synthetic failure", e.getMessage());
+ assertEquals(
+ "readFrom must throw the expected exception", "synthetic failure", e.getMessage());
}
}
@@ -266,7 +340,8 @@ public class ByteStringTest extends TestCase {
final byte[] data = getTestBytes(0x1000);
ByteString byteString = ByteString.readFrom(new ReluctantStream(data));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
// Same test as above, but with some specific chunk sizes.
@@ -281,11 +356,10 @@ public class ByteStringTest extends TestCase {
// Fails unless ByteString.readFrom reads the bytes correctly from a
// reluctant stream with the given chunkSize parameter.
- private void assertReadFromReluctantStream(byte[] bytes, int chunkSize)
- throws IOException {
+ private void assertReadFromReluctantStream(byte[] bytes, int chunkSize) throws IOException {
ByteString b = ByteString.readFrom(new ReluctantStream(bytes), chunkSize);
- assertTrue("readFrom byte stream must contain the expected bytes",
- isArray(b.toByteArray(), bytes));
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes", isArray(b.toByteArray(), bytes));
}
// Tests that ByteString.readFrom works with streams that implement
@@ -294,21 +368,23 @@ public class ByteStringTest extends TestCase {
final byte[] data = getTestBytes(0x1001);
ByteString byteString = ByteString.readFrom(new AvailableStream(data));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), data));
}
// Fails unless ByteString.readFrom reads the bytes correctly.
private void assertReadFrom(byte[] bytes) throws IOException {
- ByteString byteString =
- ByteString.readFrom(new ByteArrayInputStream(bytes));
- assertTrue("readFrom byte stream must contain the expected bytes",
+ ByteString byteString = ByteString.readFrom(new ByteArrayInputStream(bytes));
+ assertTrue(
+ "readFrom byte stream must contain the expected bytes",
isArray(byteString.toByteArray(), bytes));
}
// A stream that fails when read.
private static final class FailStream extends InputStream {
- @Override public int read() throws IOException {
+ @Override
+ public int read() throws IOException {
throw new IOException("synthetic failure");
}
}
@@ -323,7 +399,8 @@ public class ByteStringTest extends TestCase {
this.data = data;
}
- @Override public int read() {
+ @Override
+ public int read() {
if (pos == data.length) {
return -1;
} else {
@@ -331,11 +408,13 @@ public class ByteStringTest extends TestCase {
}
}
- @Override public int read(byte[] buf) {
+ @Override
+ public int read(byte[] buf) {
return read(buf, 0, buf.length);
}
- @Override public int read(byte[] buf, int offset, int size) {
+ @Override
+ public int read(byte[] buf, int offset, int size) {
if (pos == data.length) {
return -1;
}
@@ -352,7 +431,8 @@ public class ByteStringTest extends TestCase {
super(data);
}
- @Override public int available() {
+ @Override
+ public int available() {
return Math.min(250, data.length - pos);
}
}
@@ -402,8 +482,8 @@ public class ByteStringTest extends TestCase {
String testString = "I love unicode \u1234\u5678 characters";
byte[] testBytes = testString.getBytes(Internal.UTF_8);
ByteString byteString = ByteString.copyFrom(testBytes);
- assertEquals("copyToStringUtf8 must respect the charset",
- testString, byteString.toStringUtf8());
+ assertEquals(
+ "copyToStringUtf8 must respect the charset", testString, byteString.toStringUtf8());
}
public void testNewOutput_InitialCapacity() throws IOException {
@@ -421,8 +501,9 @@ public class ByteStringTest extends TestCase {
public void testNewOutput_ArrayWrite() {
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {128, 256, length / 2, length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
int[] writeSizes = {1, 4, 5, 7, 23, bytes.length};
for (int bufferSize : bufferSizes) {
@@ -433,7 +514,8 @@ public class ByteStringTest extends TestCase {
output.write(bytes, i, Math.min(writeSize, length - i));
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -444,16 +526,17 @@ public class ByteStringTest extends TestCase {
public void testNewOutput_WriteChar() {
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {0, 1, 128, 256, length / 2,
- length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
for (int bufferSize : bufferSizes) {
ByteString.Output output = ByteString.newOutput(bufferSize);
for (byte byteValue : bytes) {
output.write(byteValue);
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -464,9 +547,9 @@ public class ByteStringTest extends TestCase {
Random rng = new Random(1);
byte[] bytes = getTestBytes();
int length = bytes.length;
- int[] bufferSizes = {0, 1, 128, 256, length / 2,
- length - 1, length, length + 1,
- 2 * length, 3 * length};
+ int[] bufferSizes = {
+ 0, 1, 128, 256, length / 2, length - 1, length, length + 1, 2 * length, 3 * length
+ };
for (int bufferSize : bufferSizes) {
// Test writing the entire output using a mixture of write sizes and
@@ -483,12 +566,13 @@ public class ByteStringTest extends TestCase {
position++;
}
assertEquals("size() returns the right value", position, output.size());
- assertTrue("newOutput() substring must have correct bytes",
- isArrayRange(output.toByteString().toByteArray(),
- bytes, 0, position));
+ assertTrue(
+ "newOutput() substring must have correct bytes",
+ isArrayRange(output.toByteString().toByteArray(), bytes, 0, position));
}
ByteString byteString = output.toByteString();
- assertTrue("String built from newOutput() must contain the expected bytes",
+ assertTrue(
+ "String built from newOutput() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
}
@@ -509,7 +593,8 @@ public class ByteStringTest extends TestCase {
byte[] oldValue = byteString.toByteArray();
Arrays.fill(capturedArray, (byte) 0);
byte[] newValue = byteString.toByteArray();
- assertTrue("Output must not provide access to the underlying byte array",
+ assertTrue(
+ "Output must not provide access to the underlying byte array",
Arrays.equals(oldValue, newValue));
}
@@ -518,14 +603,15 @@ public class ByteStringTest extends TestCase {
ByteString.CodedBuilder builder = ByteString.newCodedBuilder(bytes.length);
builder.getCodedOutput().writeRawBytes(bytes);
ByteString byteString = builder.build();
- assertTrue("String built from newCodedBuilder() must contain the expected bytes",
+ assertTrue(
+ "String built from newCodedBuilder() must contain the expected bytes",
isArrayRange(bytes, byteString.toByteArray(), 0, bytes.length));
}
public void testSubstringParity() {
byte[] bigBytes = getTestBytes(2048 * 1024, 113344L);
int start = 512 * 1024 - 3333;
- int end = 512 * 1024 + 7777;
+ int end = 512 * 1024 + 7777;
ByteString concreteSubstring = ByteString.copyFrom(bigBytes).substring(start, end);
boolean ok = true;
for (int i = start; ok && i < end; ++i) {
@@ -534,10 +620,11 @@ public class ByteStringTest extends TestCase {
assertTrue("Concrete substring didn't capture the right bytes", ok);
ByteString literalString = ByteString.copyFrom(bigBytes, start, end - start);
- assertTrue("Substring must be equal to literal string",
- concreteSubstring.equals(literalString));
- assertEquals("Substring must have same hashcode as literal string",
- literalString.hashCode(), concreteSubstring.hashCode());
+ assertEquals("Substring must be equal to literal string", literalString, concreteSubstring);
+ assertEquals(
+ "Substring must have same hashcode as literal string",
+ literalString.hashCode(),
+ concreteSubstring.hashCode());
}
public void testCompositeSubstring() {
@@ -563,15 +650,22 @@ public class ByteStringTest extends TestCase {
assertTrue("Substring must support byteAt() correctly", stillEqual);
ByteString literalSubstring = ByteString.copyFrom(referenceBytes, from, to - from);
- assertTrue("Composite substring must equal a literal substring over the same bytes",
- compositeSubstring.equals(literalSubstring));
- assertTrue("Literal substring must equal a composite substring over the same bytes",
- literalSubstring.equals(compositeSubstring));
-
- assertEquals("We must get the same hashcodes for composite and literal substrings",
- literalSubstring.hashCode(), compositeSubstring.hashCode());
-
- assertFalse("We can't be equal to a proper substring",
+ assertEquals(
+ "Composite substring must equal a literal substring over the same bytes",
+ literalSubstring,
+ compositeSubstring);
+ assertEquals(
+ "Literal substring must equal a composite substring over the same bytes",
+ compositeSubstring,
+ literalSubstring);
+
+ assertEquals(
+ "We must get the same hashcodes for composite and literal substrings",
+ literalSubstring.hashCode(),
+ compositeSubstring.hashCode());
+
+ assertFalse(
+ "We can't be equal to a proper substring",
compositeSubstring.equals(literalSubstring.substring(0, literalSubstring.size() - 1)));
}
@@ -582,10 +676,11 @@ public class ByteStringTest extends TestCase {
List<ByteString> pieces = makeConcretePieces(referenceBytes);
ByteString listString = ByteString.copyFrom(pieces);
- assertTrue("Composite string must be equal to literal string",
- listString.equals(literalString));
- assertEquals("Composite string must have same hashcode as literal string",
- literalString.hashCode(), listString.hashCode());
+ assertEquals("Composite string must be equal to literal string", literalString, listString);
+ assertEquals(
+ "Composite string must have same hashcode as literal string",
+ literalString.hashCode(),
+ listString.hashCode());
}
public void testConcat() {
@@ -600,30 +695,34 @@ public class ByteStringTest extends TestCase {
concatenatedString = concatenatedString.concat(iter.next());
}
- assertTrue("Concatenated string must be equal to literal string",
- concatenatedString.equals(literalString));
- assertEquals("Concatenated string must have same hashcode as literal string",
- literalString.hashCode(), concatenatedString.hashCode());
+ assertEquals(
+ "Concatenated string must be equal to literal string", literalString, concatenatedString);
+ assertEquals(
+ "Concatenated string must have same hashcode as literal string",
+ literalString.hashCode(),
+ concatenatedString.hashCode());
}
/**
- * Test the Rope implementation can deal with Empty nodes, even though we
- * guard against them. See also {@link LiteralByteStringTest#testConcat_empty()}.
+ * Test the Rope implementation can deal with Empty nodes, even though we guard against them. See
+ * also {@link LiteralByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
byte[] referenceBytes = getTestBytes(7748, 113344L);
ByteString literalString = ByteString.copyFrom(referenceBytes);
ByteString duo = RopeByteString.newInstanceForTest(literalString, literalString);
- ByteString temp = RopeByteString.newInstanceForTest(
- RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString));
+ ByteString temp =
+ RopeByteString.newInstanceForTest(
+ RopeByteString.newInstanceForTest(literalString, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, literalString));
ByteString quintet = RopeByteString.newInstanceForTest(temp, ByteString.EMPTY);
- assertTrue("String with concatenated nulls must equal simple concatenate",
- duo.equals(quintet));
- assertEquals("String with concatenated nulls have same hashcode as simple concatenate",
- duo.hashCode(), quintet.hashCode());
+ assertEquals("String with concatenated nulls must equal simple concatenate", quintet, duo);
+ assertEquals(
+ "String with concatenated nulls have same hashcode as simple concatenate",
+ duo.hashCode(),
+ quintet.hashCode());
ByteString.ByteIterator duoIter = duo.iterator();
ByteString.ByteIterator quintetIter = quintet.iterator();
@@ -653,11 +752,13 @@ public class ByteStringTest extends TestCase {
// It is possible, using the testing factory method to create deeply nested
// trees of empty leaves, to make a string that will fail this test.
for (int i = 1; i < duo.size(); ++i) {
- assertTrue("Substrings of size() < 2 must not be RopeByteStrings",
+ assertTrue(
+ "Substrings of size() < 2 must not be RopeByteStrings",
duo.substring(i - 1, i) instanceof ByteString.LeafByteString);
}
for (int i = 1; i < quintet.size(); ++i) {
- assertTrue("Substrings of size() < 2 must not be RopeByteStrings",
+ assertTrue(
+ "Substrings of size() < 2 must not be RopeByteStrings",
quintet.substring(i - 1, i) instanceof ByteString.LeafByteString);
}
}
@@ -706,8 +807,7 @@ public class ByteStringTest extends TestCase {
return pieces;
}
- private byte[] substringUsingWriteTo(
- ByteString data, int offset, int length) throws IOException {
+ private byte[] substringUsingWriteTo(ByteString data, int offset, int length) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
data.writeTo(output, offset, length);
return output.toByteArray();
@@ -718,9 +818,7 @@ public class ByteStringTest extends TestCase {
// won't be merged into one byte array due to some optimizations.
final int dataSize = ByteString.CONCATENATE_BY_COPY_SIZE + 1;
byte[] data1 = new byte[dataSize];
- for (int i = 0; i < data1.length; i++) {
- data1[i] = (byte) 1;
- }
+ Arrays.fill(data1, (byte) 1);
data1[1] = (byte) 11;
// Test LiteralByteString.writeTo(OutputStream,int,int)
ByteString left = ByteString.wrap(data1);
@@ -729,9 +827,7 @@ public class ByteStringTest extends TestCase {
assertEquals((byte) 11, result[0]);
byte[] data2 = new byte[dataSize];
- for (int i = 0; i < data1.length; i++) {
- data2[i] = (byte) 2;
- }
+ Arrays.fill(data2, 0, data1.length, (byte) 2);
ByteString right = ByteString.wrap(data2);
// Concatenate two ByteStrings to create a RopeByteString.
ByteString root = left.concat(right);
@@ -756,11 +852,12 @@ public class ByteStringTest extends TestCase {
assertEquals((byte) 2, result[dataSize - dataSize / 2]);
assertEquals((byte) 2, result[dataSize - 1]);
}
-
- /**
- * Tests ByteString uses Arrays based byte copier when running under Hotstop VM.
- */
+
+ /** Tests ByteString uses Arrays based byte copier when running under Hotstop VM. */
public void testByteArrayCopier() throws Exception {
+ if (Android.isOnAndroidDevice()) {
+ return;
+ }
Field field = ByteString.class.getDeclaredField("byteArrayCopier");
field.setAccessible(true);
Object byteArrayCopier = field.get(null);
diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
index 50b87ae3..e276225e 100644
--- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
+++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
@@ -38,22 +38,21 @@ import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
/**
- * Test that protos generated with file option java_string_check_utf8 do in
- * fact perform appropriate UTF-8 checks.
+ * Test that protos generated with file option java_string_check_utf8 do in fact perform appropriate
+ * UTF-8 checks.
*
* @author jbaum@google.com (Jacob Butcher)
*/
public class CheckUtf8Test extends TestCase {
private static final String UTF8_BYTE_STRING_TEXT = "some text";
- private static final ByteString UTF8_BYTE_STRING =
- ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT);
+ private static final ByteString UTF8_BYTE_STRING = ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT);
private static final ByteString NON_UTF8_BYTE_STRING =
- ByteString.copyFrom(new byte[]{(byte) 0x80}); // A lone continuation byte.
+ ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte.
public void testBuildRequiredStringWithGoodUtf8() throws Exception {
- assertEquals(UTF8_BYTE_STRING_TEXT,
- StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq());
+ assertEquals(
+ UTF8_BYTE_STRING_TEXT, StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq());
}
public void testParseRequiredStringWithGoodUtf8() throws Exception {
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 5ea6b79c..f64df334 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
@@ -699,7 +699,7 @@ public class CodedInputStreamTest extends TestCase {
}
assertEquals(true, input.isAtEnd());
} catch (Exception e) {
- fail("Catch exception in the testIsAtEnd");
+ throw new AssertionError("Catch exception in the testIsAtEnd", e);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
index 78f415c2..8dc3e4ce 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
@@ -257,13 +257,27 @@ public class CodedOutputStreamTest extends TestCase {
// 41256202580718336
assertWriteVarint(
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));
+ (0x00 << 0)
+ | (0x66 << 7)
+ | (0x6b << 14)
+ | (0x1c << 21)
+ | (0x43L << 28)
+ | (0x49L << 35)
+ | (0x24L << 42)
+ | (0x49L << 49));
// 11964378330978735131
assertWriteVarint(
bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
- (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bL << 28) | (0x56L << 35)
- | (0x00L << 42) | (0x05L << 49) | (0x26L << 56) | (0x01L << 63));
+ (0x1b << 0)
+ | (0x28 << 7)
+ | (0x79 << 14)
+ | (0x42 << 21)
+ | (0x3bL << 28)
+ | (0x56L << 35)
+ | (0x00L << 42)
+ | (0x05L << 49)
+ | (0x26L << 56)
+ | (0x01L << 63));
}
/** Tests writeRawLittleEndian32() and writeRawLittleEndian64(). */
@@ -344,8 +358,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Tests writing a whole message with every packed field type. Ensures the
- * wire format of packed fields is compatible with C++.
+ * Tests writing a whole message with every packed field type. Ensures the wire format of packed
+ * fields is compatible with C++.
*/
public void testWriteWholePackedFieldsMessage() throws Exception {
byte[] expectedBytes = TestUtil.getGoldenPackedFieldsMessage().toByteArray();
@@ -361,8 +375,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Test writing a message containing a negative enum value. This used to
- * fail because the size was not properly computed as a sign-extended varint.
+ * Test writing a message containing a negative enum value. This used to fail because the size was
+ * not properly computed as a sign-extended varint.
*/
public void testWriteMessageWithNegativeEnumValue() throws Exception {
SparseEnumMessage message =
@@ -394,8 +408,9 @@ public class CodedOutputStreamTest extends TestCase {
String string =
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
// Ensure we take the slower fast path.
- assertTrue(CodedOutputStream.computeUInt32SizeNoTag(string.length())
- != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
+ assertTrue(
+ CodedOutputStream.computeUInt32SizeNoTag(string.length())
+ != CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
coder.stream().writeStringNoTag(string);
coder.stream().flush();
@@ -438,9 +453,7 @@ public class CodedOutputStreamTest extends TestCase {
}
final int length2 = 8 * 1024;
byte[] data = new byte[length2];
- for (int i = 0; i < length2; i++) {
- data[i] = (byte) 2;
- }
+ Arrays.fill(data, 0, length2, (byte) 2);
codedStream.writeRawBytes(data);
final int length3 = bufferSize - length1 - length2;
for (int i = 0; i < length3; i++) {
@@ -521,10 +534,14 @@ public class CodedOutputStreamTest extends TestCase {
}
public void testSerializeInvalidUtf8() throws Exception {
- String[] invalidStrings = new String[] {newString(Character.MIN_HIGH_SURROGATE),
- "foobar" + newString(Character.MIN_HIGH_SURROGATE), newString(Character.MIN_LOW_SURROGATE),
- "foobar" + newString(Character.MIN_LOW_SURROGATE),
- newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)};
+ String[] invalidStrings =
+ new String[] {
+ newString(Character.MIN_HIGH_SURROGATE),
+ "foobar" + newString(Character.MIN_HIGH_SURROGATE),
+ newString(Character.MIN_LOW_SURROGATE),
+ "foobar" + newString(Character.MIN_LOW_SURROGATE),
+ newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)
+ };
CodedOutputStream outputWithStream = CodedOutputStream.newInstance(new ByteArrayOutputStream());
CodedOutputStream outputWithArray = CodedOutputStream.newInstance(new byte[10000]);
@@ -562,7 +579,7 @@ public class CodedOutputStreamTest extends TestCase {
}
}
- /** Regression test for https://github.com/google/protobuf/issues/292 */
+ /** Regression test for https://github.com/protocolbuffers/protobuf/issues/292 */
public void testCorrectExceptionThrowWhenEncodingStringsWithoutEnoughSpace() throws Exception {
String testCase = "Foooooooo";
assertEquals(
@@ -594,16 +611,17 @@ public class CodedOutputStreamTest extends TestCase {
// with ASCII and Unicode characters requiring different UTF-8 byte counts per
// char, hence causing the length delimiter varint to sometimes require more
// bytes for the Unicode strings than the ASCII string of the same length.
- int[] lengths = new int[] {
- 0,
- 1,
- (1 << 4) - 1, // 1 byte for ASCII and Unicode
- (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode
- (1 << 11) - 1, // 2 bytes for ASCII and Unicode
- (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode
- (1 << 17) - 1,
- // 3 bytes for ASCII and Unicode
- };
+ int[] lengths =
+ new int[] {
+ 0,
+ 1,
+ (1 << 4) - 1, // 1 byte for ASCII and Unicode
+ (1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode
+ (1 << 11) - 1, // 2 bytes for ASCII and Unicode
+ (1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode
+ (1 << 17) - 1,
+ // 3 bytes for ASCII and Unicode
+ };
for (OutputType outputType : OutputType.values()) {
for (int i : lengths) {
testEncodingOfString(outputType, 'q', i); // 1 byte per char
@@ -626,8 +644,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Parses the given bytes using writeRawLittleEndian32() and checks
- * that the result matches the given value.
+ * Parses the given bytes using writeRawLittleEndian32() and checks that the result matches the
+ * given value.
*/
private static void assertWriteLittleEndian32(byte[] data, int value) throws Exception {
for (OutputType outputType : OutputType.values()) {
@@ -647,8 +665,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Parses the given bytes using writeRawLittleEndian64() and checks
- * that the result matches the given value.
+ * Parses the given bytes using writeRawLittleEndian64() and checks that the result matches the
+ * given value.
*/
private static void assertWriteLittleEndian64(byte[] data, long value) throws Exception {
for (OutputType outputType : OutputType.values()) {
@@ -691,9 +709,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * 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.
+ * 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.
*/
private static byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
@@ -703,7 +720,7 @@ public class CodedOutputStreamTest extends TestCase {
return bytes;
}
- /** Arrays.asList() does not work with arrays of primitives. :( */
+ /** Arrays.asList() does not work with arrays of primitives. :( */
private static List<Byte> toList(byte[] bytes) {
List<Byte> result = new ArrayList<Byte>();
for (byte b : bytes) {
@@ -717,8 +734,8 @@ public class CodedOutputStreamTest extends TestCase {
}
/**
- * Writes the given value using writeRawVarint32() and writeRawVarint64() and
- * checks that the result matches the given bytes.
+ * Writes the given value using writeRawVarint32() and writeRawVarint64() and checks that the
+ * result matches the given bytes.
*/
private static void assertWriteVarint(byte[] data, long value) throws Exception {
for (OutputType outputType : OutputType.values()) {
diff --git a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
index 9c0997c4..2addde84 100644
--- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
@@ -41,35 +41,28 @@ import junit.framework.TestCase;
* @author birdo@google.com (Roberto Scaramuzzi)
*/
public class DeprecatedFieldTest extends TestCase {
- private String[] deprecatedGetterNames = {
- "hasDeprecatedInt32",
- "getDeprecatedInt32"};
+ private String[] deprecatedGetterNames = {"hasDeprecatedInt32", "getDeprecatedInt32"};
private String[] deprecatedBuilderGetterNames = {
- "hasDeprecatedInt32",
- "getDeprecatedInt32",
- "clearDeprecatedInt32"};
+ "hasDeprecatedInt32", "getDeprecatedInt32", "clearDeprecatedInt32"
+ };
- private String[] deprecatedBuilderSetterNames = {
- "setDeprecatedInt32"};
+ private String[] deprecatedBuilderSetterNames = {"setDeprecatedInt32"};
public void testDeprecatedField() throws Exception {
Class<?> deprecatedFields = TestDeprecatedFields.class;
Class<?> deprecatedFieldsBuilder = TestDeprecatedFields.Builder.class;
for (String name : deprecatedGetterNames) {
Method method = deprecatedFields.getMethod(name);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
for (String name : deprecatedBuilderGetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
for (String name : deprecatedBuilderSetterNames) {
Method method = deprecatedFieldsBuilder.getMethod(name, int.class);
- assertTrue("Method " + name + " should be deprecated",
- isDeprecated(method));
+ assertTrue("Method " + name + " should be deprecated", isDeprecated(method));
}
}
@@ -77,8 +70,7 @@ public class DeprecatedFieldTest extends TestCase {
Class<?> oneofCase = TestDeprecatedFields.OneofFieldsCase.class;
String name = "DEPRECATED_INT32_IN_ONEOF";
java.lang.reflect.Field enumValue = oneofCase.getField(name);
- assertTrue("Enum value " + name + " should be deprecated.",
- isDeprecated(enumValue));
+ assertTrue("Enum value " + name + " should be deprecated.", isDeprecated(enumValue));
}
private boolean isDeprecated(AnnotatedElement annotated) {
diff --git a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
index 0f09a51b..01a96ba5 100644
--- a/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
@@ -43,15 +43,13 @@ import org.junit.runners.JUnit4;
public class DiscardUnknownFieldsTest {
@Test
public void testProto2() throws Exception {
+ testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
+ testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
testProto2Message(
- UnittestProto.TestEmptyMessage.getDefaultInstance());
+ DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
testProto2Message(
- UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
- testProto2Message(
- DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
- testProto2Message(
- DynamicMessage.getDefaultInstance(
- UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
+ DynamicMessage.getDefaultInstance(
+ UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
}
@Test
@@ -62,22 +60,17 @@ public class DiscardUnknownFieldsTest {
}
private static void testProto2Message(Message message) throws Exception {
- assertUnknownFieldsDefaultPreserved(message);
+ assertUnknownFieldsPreserved(message);
assertUnknownFieldsExplicitlyDiscarded(message);
assertReuseCodedInputStreamPreserve(message);
assertUnknownFieldsInUnknownFieldSetArePreserve(message);
}
private static void testProto3Message(Message message) throws Exception {
- CodedInputStream.setProto3KeepUnknownsByDefaultForTest();
- assertUnknownFieldsDefaultPreserved(message);
+ assertUnknownFieldsPreserved(message);
assertUnknownFieldsExplicitlyDiscarded(message);
assertReuseCodedInputStreamPreserve(message);
assertUnknownFieldsInUnknownFieldSetArePreserve(message);
- CodedInputStream.setProto3DiscardUnknownsByDefaultForTest();
- assertUnknownFieldsDefaultDiscarded(message);
- assertUnknownFieldsExplicitlyDiscarded(message);
- assertUnknownFieldsInUnknownFieldSetAreDiscarded(message);
}
private static void assertReuseCodedInputStreamPreserve(Message message) throws Exception {
@@ -86,18 +79,16 @@ public class DiscardUnknownFieldsTest {
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());
- }
+
+ // 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.
+ parsed = message.getParserForType().parseFrom(input);
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
}
/**
@@ -109,46 +100,18 @@ public class DiscardUnknownFieldsTest {
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());
- }
+ private static void assertUnknownFieldsPreserved(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(), 0, parsed.getSerializedSize());
- }
+ parsed = message.newBuilderForType().mergeFrom(payload).build();
+ assertEquals(message.getClass().getName(), payload, parsed.toByteString());
}
private static void assertUnknownFieldsExplicitlyDiscarded(Message message) throws Exception {
- Message parsed =
- DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload);
+ Message parsed = DiscardUnknownFieldsParser.wrap(message.getParserForType()).parseFrom(payload);
assertEquals(message.getClass().getName(), 0, parsed.getSerializedSize());
}
diff --git a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
index 923d7f43..6a942121 100644
--- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class DoubleArrayListTest extends TestCase {
- private static final DoubleArrayList UNARY_LIST =
- newImmutableDoubleArrayList(1);
- private static final DoubleArrayList TERTIARY_LIST =
- newImmutableDoubleArrayList(1, 2, 3);
+ private static final DoubleArrayList UNARY_LIST = newImmutableDoubleArrayList(1);
+ private static final DoubleArrayList TERTIARY_LIST = newImmutableDoubleArrayList(1, 2, 3);
private DoubleArrayList list;
@@ -78,10 +76,10 @@ public class DoubleArrayListTest extends TestCase {
list.addAll(asList(1D, 2D, 3D, 4D));
Iterator<Double> iterator = list.iterator();
assertEquals(4, list.size());
- assertEquals(1D, (double) list.get(0));
- assertEquals(1D, (double) iterator.next());
+ assertEquals(1D, (double) list.get(0), 0.0);
+ assertEquals(1D, (double) iterator.next(), 0.0);
list.set(0, 1D);
- assertEquals(2D, (double) iterator.next());
+ assertEquals(2D, (double) iterator.next(), 0.0);
list.remove(0);
try {
@@ -102,9 +100,9 @@ public class DoubleArrayListTest extends TestCase {
}
public void testGet() {
- assertEquals(1D, (double) TERTIARY_LIST.get(0));
- assertEquals(2D, (double) TERTIARY_LIST.get(1));
- assertEquals(3D, (double) TERTIARY_LIST.get(2));
+ assertEquals(1D, (double) TERTIARY_LIST.get(0), 0.0);
+ assertEquals(2D, (double) TERTIARY_LIST.get(1), 0.0);
+ assertEquals(3D, (double) TERTIARY_LIST.get(2), 0.0);
try {
TERTIARY_LIST.get(-1);
@@ -122,9 +120,9 @@ public class DoubleArrayListTest extends TestCase {
}
public void testGetDouble() {
- assertEquals(1D, TERTIARY_LIST.getDouble(0));
- assertEquals(2D, TERTIARY_LIST.getDouble(1));
- assertEquals(3D, TERTIARY_LIST.getDouble(2));
+ assertEquals(1D, TERTIARY_LIST.getDouble(0), 0.0);
+ assertEquals(2D, TERTIARY_LIST.getDouble(1), 0.0);
+ assertEquals(3D, TERTIARY_LIST.getDouble(2), 0.0);
try {
TERTIARY_LIST.get(-1);
@@ -163,11 +161,11 @@ public class DoubleArrayListTest extends TestCase {
list.addDouble(2);
list.addDouble(4);
- assertEquals(2D, (double) list.set(0, 3D));
- assertEquals(3D, list.getDouble(0));
+ assertEquals(2D, (double) list.set(0, 3D), 0.0);
+ assertEquals(3D, list.getDouble(0), 0.0);
- assertEquals(4D, (double) list.set(1, 0D));
- assertEquals(0D, list.getDouble(1));
+ assertEquals(4D, (double) list.set(1, 0D), 0.0);
+ assertEquals(0D, list.getDouble(1), 0.0);
try {
list.set(-1, 0D);
@@ -188,11 +186,11 @@ public class DoubleArrayListTest extends TestCase {
list.addDouble(1);
list.addDouble(3);
- assertEquals(1D, list.setDouble(0, 0));
- assertEquals(0D, list.getDouble(0));
+ assertEquals(1D, list.setDouble(0, 0), 0.0);
+ assertEquals(0D, list.getDouble(0), 0.0);
- assertEquals(3D, list.setDouble(1, 0));
- assertEquals(0D, list.getDouble(1));
+ assertEquals(3D, list.setDouble(1, 0), 0.0);
+ assertEquals(0D, list.getDouble(1), 0.0);
try {
list.setDouble(-1, 0);
@@ -225,9 +223,7 @@ public class DoubleArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Double.valueOf(5 + i));
}
- assertEquals(
- asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D),
- list);
+ assertEquals(asList(0D, 1D, 4D, 2D, 3D, 5D, 6D, 7D, 8D, 9D, 10D), list);
try {
list.add(-1, 5D);
@@ -257,8 +253,8 @@ public class DoubleArrayListTest extends TestCase {
assertTrue(list.addAll(Collections.singleton(1D)));
assertEquals(1, list.size());
- assertEquals(1D, (double) list.get(0));
- assertEquals(1D, list.getDouble(0));
+ assertEquals(1D, (double) list.get(0), 0.0);
+ assertEquals(1D, list.getDouble(0), 0.0);
assertTrue(list.addAll(asList(2D, 3D, 4D, 5D, 6D)));
assertEquals(asList(1D, 2D, 3D, 4D, 5D, 6D), list);
@@ -272,7 +268,7 @@ public class DoubleArrayListTest extends TestCase {
public void testRemove() {
list.addAll(TERTIARY_LIST);
- assertEquals(1D, (double) list.remove(0));
+ assertEquals(1D, (double) list.remove(0), 0.0);
assertEquals(asList(2D, 3D), list);
assertTrue(list.remove(Double.valueOf(3)));
@@ -281,7 +277,7 @@ public class DoubleArrayListTest extends TestCase {
assertFalse(list.remove(Double.valueOf(3)));
assertEquals(asList(2D), list);
- assertEquals(2D, (double) list.remove(0));
+ assertEquals(2D, (double) list.remove(0), 0.0);
assertEquals(asList(), list);
try {
@@ -312,7 +308,7 @@ public class DoubleArrayListTest extends TestCase {
assertEquals(0, toRemove.size());
}
- private void assertImmutable(DoubleArrayList list) {
+ private void assertImmutable(DoubleList list) {
if (list.contains(1D)) {
throw new RuntimeException("Cannot test the immutability of lists that contain 1.");
}
diff --git a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
index 77d14f6b..0514241a 100644
--- a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
@@ -41,32 +41,30 @@ import java.util.Arrays;
import junit.framework.TestCase;
/**
- * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which
- * tests some {@link DynamicMessage} functionality.
+ * Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which tests some {@link
+ * DynamicMessage} functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class DynamicMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
TestUtil.ReflectionTester extensionsReflectionTester =
- new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
- TestUtil.getExtensionRegistry());
+ new TestUtil.ReflectionTester(
+ TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
TestUtil.ReflectionTester packedReflectionTester =
- new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);
public void testDynamicMessageAccessors() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
reflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testSettersAfterBuild() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
Message firstMessage = builder.build();
// double build()
builder.build();
@@ -85,12 +83,12 @@ public class DynamicMessageTest extends TestCase {
}
public void testUnknownFields() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
- builder.setUnknownFields(UnknownFieldSet.newBuilder()
- .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
- .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
- .build());
+ Message.Builder builder = DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
+ builder.setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
+ .build());
Message message = builder.build();
assertEquals(2, message.getUnknownFields().asMap().size());
// clone() with unknown fields
@@ -105,8 +103,7 @@ public class DynamicMessageTest extends TestCase {
}
public void testDynamicMessageSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionSettersRejectNull(builder);
}
@@ -114,22 +111,19 @@ public class DynamicMessageTest extends TestCase {
// We don't need to extensively test DynamicMessage's handling of
// extensions because, frankly, it doesn't do anything special with them.
// It treats them just like any other fields.
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
}
public void testDynamicMessageExtensionSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllExtensions.getDescriptor());
extensionsReflectionTester.assertReflectionSettersRejectNull(builder);
}
public void testDynamicMessageRepeatedSetters() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
reflectionTester.modifyRepeatedFieldsViaReflection(builder);
Message message = builder.build();
@@ -137,33 +131,29 @@ public class DynamicMessageTest extends TestCase {
}
public void testDynamicMessageRepeatedSettersRejectNull() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testDynamicMessageDefaults() throws Exception {
reflectionTester.assertClearViaReflection(
- DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor()));
+ DynamicMessage.getDefaultInstance(TestAllTypes.getDescriptor()));
reflectionTester.assertClearViaReflection(
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build());
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor()).build());
}
public void testDynamicMessageSerializedSize() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
- Message.Builder dynamicBuilder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder dynamicBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(dynamicBuilder);
Message dynamicMessage = dynamicBuilder.build();
- assertEquals(message.getSerializedSize(),
- dynamicMessage.getSerializedSize());
+ assertEquals(message.getSerializedSize(), dynamicMessage.getSerializedSize());
}
public void testDynamicMessageSerialization() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
Message message = builder.build();
@@ -183,8 +173,7 @@ public class DynamicMessageTest extends TestCase {
ByteString rawBytes = message.toByteString();
- Message message2 =
- DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes);
+ Message message2 = DynamicMessage.parseFrom(TestAllTypes.getDescriptor(), rawBytes);
reflectionTester.assertAllFieldsSetViaReflection(message2);
// Test Parser interface.
@@ -194,20 +183,19 @@ public class DynamicMessageTest extends TestCase {
public void testDynamicMessageExtensionParsing() throws Exception {
ByteString rawBytes = TestUtil.getAllExtensionsSet().toByteString();
- Message message = DynamicMessage.parseFrom(
- TestAllExtensions.getDescriptor(), rawBytes,
- TestUtil.getExtensionRegistry());
+ Message message =
+ DynamicMessage.parseFrom(
+ TestAllExtensions.getDescriptor(), rawBytes, TestUtil.getFullExtensionRegistry());
extensionsReflectionTester.assertAllFieldsSetViaReflection(message);
// Test Parser interface.
- Message message2 = message.getParserForType().parseFrom(
- rawBytes, TestUtil.getExtensionRegistry());
+ Message message2 =
+ message.getParserForType().parseFrom(rawBytes, TestUtil.getExtensionRegistry());
extensionsReflectionTester.assertAllFieldsSetViaReflection(message2);
}
public void testDynamicMessagePackedSerialization() throws Exception {
- Message.Builder builder =
- DynamicMessage.newBuilder(TestPackedTypes.getDescriptor());
+ Message.Builder builder = DynamicMessage.newBuilder(TestPackedTypes.getDescriptor());
packedReflectionTester.setPackedFieldsViaReflection(builder);
Message message = builder.build();
@@ -227,8 +215,7 @@ public class DynamicMessageTest extends TestCase {
ByteString rawBytes = message.toByteString();
- Message message2 =
- DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes);
+ Message message2 = DynamicMessage.parseFrom(TestPackedTypes.getDescriptor(), rawBytes);
packedReflectionTester.assertPackedFieldsSetViaReflection(message2);
// Test Parser interface.
@@ -245,41 +232,38 @@ public class DynamicMessageTest extends TestCase {
reflectionTester.assertAllFieldsSetViaReflection(copy);
// Test oneof behavior
- FieldDescriptor bytesField =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
- FieldDescriptor uint32Field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_uint32");
+ FieldDescriptor bytesField = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ FieldDescriptor uint32Field = TestAllTypes.getDescriptor().findFieldByName("oneof_uint32");
assertTrue(copy.hasField(bytesField));
assertFalse(copy.hasField(uint32Field));
- DynamicMessage copy2 =
- DynamicMessage.newBuilder(message).setField(uint32Field, 123).build();
+ DynamicMessage copy2 = DynamicMessage.newBuilder(message).setField(uint32Field, 123).build();
assertFalse(copy2.hasField(bytesField));
assertTrue(copy2.hasField(uint32Field));
assertEquals(123, copy2.getField(uint32Field));
}
public void testToBuilder() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
reflectionTester.setAllFieldsViaReflection(builder);
int unknownFieldNum = 9;
long unknownFieldVal = 90;
- builder.setUnknownFields(UnknownFieldSet.newBuilder()
- .addField(unknownFieldNum,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(unknownFieldVal).build())
- .build());
+ builder.setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ unknownFieldNum,
+ UnknownFieldSet.Field.newBuilder().addVarint(unknownFieldVal).build())
+ .build());
DynamicMessage message = builder.build();
DynamicMessage derived = message.toBuilder().build();
reflectionTester.assertAllFieldsSetViaReflection(derived);
- assertEquals(Arrays.asList(unknownFieldVal),
+ assertEquals(
+ Arrays.asList(unknownFieldVal),
derived.getUnknownFields().getField(unknownFieldNum).getVarintList());
}
public void testDynamicOneofMessage() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
assertFalse(builder.hasOneof(oneof));
assertSame(null, builder.getOneofFieldDescriptor(oneof));
@@ -292,8 +276,7 @@ public class DynamicMessageTest extends TestCase {
DynamicMessage message = builder.buildPartial();
assertTrue(message.hasOneof(oneof));
- DynamicMessage.Builder mergedBuilder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder mergedBuilder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
FieldDescriptor mergedField = oneof.getField(0);
mergedBuilder.setField(mergedField, 123);
assertTrue(mergedBuilder.hasField(mergedField));
@@ -310,15 +293,12 @@ public class DynamicMessageTest extends TestCase {
// Regression test for a bug that makes setField() not work for repeated
// enum fields.
public void testSettersForRepeatedEnumField() throws Exception {
- DynamicMessage.Builder builder =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
+ DynamicMessage.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
FieldDescriptor repeatedEnumField =
- TestAllTypes.getDescriptor().findFieldByName(
- "repeated_nested_enum");
+ TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
EnumDescriptor enumDescriptor = TestAllTypes.NestedEnum.getDescriptor();
builder.setField(repeatedEnumField, enumDescriptor.getValues());
DynamicMessage message = builder.build();
- assertEquals(
- enumDescriptor.getValues(), message.getField(repeatedEnumField));
+ assertEquals(enumDescriptor.getValues(), message.getField(repeatedEnumField));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/EnumTest.java b/java/core/src/test/java/com/google/protobuf/EnumTest.java
index 14c7406b..80c176a7 100644
--- a/java/core/src/test/java/com/google/protobuf/EnumTest.java
+++ b/java/core/src/test/java/com/google/protobuf/EnumTest.java
@@ -34,43 +34,43 @@ import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import protobuf_unittest.UnittestProto.ForeignEnum;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
import junit.framework.TestCase;
public class EnumTest extends TestCase {
-
+
public void testForNumber() {
ForeignEnum e = ForeignEnum.forNumber(ForeignEnum.FOREIGN_BAR.getNumber());
assertEquals(ForeignEnum.FOREIGN_BAR, e);
e = ForeignEnum.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumber_oneof() {
- TestAllTypes.OneofFieldCase e = TestAllTypes.OneofFieldCase.forNumber(
- TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
+ TestAllTypes.OneofFieldCase e =
+ TestAllTypes.OneofFieldCase.forNumber(
+ TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
assertEquals(TestAllTypes.OneofFieldCase.ONEOF_NESTED_MESSAGE, e);
e = TestAllTypes.OneofFieldCase.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumberLite() {
ForeignEnumLite e = ForeignEnumLite.forNumber(ForeignEnumLite.FOREIGN_LITE_BAR.getNumber());
assertEquals(ForeignEnumLite.FOREIGN_LITE_BAR, e);
e = ForeignEnumLite.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
-
+
public void testForNumberLite_oneof() {
- TestAllTypesLite.OneofFieldCase e = TestAllTypesLite.OneofFieldCase.forNumber(
- TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
+ TestAllTypesLite.OneofFieldCase e =
+ TestAllTypesLite.OneofFieldCase.forNumber(
+ TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE.getNumber());
assertEquals(TestAllTypesLite.OneofFieldCase.ONEOF_NESTED_MESSAGE, e);
e = TestAllTypesLite.OneofFieldCase.forNumber(1000);
- assertEquals(null, e);
+ assertNull(e);
}
}
-
diff --git a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
index 6157e589..a0e91375 100644
--- a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
@@ -47,31 +47,31 @@ import junit.framework.TestSuite;
* creates.
*
* <p>This test simulates the runtime behaviour of the ExtensionRegistryFactory by delegating test
- * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of
- * which is executed using a custom ClassLoader, simulating the ProtoLite environment.
+ * definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of which
+ * is executed using a custom ClassLoader, simulating the ProtoLite environment.
*
- * <p>The test mechanism employed here is based on the pattern in
- * {@code com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest}
+ * <p>The test mechanism employed here is based on the pattern in {@code
+ * com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest}
*/
public class ExtensionRegistryFactoryTest extends TestCase {
// A classloader which blacklists some non-Lite classes.
private static final ClassLoader LITE_CLASS_LOADER = getLiteOnlyClassLoader();
- /**
- * Defines the set of test methods which will be run.
- */
+ /** Defines the set of test methods which will be run. */
static interface RegistryTests {
void testCreate();
+
void testEmpty();
+
void testIsFullRegistry();
+
void testAdd();
+
void testAdd_immutable();
}
- /**
- * Test implementations for the non-Lite usage of ExtensionRegistryFactory.
- */
+ /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */
public static class InnerTest implements RegistryTests {
@Override
@@ -108,20 +108,25 @@ public class ExtensionRegistryFactoryTest extends TestCase {
ExtensionRegistry fullRegistry1 = (ExtensionRegistry) registry1;
ExtensionRegistry fullRegistry2 = (ExtensionRegistry) registry2;
- assertTrue("Test is using a non-lite extension",
+ assertTrue(
+ "Test is using a non-lite extension",
GeneratedMessageLite.GeneratedExtension.class.isAssignableFrom(
NonNestedExtensionLite.nonNestedExtensionLite.getClass()));
- assertNull("Extension is not registered in masqueraded full registry",
+ assertNull(
+ "Extension is not registered in masqueraded full registry",
fullRegistry1.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension"));
GeneratedMessageLite.GeneratedExtension<NonNestedExtensionLite.MessageLiteToBeExtended, ?>
- extension = registry1.findLiteExtensionByNumber(
- NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
+ extension =
+ registry1.findLiteExtensionByNumber(
+ NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
assertNotNull("Extension registered in lite registry", extension);
- assertTrue("Test is using a non-lite extension",
+ assertTrue(
+ "Test is using a non-lite extension",
GeneratedMessage.GeneratedExtension.class.isAssignableFrom(
- NonNestedExtension.nonNestedExtension.getClass()));
- assertNotNull("Extension is registered in masqueraded full registry",
+ NonNestedExtension.nonNestedExtension.getClass()));
+ assertNotNull(
+ "Extension is registered in masqueraded full registry",
fullRegistry2.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension"));
}
@@ -131,27 +136,29 @@ public class ExtensionRegistryFactoryTest extends TestCase {
try {
NonNestedExtensionLite.registerAllExtensions(registry1);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
try {
registry1.add(NonNestedExtensionLite.nonNestedExtensionLite);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
ExtensionRegistryLite registry2 = ExtensionRegistryLite.newInstance().getUnmodifiable();
try {
NonNestedExtension.registerAllExtensions((ExtensionRegistry) registry2);
fail();
- } catch (IllegalArgumentException expected) {}
+ } catch (IllegalArgumentException expected) {
+ }
try {
registry2.add(NonNestedExtension.nonNestedExtension);
fail();
- } catch (IllegalArgumentException expected) {}
+ } catch (IllegalArgumentException expected) {
+ }
}
}
- /**
- * Test implementations for the Lite usage of ExtensionRegistryFactory.
- */
+ /** Test implementations for the Lite usage of ExtensionRegistryFactory. */
public static final class InnerLiteTest implements RegistryTests {
@Override
@@ -180,8 +187,9 @@ public class ExtensionRegistryFactoryTest extends TestCase {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
NonNestedExtensionLite.registerAllExtensions(registry);
GeneratedMessageLite.GeneratedExtension<NonNestedExtensionLite.MessageLiteToBeExtended, ?>
- extension = registry.findLiteExtensionByNumber(
- NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
+ extension =
+ registry.findLiteExtensionByNumber(
+ NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
assertNotNull("Extension is registered in Lite registry", extension);
}
@@ -191,13 +199,12 @@ public class ExtensionRegistryFactoryTest extends TestCase {
try {
NonNestedExtensionLite.registerAllExtensions(registry);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
}
- /**
- * Defines a suite of tests which the JUnit3 runner retrieves by reflection.
- */
+ /** Defines a suite of tests which the JUnit3 runner retrieves by reflection. */
public static Test suite() {
TestSuite suite = new TestSuite();
for (Method method : RegistryTests.class.getMethods()) {
@@ -235,8 +242,8 @@ public class ExtensionRegistryFactoryTest extends TestCase {
}
/**
- * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT
- * to determine the Lite/non-Lite runtime.
+ * Constructs a custom ClassLoader blacklisting the classes which are inspected in the SUT to
+ * determine the Lite/non-Lite runtime.
*/
private static ClassLoader getLiteOnlyClassLoader() {
ClassLoader testClassLoader = ExtensionRegistryFactoryTest.class.getClassLoader();
@@ -250,8 +257,8 @@ public class ExtensionRegistryFactoryTest extends TestCase {
// Construct a URLClassLoader delegating to the system ClassLoader, and looking up classes
// in jar files based on the URLs already configured for this test's UrlClassLoader.
// Certain classes throw a ClassNotFoundException by design.
- return new URLClassLoader(((URLClassLoader) testClassLoader).getURLs(),
- ClassLoader.getSystemClassLoader()) {
+ return new URLClassLoader(
+ ((URLClassLoader) testClassLoader).getURLs(), ClassLoader.getSystemClassLoader()) {
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (classNamesNotInLite.contains(name)) {
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 42da5bb3..85a2fe08 100644
--- a/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FieldPresenceTest.java
@@ -38,12 +38,10 @@ import com.google.protobuf.FieldPresenceTestProto.TestAllTypes;
import com.google.protobuf.FieldPresenceTestProto.TestOptionalFieldsOnly;
import com.google.protobuf.FieldPresenceTestProto.TestRepeatedFieldsOnly;
import protobuf_unittest.UnittestProto;
-
import junit.framework.TestCase;
/**
- * Unit tests for protos that doesn't support field presence test for optional
- * non-message fields.
+ * Unit tests for protos that doesn't support field presence test for optional non-message fields.
*/
public class FieldPresenceTest extends TestCase {
private static boolean hasMethod(Class<?> clazz, String name) {
@@ -59,9 +57,7 @@ public class FieldPresenceTest extends TestCase {
}
private static void assertHasMethodRemoved(
- Class<?> classWithFieldPresence,
- Class<?> classWithoutFieldPresence,
- String camelName) {
+ Class<?> classWithFieldPresence, Class<?> classWithoutFieldPresence, String camelName) {
assertTrue(hasMethod(classWithFieldPresence, "get" + camelName));
assertTrue(hasMethod(classWithFieldPresence, "has" + camelName));
assertTrue(hasMethod(classWithoutFieldPresence, "get" + camelName));
@@ -70,72 +66,38 @@ public class FieldPresenceTest extends TestCase {
public void testHasMethod() {
// Optional non-message fields don't have a hasFoo() method generated.
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalInt32");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalString");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalBytes");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalInt32");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalString");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalBytes");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OptionalNestedEnum");
+ UnittestProto.TestAllTypes.class, TestAllTypes.class, "OptionalNestedEnum");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalInt32");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalInt32");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalString");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalString");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalBytes");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalBytes");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OptionalNestedEnum");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OptionalNestedEnum");
// message fields still have the hasFoo() method generated.
- assertFalse(TestAllTypes.newBuilder().build().hasOptionalNestedMessage());
+ assertFalse(TestAllTypes.getDefaultInstance().hasOptionalNestedMessage());
assertFalse(TestAllTypes.newBuilder().hasOptionalNestedMessage());
// oneof fields don't have hasFoo() methods for non-message types.
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofUint32");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofString");
- assertHasMethodRemoved(
- UnittestProto.TestAllTypes.class,
- TestAllTypes.class,
- "OneofBytes");
- assertFalse(TestAllTypes.newBuilder().build().hasOneofNestedMessage());
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofUint32");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofString");
+ assertHasMethodRemoved(UnittestProto.TestAllTypes.class, TestAllTypes.class, "OneofBytes");
+ assertFalse(TestAllTypes.getDefaultInstance().hasOneofNestedMessage());
assertFalse(TestAllTypes.newBuilder().hasOneofNestedMessage());
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofUint32");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofUint32");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofString");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofString");
assertHasMethodRemoved(
- UnittestProto.TestAllTypes.Builder.class,
- TestAllTypes.Builder.class,
- "OneofBytes");
+ UnittestProto.TestAllTypes.Builder.class, TestAllTypes.Builder.class, "OneofBytes");
}
public void testOneofEquals() throws Exception {
@@ -200,10 +162,10 @@ public class FieldPresenceTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.BAR, message.getOptionalNestedEnum());
// equals()/hashCode() should produce the same results.
- TestAllTypes empty = TestAllTypes.newBuilder().build();
+ TestAllTypes empty = TestAllTypes.getDefaultInstance();
message = builder.build();
- assertTrue(empty.equals(message));
- assertTrue(message.equals(empty));
+ assertEquals(message, empty);
+ assertEquals(empty, message);
assertEquals(empty.hashCode(), message.hashCode());
}
@@ -215,7 +177,7 @@ public class FieldPresenceTest extends TestCase {
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
// Field not present.
- TestAllTypes message = TestAllTypes.newBuilder().build();
+ TestAllTypes message = TestAllTypes.getDefaultInstance();
assertFalse(message.hasField(optionalInt32Field));
assertFalse(message.hasField(optionalStringField));
assertFalse(message.hasField(optionalBytesField));
@@ -223,12 +185,13 @@ public class FieldPresenceTest extends TestCase {
assertEquals(0, message.getAllFields().size());
// Field set to default value is seen as not present.
- message = TestAllTypes.newBuilder()
- .setOptionalInt32(0)
- .setOptionalString("")
- .setOptionalBytes(ByteString.EMPTY)
- .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO)
- .build();
+ message =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(0)
+ .setOptionalString("")
+ .setOptionalBytes(ByteString.EMPTY)
+ .setOptionalNestedEnum(TestAllTypes.NestedEnum.FOO)
+ .build();
assertFalse(message.hasField(optionalInt32Field));
assertFalse(message.hasField(optionalStringField));
assertFalse(message.hasField(optionalBytesField));
@@ -236,12 +199,13 @@ public class FieldPresenceTest extends TestCase {
assertEquals(0, message.getAllFields().size());
// Field set to non-default value is seen as present.
- message = TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("x")
- .setOptionalBytes(ByteString.copyFromUtf8("y"))
- .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR)
- .build();
+ message =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("x")
+ .setOptionalBytes(ByteString.copyFromUtf8("y"))
+ .setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR)
+ .build();
assertTrue(message.hasField(optionalInt32Field));
assertTrue(message.hasField(optionalStringField));
assertTrue(message.hasField(optionalBytesField));
@@ -284,7 +248,9 @@ public class FieldPresenceTest extends TestCase {
assertEquals(4, message.getAllFields().size());
// Field set to default value is seen as not present.
- message = message.toBuilder()
+ message =
+ message
+ .toBuilder()
.setField(optionalInt32Field, 0)
.setField(optionalStringField, "")
.setField(optionalBytesField, ByteString.EMPTY)
@@ -302,8 +268,7 @@ public class FieldPresenceTest extends TestCase {
assertFalse(builder.hasOptionalNestedMessage());
assertFalse(builder.build().hasOptionalNestedMessage());
- TestAllTypes.NestedMessage.Builder nestedBuilder =
- builder.getOptionalNestedMessageBuilder();
+ TestAllTypes.NestedMessage.Builder nestedBuilder = builder.getOptionalNestedMessageBuilder();
assertTrue(builder.hasOptionalNestedMessage());
assertTrue(builder.build().hasOptionalNestedMessage());
@@ -341,8 +306,7 @@ public class FieldPresenceTest extends TestCase {
assertTrue(message.hasOptionalNestedMessage());
assertEquals(0, message.getOptionalNestedMessage().getValue());
// The oneof field set to its default value is also present.
- assertEquals(
- TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase());
+ assertEquals(TestAllTypes.OneofFieldCase.ONEOF_INT32, message.getOneofFieldCase());
}
// Regression test for b/16173397
@@ -376,8 +340,7 @@ public class FieldPresenceTest extends TestCase {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// Test optional proto2 message fields.
- UnittestProto.TestRequired.Builder proto2Builder =
- builder.getOptionalProto2MessageBuilder();
+ UnittestProto.TestRequired.Builder proto2Builder = builder.getOptionalProto2MessageBuilder();
assertFalse(builder.isInitialized());
assertFalse(builder.buildPartial().isInitialized());
diff --git a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
index 903a79db..7ed61340 100644
--- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class FloatArrayListTest extends TestCase {
- private static final FloatArrayList UNARY_LIST =
- newImmutableFloatArrayList(1);
- private static final FloatArrayList TERTIARY_LIST =
- newImmutableFloatArrayList(1, 2, 3);
+ private static final FloatArrayList UNARY_LIST = newImmutableFloatArrayList(1);
+ private static final FloatArrayList TERTIARY_LIST = newImmutableFloatArrayList(1, 2, 3);
private FloatArrayList list;
@@ -78,10 +76,10 @@ public class FloatArrayListTest extends TestCase {
list.addAll(asList(1F, 2F, 3F, 4F));
Iterator<Float> iterator = list.iterator();
assertEquals(4, list.size());
- assertEquals(1F, (float) list.get(0));
- assertEquals(1F, (float) iterator.next());
+ assertEquals(1F, (float) list.get(0), 0.0f);
+ assertEquals(1F, (float) iterator.next(), 0.0f);
list.set(0, 1F);
- assertEquals(2F, (float) iterator.next());
+ assertEquals(2F, (float) iterator.next(), 0.0f);
list.remove(0);
try {
@@ -102,9 +100,9 @@ public class FloatArrayListTest extends TestCase {
}
public void testGet() {
- assertEquals(1F, (float) TERTIARY_LIST.get(0));
- assertEquals(2F, (float) TERTIARY_LIST.get(1));
- assertEquals(3F, (float) TERTIARY_LIST.get(2));
+ assertEquals(1F, (float) TERTIARY_LIST.get(0), 0.0f);
+ assertEquals(2F, (float) TERTIARY_LIST.get(1), 0.0f);
+ assertEquals(3F, (float) TERTIARY_LIST.get(2), 0.0f);
try {
TERTIARY_LIST.get(-1);
@@ -122,9 +120,9 @@ public class FloatArrayListTest extends TestCase {
}
public void testGetFloat() {
- assertEquals(1F, TERTIARY_LIST.getFloat(0));
- assertEquals(2F, TERTIARY_LIST.getFloat(1));
- assertEquals(3F, TERTIARY_LIST.getFloat(2));
+ assertEquals(1F, TERTIARY_LIST.getFloat(0), 0.0f);
+ assertEquals(2F, TERTIARY_LIST.getFloat(1), 0.0f);
+ assertEquals(3F, TERTIARY_LIST.getFloat(2), 0.0f);
try {
TERTIARY_LIST.get(-1);
@@ -163,11 +161,11 @@ public class FloatArrayListTest extends TestCase {
list.addFloat(2);
list.addFloat(4);
- assertEquals(2F, (float) list.set(0, 3F));
- assertEquals(3F, list.getFloat(0));
+ assertEquals(2F, (float) list.set(0, 3F), 0.0f);
+ assertEquals(3F, list.getFloat(0), 0.0f);
- assertEquals(4F, (float) list.set(1, 0F));
- assertEquals(0F, list.getFloat(1));
+ assertEquals(4F, (float) list.set(1, 0F), 0.0f);
+ assertEquals(0F, list.getFloat(1), 0.0f);
try {
list.set(-1, 0F);
@@ -188,11 +186,11 @@ public class FloatArrayListTest extends TestCase {
list.addFloat(1);
list.addFloat(3);
- assertEquals(1F, list.setFloat(0, 0));
- assertEquals(0F, list.getFloat(0));
+ assertEquals(1F, list.setFloat(0, 0), 0.0f);
+ assertEquals(0F, list.getFloat(0), 0.0f);
- assertEquals(3F, list.setFloat(1, 0));
- assertEquals(0F, list.getFloat(1));
+ assertEquals(3F, list.setFloat(1, 0), 0.0f);
+ assertEquals(0F, list.getFloat(1), 0.0f);
try {
list.setFloat(-1, 0);
@@ -225,9 +223,7 @@ public class FloatArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Float.valueOf(5 + i));
}
- assertEquals(
- asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F),
- list);
+ assertEquals(asList(0F, 1F, 4F, 2F, 3F, 5F, 6F, 7F, 8F, 9F, 10F), list);
try {
list.add(-1, 5F);
@@ -257,8 +253,8 @@ public class FloatArrayListTest extends TestCase {
assertTrue(list.addAll(Collections.singleton(1F)));
assertEquals(1, list.size());
- assertEquals(1F, (float) list.get(0));
- assertEquals(1F, list.getFloat(0));
+ assertEquals(1F, (float) list.get(0), 0.0f);
+ assertEquals(1F, list.getFloat(0), 0.0f);
assertTrue(list.addAll(asList(2F, 3F, 4F, 5F, 6F)));
assertEquals(asList(1F, 2F, 3F, 4F, 5F, 6F), list);
@@ -272,7 +268,7 @@ public class FloatArrayListTest extends TestCase {
public void testRemove() {
list.addAll(TERTIARY_LIST);
- assertEquals(1F, (float) list.remove(0));
+ assertEquals(1F, (float) list.remove(0), 0.0f);
assertEquals(asList(2F, 3F), list);
assertTrue(list.remove(Float.valueOf(3)));
@@ -281,7 +277,7 @@ public class FloatArrayListTest extends TestCase {
assertFalse(list.remove(Float.valueOf(3)));
assertEquals(asList(2F), list);
- assertEquals(2F, (float) list.remove(0));
+ assertEquals(2F, (float) list.remove(0), 0.0f);
assertEquals(asList(), list);
try {
@@ -312,7 +308,7 @@ public class FloatArrayListTest extends TestCase {
assertEquals(0, toRemove.size());
}
- private void assertImmutable(FloatArrayList list) {
+ private void assertImmutable(FloatList list) {
if (list.contains(1F)) {
throw new RuntimeException("Cannot test the immutability of lists that contain 1.");
}
diff --git a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
index b7eaebf5..baa6d086 100644
--- a/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
+++ b/java/core/src/test/java/com/google/protobuf/ForceFieldBuildersPreRun.java
@@ -31,11 +31,10 @@
package com.google.protobuf;
/**
- * A prerun for a test suite that allows running the full protocol buffer
- * tests in a mode that disables the optimization for not using
- * {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder} until they are
- * requested. This allows us to run all the tests through both code paths
- * and ensures that both code paths produce identical results.
+ * A prerun for a test suite that allows running the full protocol buffer tests in a mode that
+ * disables the optimization for not using {@link RepeatedFieldBuilder} and {@link
+ * SingleFieldBuilder} until they are requested. This allows us to run all the tests through both
+ * code paths and ensures that both code paths produce identical results.
*
* @author jonp@google.com (Jon Perlow)
*/
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 c9ebe7f5..13457bc0 100644
--- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
@@ -71,20 +71,21 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Unit test for generated messages and generated code. See also
- * {@link MessageTest}, which tests some generated message functionality.
+ * Unit test for generated messages and generated code. See also {@link MessageTest}, which tests
+ * some generated message functionality.
*
* @author kenton@google.com Kenton Varda
*/
public class GeneratedMessageTest extends TestCase {
TestUtil.ReflectionTester reflectionTester =
- new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
+ new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);
public void testDefaultInstance() throws Exception {
- assertSame(TestAllTypes.getDefaultInstance(),
- TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
- assertSame(TestAllTypes.getDefaultInstance(),
- TestAllTypes.newBuilder().getDefaultInstanceForType());
+ assertSame(
+ TestAllTypes.getDefaultInstance(),
+ TestAllTypes.getDefaultInstance().getDefaultInstanceForType());
+ assertSame(
+ TestAllTypes.getDefaultInstance(), TestAllTypes.newBuilder().getDefaultInstanceForType());
}
public void testMessageOrBuilder() throws Exception {
@@ -110,10 +111,8 @@ public class GeneratedMessageTest extends TestCase {
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
@@ -130,20 +129,16 @@ public class GeneratedMessageTest extends TestCase {
// Make sure value1 didn't change.
assertEquals(100, value1.getOptionalSfixed64());
assertEquals(100, value1.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_BAR,
- value1.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_BAR, value1.getRepeatedImportEnum(0));
assertEquals(1, value1.getOptionalForeignMessage().getC());
assertEquals(1, value1.getRepeatedForeignMessage(0).getC());
// Make sure value2 is correct
assertEquals(200, value2.getOptionalSfixed64());
assertEquals(200, value2.getRepeatedInt32(0));
- assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
- value2.getOptionalImportEnum());
- assertEquals(UnittestImport.ImportEnum.IMPORT_FOO,
- value2.getRepeatedImportEnum(0));
+ assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getOptionalImportEnum());
+ assertEquals(UnittestImport.ImportEnum.IMPORT_FOO, value2.getRepeatedImportEnum(0));
assertEquals(2, value2.getOptionalForeignMessage().getC());
assertEquals(2, value2.getRepeatedForeignMessage(0).getC());
}
@@ -157,8 +152,7 @@ public class GeneratedMessageTest extends TestCase {
TestAllTypes value2 = value1.toBuilder().build();
assertSame(value1.getRepeatedInt32List(), value2.getRepeatedInt32List());
- assertSame(value1.getRepeatedForeignMessageList(),
- value2.getRepeatedForeignMessageList());
+ assertSame(value1.getRepeatedForeignMessageList(), value2.getRepeatedForeignMessageList());
}
public void testRepeatedArraysAreImmutable() throws Exception {
@@ -171,7 +165,6 @@ public class GeneratedMessageTest extends TestCase {
assertIsUnmodifiable(builder.getRepeatedForeignMessageList());
assertIsUnmodifiable(builder.getRepeatedFloatList());
-
TestAllTypes value = builder.build();
assertIsUnmodifiable(value.getRepeatedInt32List());
assertIsUnmodifiable(value.getRepeatedImportEnumList());
@@ -239,8 +232,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.setOptionalNestedMessage(
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.setOptionalNestedMessage((TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -270,8 +262,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.addRepeatedNestedMessage(
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.addRepeatedNestedMessage((TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -313,10 +304,8 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
- builder.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- builder.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
+ builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ builder.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(456).build());
try {
builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage) null);
fail("Exception was not thrown");
@@ -324,8 +313,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.setRepeatedNestedMessage(
- 1, (TestAllTypes.NestedMessage.Builder) null);
+ builder.setRepeatedNestedMessage(1, (TestAllTypes.NestedMessage.Builder) null);
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -347,14 +335,12 @@ public class GeneratedMessageTest extends TestCase {
builder.addAllRepeatedInt32(Arrays.asList(1, 2, 3, 4));
builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ));
- ForeignMessage foreignMessage =
- ForeignMessage.newBuilder().setC(12).build();
+ ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build();
builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage));
TestAllTypes message = builder.build();
assertEquals(message.getRepeatedInt32List(), Arrays.asList(1, 2, 3, 4));
- assertEquals(message.getRepeatedForeignEnumList(),
- Arrays.asList(ForeignEnum.FOREIGN_BAZ));
+ assertEquals(message.getRepeatedForeignEnumList(), Arrays.asList(ForeignEnum.FOREIGN_BAZ));
assertEquals(1, message.getRepeatedForeignMessageCount());
assertEquals(12, message.getRepeatedForeignMessage(0).getC());
}
@@ -362,19 +348,16 @@ public class GeneratedMessageTest extends TestCase {
public void testRepeatedAppendRejectsNull() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- ForeignMessage foreignMessage =
- ForeignMessage.newBuilder().setC(12).build();
+ ForeignMessage foreignMessage = ForeignMessage.newBuilder().setC(12).build();
try {
- builder.addAllRepeatedForeignMessage(
- Arrays.asList(foreignMessage, (ForeignMessage) null));
+ builder.addAllRepeatedForeignMessage(Arrays.asList(foreignMessage, (ForeignMessage) null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
- builder.addAllRepeatedForeignEnum(
- Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
+ builder.addAllRepeatedForeignEnum(Arrays.asList(ForeignEnum.FOREIGN_BAZ, null));
fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -394,20 +377,22 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
}
-
+
public void testRepeatedAppendIterateOnlyOnce() throws Exception {
// Create a Iterable that can only be iterated once.
- Iterable<String> stringIterable = new Iterable<String>() {
- private boolean called = false;
- @Override
- public Iterator<String> iterator() {
- if (called) {
- throw new IllegalStateException();
- }
- called = true;
- return Arrays.asList("one", "two", "three").iterator();
- }
- };
+ Iterable<String> stringIterable =
+ new Iterable<String>() {
+ private boolean called = false;
+
+ @Override
+ public Iterator<String> iterator() {
+ if (called) {
+ throw new IllegalStateException();
+ }
+ called = true;
+ return Arrays.asList("one", "two", "three").iterator();
+ }
+ };
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addAllRepeatedString(stringIterable);
assertEquals(3, builder.getRepeatedStringCount());
@@ -434,29 +419,31 @@ public class GeneratedMessageTest extends TestCase {
}
public void testSettingForeignMessageUsingBuilder() throws Exception {
- TestAllTypes message = TestAllTypes.newBuilder()
- // Pass builder for foreign message instance.
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
- .build();
- TestAllTypes expectedMessage = TestAllTypes.newBuilder()
- // Create expected version passing foreign message instance explicitly.
- .setOptionalForeignMessage(
- ForeignMessage.newBuilder().setC(123).build())
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder()
+ // Pass builder for foreign message instance.
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123))
+ .build();
+ TestAllTypes expectedMessage =
+ TestAllTypes.newBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(123).build())
+ .build();
// TODO(ngd): Upgrade to using real #equals method once implemented
assertEquals(expectedMessage.toString(), message.toString());
}
public void testSettingRepeatedForeignMessageUsingBuilder() throws Exception {
- TestAllTypes message = TestAllTypes.newBuilder()
- // Pass builder for foreign message instance.
- .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
- .build();
- TestAllTypes expectedMessage = TestAllTypes.newBuilder()
- // Create expected version passing foreign message instance explicitly.
- .addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(456).build())
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder()
+ // Pass builder for foreign message instance.
+ .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456))
+ .build();
+ TestAllTypes expectedMessage =
+ TestAllTypes.newBuilder()
+ // Create expected version passing foreign message instance explicitly.
+ .addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(456).build())
+ .build();
assertEquals(expectedMessage.toString(), message.toString());
}
@@ -464,14 +451,13 @@ public class GeneratedMessageTest extends TestCase {
TestUtil.assertClear(TestAllTypes.getDefaultInstance());
TestUtil.assertClear(TestAllTypes.newBuilder().build());
- TestExtremeDefaultValues message =
- TestExtremeDefaultValues.getDefaultInstance();
+ TestExtremeDefaultValues message = TestExtremeDefaultValues.getDefaultInstance();
assertEquals("\u1234", message.getUtf8String());
- assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble());
- assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble());
+ assertEquals(Double.POSITIVE_INFINITY, message.getInfDouble(), 0.0);
+ assertEquals(Double.NEGATIVE_INFINITY, message.getNegInfDouble(), 0.0);
assertTrue(Double.isNaN(message.getNanDouble()));
- assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat());
- assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat());
+ assertEquals(Float.POSITIVE_INFINITY, message.getInfFloat(), 0.0f);
+ assertEquals(Float.NEGATIVE_INFINITY, message.getNegInfFloat(), 0.0f);
assertTrue(Float.isNaN(message.getNanFloat()));
assertEquals("? ? ?? ?? ??? ??/ ??-", message.getCppTrigraph());
}
@@ -523,19 +509,15 @@ public class GeneratedMessageTest extends TestCase {
}
public void testReflectionDefaults() throws Exception {
- reflectionTester.assertClearViaReflection(
- TestAllTypes.getDefaultInstance());
- reflectionTester.assertClearViaReflection(
- TestAllTypes.newBuilder().build());
+ reflectionTester.assertClearViaReflection(TestAllTypes.getDefaultInstance());
+ reflectionTester.assertClearViaReflection(TestAllTypes.newBuilder().build());
}
public void testReflectionGetOneof() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
- Descriptors.OneofDescriptor oneof =
- TestAllTypes.getDescriptor().getOneofs().get(0);
- Descriptors.FieldDescriptor field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
+ Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
assertSame(field, builder.getOneofFieldDescriptor(oneof));
TestAllTypes message = builder.build();
@@ -545,10 +527,8 @@ public class GeneratedMessageTest extends TestCase {
public void testReflectionClearOneof() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
reflectionTester.setAllFieldsViaReflection(builder);
- Descriptors.OneofDescriptor oneof =
- TestAllTypes.getDescriptor().getOneofs().get(0);
- Descriptors.FieldDescriptor field =
- TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
+ Descriptors.OneofDescriptor oneof = TestAllTypes.getDescriptor().getOneofs().get(0);
+ Descriptors.FieldDescriptor field = TestAllTypes.getDescriptor().findFieldByName("oneof_bytes");
assertTrue(builder.hasOneof(oneof));
assertTrue(builder.hasField(field));
@@ -558,8 +538,8 @@ public class GeneratedMessageTest extends TestCase {
}
public void testEnumInterface() throws Exception {
- assertTrue(TestAllTypes.getDefaultInstance().getDefaultNestedEnum()
- instanceof ProtocolMessageEnum);
+ assertTrue(
+ TestAllTypes.getDefaultInstance().getDefaultNestedEnum() instanceof ProtocolMessageEnum);
}
public void testEnumMap() throws Exception {
@@ -574,15 +554,13 @@ public class GeneratedMessageTest extends TestCase {
public void testParsePackedToUnpacked() throws Exception {
TestUnpackedTypes.Builder builder = TestUnpackedTypes.newBuilder();
- TestUnpackedTypes message =
- builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
+ TestUnpackedTypes message = builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
TestUtil.assertUnpackedFieldsSet(message);
}
public void testParseUnpackedToPacked() throws Exception {
TestPackedTypes.Builder builder = TestPackedTypes.newBuilder();
- TestPackedTypes message =
- builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
+ TestPackedTypes message = builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
TestUtil.assertPackedFieldsSet(message);
}
@@ -590,8 +568,8 @@ public class GeneratedMessageTest extends TestCase {
// Extensions.
TestUtil.ReflectionTester extensionsReflectionTester =
- new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
- TestUtil.getExtensionRegistry());
+ new TestUtil.ReflectionTester(
+ TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
public void testExtensionMessageOrBuilder() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
@@ -661,32 +639,29 @@ public class GeneratedMessageTest extends TestCase {
TestUtil.assertRepeatedExtensionsModified(message);
}
- public void testExtensionReflectionRepeatedSettersRejectNull()
- throws Exception {
+ public void testExtensionReflectionRepeatedSettersRejectNull() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
- extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(
- builder);
+ extensionsReflectionTester.assertReflectionRepeatedSettersRejectNull(builder);
}
public void testExtensionReflectionDefaults() throws Exception {
- extensionsReflectionTester.assertClearViaReflection(
- TestAllExtensions.getDefaultInstance());
- extensionsReflectionTester.assertClearViaReflection(
- TestAllExtensions.newBuilder().build());
+ extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.getDefaultInstance());
+ extensionsReflectionTester.assertClearViaReflection(TestAllExtensions.newBuilder().build());
}
public void testClearExtension() throws Exception {
// clearExtension() is not actually used in TestUtil, so try it manually.
assertFalse(
- TestAllExtensions.newBuilder()
- .setExtension(UnittestProto.optionalInt32Extension, 1)
- .clearExtension(UnittestProto.optionalInt32Extension)
- .hasExtension(UnittestProto.optionalInt32Extension));
- assertEquals(0,
- TestAllExtensions.newBuilder()
- .addExtension(UnittestProto.repeatedInt32Extension, 1)
- .clearExtension(UnittestProto.repeatedInt32Extension)
- .getExtensionCount(UnittestProto.repeatedInt32Extension));
+ TestAllExtensions.newBuilder()
+ .setExtension(UnittestProto.optionalInt32Extension, 1)
+ .clearExtension(UnittestProto.optionalInt32Extension)
+ .hasExtension(UnittestProto.optionalInt32Extension));
+ assertEquals(
+ 0,
+ TestAllExtensions.newBuilder()
+ .addExtension(UnittestProto.repeatedInt32Extension, 1)
+ .clearExtension(UnittestProto.repeatedInt32Extension)
+ .getExtensionCount(UnittestProto.repeatedInt32Extension));
}
public void testExtensionCopy() throws Exception {
@@ -697,13 +672,12 @@ public class GeneratedMessageTest extends TestCase {
public void testExtensionMergeFrom() throws Exception {
TestAllExtensions original =
- TestAllExtensions.newBuilder()
- .setExtension(UnittestProto.optionalInt32Extension, 1).build();
- TestAllExtensions merged =
- TestAllExtensions.newBuilder().mergeFrom(original).build();
+ TestAllExtensions.newBuilder()
+ .setExtension(UnittestProto.optionalInt32Extension, 1)
+ .build();
+ TestAllExtensions merged = TestAllExtensions.newBuilder().mergeFrom(original).build();
assertTrue(merged.hasExtension(UnittestProto.optionalInt32Extension));
- assertEquals(
- 1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
+ assertEquals(1, (int) merged.getExtension(UnittestProto.optionalInt32Extension));
}
// =================================================================
@@ -714,64 +688,69 @@ public class GeneratedMessageTest extends TestCase {
// or messages defined in multiple_files_test.proto because the class loading
// order affects initialization process of custom options.
public void testEnumValueOptionsInMultipleFilesMode() throws Exception {
- assertEquals(12345, EnumWithNoOuter.FOO.getValueDescriptor().getOptions()
- .getExtension(MultipleFilesTestProto.enumValueOption).intValue());
+ assertEquals(
+ 12345,
+ EnumWithNoOuter.FOO
+ .getValueDescriptor()
+ .getOptions()
+ .getExtension(MultipleFilesTestProto.enumValueOption)
+ .intValue());
}
public void testMultipleFilesOption() throws Exception {
// We mostly just want to check that things compile.
MessageWithNoOuter message =
- MessageWithNoOuter.newBuilder()
- .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
- .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
- .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
- .setForeignEnum(EnumWithNoOuter.BAR)
- .build();
+ MessageWithNoOuter.newBuilder()
+ .setNested(MessageWithNoOuter.NestedMessage.newBuilder().setI(1))
+ .addForeign(TestAllTypes.newBuilder().setOptionalInt32(1))
+ .setNestedEnum(MessageWithNoOuter.NestedEnum.BAZ)
+ .setForeignEnum(EnumWithNoOuter.BAR)
+ .build();
assertEquals(message, MessageWithNoOuter.parseFrom(message.toByteString()));
- assertEquals(MultipleFilesTestProto.getDescriptor(),
- MessageWithNoOuter.getDescriptor().getFile());
+ assertEquals(
+ MultipleFilesTestProto.getDescriptor(), MessageWithNoOuter.getDescriptor().getFile());
Descriptors.FieldDescriptor field =
- MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
- assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(),
- message.getField(field));
+ MessageWithNoOuter.getDescriptor().findFieldByName("foreign_enum");
+ assertEquals(EnumWithNoOuter.BAR.getValueDescriptor(), message.getField(field));
- assertEquals(MultipleFilesTestProto.getDescriptor(),
- ServiceWithNoOuter.getDescriptor().getFile());
+ assertEquals(
+ MultipleFilesTestProto.getDescriptor(), ServiceWithNoOuter.getDescriptor().getFile());
assertFalse(
- TestAllExtensions.getDefaultInstance().hasExtension(
- MultipleFilesTestProto.extensionWithOuter));
+ TestAllExtensions.getDefaultInstance()
+ .hasExtension(MultipleFilesTestProto.extensionWithOuter));
}
- public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize()
- throws Exception {
- TestOptionalOptimizedForSize message =
- TestOptionalOptimizedForSize.getDefaultInstance();
+ public void testOptionalFieldWithRequiredSubfieldsOptimizedForSize() throws Exception {
+ TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.getDefaultInstance();
assertTrue(message.isInitialized());
- message = TestOptionalOptimizedForSize.newBuilder().setO(
- TestRequiredOptimizedForSize.newBuilder().buildPartial()
- ).buildPartial();
+ message =
+ TestOptionalOptimizedForSize.newBuilder()
+ .setO(TestRequiredOptimizedForSize.newBuilder().buildPartial())
+ .buildPartial();
assertFalse(message.isInitialized());
- message = TestOptionalOptimizedForSize.newBuilder().setO(
- TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial()
- ).buildPartial();
+ message =
+ TestOptionalOptimizedForSize.newBuilder()
+ .setO(TestRequiredOptimizedForSize.newBuilder().setX(5).buildPartial())
+ .buildPartial();
assertTrue(message.isInitialized());
}
- public void testUninitializedExtensionInOptimizedForSize()
- throws Exception {
+ public void testUninitializedExtensionInOptimizedForSize() throws Exception {
TestOptimizedForSize.Builder builder = TestOptimizedForSize.newBuilder();
- builder.setExtension(TestOptimizedForSize.testExtension2,
+ builder.setExtension(
+ TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().buildPartial());
assertFalse(builder.isInitialized());
assertFalse(builder.buildPartial().isInitialized());
builder = TestOptimizedForSize.newBuilder();
- builder.setExtension(TestOptimizedForSize.testExtension2,
+ builder.setExtension(
+ TestOptimizedForSize.testExtension2,
TestRequiredOptimizedForSize.newBuilder().setX(10).buildPartial());
assertTrue(builder.isInitialized());
assertTrue(builder.buildPartial().isInitialized());
@@ -802,13 +781,11 @@ public class GeneratedMessageTest extends TestCase {
assertEquals(UnittestProto.TestRequired.MULTI_FIELD_NUMBER, 1001);
assertEquals(UnittestProto.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1);
assertEquals(UnittestProto.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16);
- assertEquals(
- UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
+ assertEquals(UnittestProto.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18);
assertEquals(UnittestProto.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21);
assertEquals(UnittestProto.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31);
assertEquals(UnittestProto.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46);
- assertEquals(
- UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
+ assertEquals(UnittestProto.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48);
assertEquals(UnittestProto.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51);
}
@@ -817,7 +794,7 @@ public class GeneratedMessageTest extends TestCase {
UnittestProto.TestRecursiveMessage.getDefaultInstance();
assertTrue(message != null);
assertNotNull(message.getA());
- assertTrue(message.getA() == message);
+ assertTrue(message.getA().equals(message));
}
public void testSerialize() throws Exception {
@@ -853,6 +830,67 @@ public class GeneratedMessageTest extends TestCase {
assertEquals(expected, actual);
}
+ public void testDeserializeWithoutClassField() throws Exception {
+ // serialized form for version <=3.6.0
+ // just includes messageClassName and asBytes
+
+ // Int32Value.newBuilder().setValue(123).build()
+ byte[] int32ValueBytes =
+ new byte[] {
+ -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112,
+ 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101,
+ 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101,
+ 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 91, 0, 7, 97, 115, 66, 121, 116,
+ 101, 115, 116, 0, 2, 91, 66, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97,
+ 115, 115, 78, 97, 109, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
+ 83, 116, 114, 105, 110, 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8,
+ 84, -32, 2, 0, 0, 120, 112, 0, 0, 0, 2, 8, 123, 116, 0, 30, 99, 111, 109, 46, 103, 111,
+ 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50,
+ 86, 97, 108, 117, 101
+ };
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes);
+ ObjectInputStream in = new ObjectInputStream(bais);
+ Int32Value int32Value = (Int32Value) in.readObject();
+ assertEquals(123, int32Value.getValue());
+ }
+
+ public void testDeserializeWithClassField() throws Exception {
+ // serialized form for version > 3.6.0
+ // includes messageClass, messageClassName (for compatibility), and asBytes
+
+ // Int32Value.newBuilder().setValue(123).build()
+ byte[] int32ValueBytes =
+ new byte[] {
+ -84, -19, 0, 5, 115, 114, 0, 55, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112,
+ 114, 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101,
+ 115, 115, 97, 103, 101, 76, 105, 116, 101, 36, 83, 101, 114, 105, 97, 108, 105, 122, 101,
+ 100, 70, 111, 114, 109, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 91, 0, 7, 97, 115, 66, 121, 116,
+ 101, 115, 116, 0, 2, 91, 66, 76, 0, 12, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97,
+ 115, 115, 116, 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115,
+ 115, 59, 76, 0, 16, 109, 101, 115, 115, 97, 103, 101, 67, 108, 97, 115, 115, 78, 97, 109,
+ 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110,
+ 103, 59, 120, 112, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120,
+ 112, 0, 0, 0, 2, 8, 123, 118, 114, 0, 30, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101,
+ 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117,
+ 101, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 66, 0, 21, 109, 101, 109, 111, 105, 122, 101, 100,
+ 73, 115, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 100, 73, 0, 6, 118, 97, 108, 117,
+ 101, 95, 120, 114, 0, 38, 99, 111, 109, 46, 103, 111, 111, 103, 108, 101, 46, 112, 114,
+ 111, 116, 111, 98, 117, 102, 46, 71, 101, 110, 101, 114, 97, 116, 101, 100, 77, 101, 115,
+ 115, 97, 103, 101, 86, 51, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 76, 0, 13, 117, 110, 107, 110,
+ 111, 119, 110, 70, 105, 101, 108, 100, 115, 116, 0, 37, 76, 99, 111, 109, 47, 103, 111,
+ 111, 103, 108, 101, 47, 112, 114, 111, 116, 111, 98, 117, 102, 47, 85, 110, 107, 110, 111,
+ 119, 110, 70, 105, 101, 108, 100, 83, 101, 116, 59, 120, 112, 116, 0, 30, 99, 111, 109,
+ 46, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110,
+ 116, 51, 50, 86, 97, 108, 117, 101
+ };
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(int32ValueBytes);
+ ObjectInputStream in = new ObjectInputStream(bais);
+ Int32Value int32Value = (Int32Value) in.readObject();
+ assertEquals(123, int32Value.getValue());
+ }
+
public void testEnumValues() {
assertEquals(TestAllTypes.NestedEnum.BAR_VALUE, TestAllTypes.NestedEnum.BAR.getNumber());
assertEquals(TestAllTypes.NestedEnum.BAZ_VALUE, TestAllTypes.NestedEnum.BAZ.getNumber());
@@ -860,33 +898,33 @@ public class GeneratedMessageTest extends TestCase {
}
public void testNonNestedExtensionInitialization() {
- assertTrue(NonNestedExtension.nonNestedExtension
- .getMessageDefaultInstance() instanceof MyNonNestedExtension);
- assertEquals("nonNestedExtension",
- NonNestedExtension.nonNestedExtension.getDescriptor().getName());
+ assertTrue(
+ NonNestedExtension.nonNestedExtension.getMessageDefaultInstance()
+ instanceof MyNonNestedExtension);
+ assertEquals(
+ "nonNestedExtension", NonNestedExtension.nonNestedExtension.getDescriptor().getName());
}
public void testNestedExtensionInitialization() {
- assertTrue(MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
- instanceof MessageToBeExtended);
- assertEquals("recursiveExtension",
- MyNestedExtension.recursiveExtension.getDescriptor().getName());
+ assertTrue(
+ MyNestedExtension.recursiveExtension.getMessageDefaultInstance()
+ instanceof MessageToBeExtended);
+ assertEquals(
+ "recursiveExtension", MyNestedExtension.recursiveExtension.getDescriptor().getName());
}
public void testInvalidations() throws Exception {
GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
- TestAllTypes.NestedMessage nestedMessage1 =
- TestAllTypes.NestedMessage.newBuilder().build();
- TestAllTypes.NestedMessage nestedMessage2 =
- TestAllTypes.NestedMessage.newBuilder().build();
+ TestAllTypes.NestedMessage nestedMessage1 = TestAllTypes.NestedMessage.newBuilder().build();
+ TestAllTypes.NestedMessage nestedMessage2 = TestAllTypes.NestedMessage.newBuilder().build();
// Set all three flavors (enum, primitive, message and singular/repeated)
// and verify no invalidations fired
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- TestAllTypes.Builder builder = (TestAllTypes.Builder)
- ((AbstractMessage) TestAllTypes.getDefaultInstance()).
- newBuilderForType(mockParent);
+ TestAllTypes.Builder builder =
+ (TestAllTypes.Builder)
+ ((AbstractMessage) TestAllTypes.getDefaultInstance()).newBuilderForType(mockParent);
builder.setOptionalInt32(1);
builder.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAR);
builder.setOptionalNestedMessage(nestedMessage1);
@@ -933,15 +971,15 @@ public class GeneratedMessageTest extends TestCase {
builder.addRepeatedNestedMessage(nestedMessage2);
builder.addRepeatedNestedMessage(nestedMessage1);
assertEquals(6, mockParent.getInvalidationCount());
-
}
public void testInvalidations_Extensions() throws Exception {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- TestAllExtensions.Builder builder = (TestAllExtensions.Builder)
- ((AbstractMessage) TestAllExtensions.getDefaultInstance()).
- newBuilderForType(mockParent);
+ TestAllExtensions.Builder builder =
+ (TestAllExtensions.Builder)
+ ((AbstractMessage) TestAllExtensions.getDefaultInstance())
+ .newBuilderForType(mockParent);
builder.addExtension(UnittestProto.repeatedInt32Extension, 1);
builder.setExtension(UnittestProto.repeatedInt32Extension, 0, 2);
@@ -969,25 +1007,19 @@ public class GeneratedMessageTest extends TestCase {
// Mostly just makes sure the base interface exists and has some methods.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TestAllTypes message = builder.buildPartial();
- TestAllTypesOrBuilder builderAsInterface = (TestAllTypesOrBuilder) builder;
TestAllTypesOrBuilder messageAsInterface = (TestAllTypesOrBuilder) message;
+ assertEquals(messageAsInterface.getDefaultBool(), messageAsInterface.getDefaultBool());
assertEquals(
- messageAsInterface.getDefaultBool(),
- messageAsInterface.getDefaultBool());
- assertEquals(
- messageAsInterface.getOptionalDouble(),
- messageAsInterface.getOptionalDouble());
+ messageAsInterface.getOptionalDouble(), messageAsInterface.getOptionalDouble(), 0.0);
}
public void testMessageOrBuilderGetters() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
// single fields
- assertSame(ForeignMessage.getDefaultInstance(),
- builder.getOptionalForeignMessageOrBuilder());
- ForeignMessage.Builder subBuilder =
- builder.getOptionalForeignMessageBuilder();
+ assertSame(ForeignMessage.getDefaultInstance(), builder.getOptionalForeignMessageOrBuilder());
+ ForeignMessage.Builder subBuilder = builder.getOptionalForeignMessageBuilder();
assertSame(subBuilder, builder.getOptionalForeignMessageOrBuilder());
// repeated fields
@@ -1016,36 +1048,37 @@ public class GeneratedMessageTest extends TestCase {
public void testGetFieldBuilder() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("optional_nested_message");
- FieldDescriptor foreignFieldDescriptor =
- descriptor.findFieldByName("optional_foreign_message");
- FieldDescriptor importFieldDescriptor =
- descriptor.findFieldByName("optional_import_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message");
+ FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("optional_foreign_message");
+ FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("optional_import_message");
// Mutate the message with new field builder
// Mutate nested message
TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
- Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor)
- .mergeFrom((Message) builder1.getField(fieldDescriptor));
+ Message.Builder fieldBuilder1 =
+ builder1
+ .newBuilderForField(fieldDescriptor)
+ .mergeFrom((Message) builder1.getField(fieldDescriptor));
FieldDescriptor subFieldDescriptor1 =
fieldBuilder1.getDescriptorForType().findFieldByName("bb");
fieldBuilder1.setField(subFieldDescriptor1, 1);
builder1.setField(fieldDescriptor, fieldBuilder1.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
- foreignFieldDescriptor)
- .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
+ Message.Builder foreignFieldBuilder1 =
+ builder1
+ .newBuilderForField(foreignFieldDescriptor)
+ .mergeFrom((Message) builder1.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor1 =
foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
builder1.setField(foreignFieldDescriptor, foreignFieldBuilder1.build());
// Mutate import message
- Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
- importFieldDescriptor)
- .mergeFrom((Message) builder1.getField(importFieldDescriptor));
+ Message.Builder importFieldBuilder1 =
+ builder1
+ .newBuilderForField(importFieldDescriptor)
+ .mergeFrom((Message) builder1.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor1 =
importFieldBuilder1.getDescriptorForType().findFieldByName("d");
importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
@@ -1063,18 +1096,20 @@ public class GeneratedMessageTest extends TestCase {
builder2.setField(fieldDescriptor, fieldBuilder2.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
- foreignFieldDescriptor)
- .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
+ Message.Builder foreignFieldBuilder2 =
+ builder2
+ .newBuilderForField(foreignFieldDescriptor)
+ .mergeFrom((Message) builder2.getField(foreignFieldDescriptor));
FieldDescriptor subForeignFieldDescriptor2 =
foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
builder2.setField(foreignFieldDescriptor, foreignFieldBuilder2.build());
// Mutate import message
- Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
- importFieldDescriptor)
- .mergeFrom((Message) builder2.getField(importFieldDescriptor));
+ Message.Builder importFieldBuilder2 =
+ builder2
+ .newBuilderForField(importFieldDescriptor)
+ .mergeFrom((Message) builder2.getField(importFieldDescriptor));
FieldDescriptor subImportFieldDescriptor2 =
importFieldBuilder2.getDescriptorForType().findFieldByName("d");
importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
@@ -1088,10 +1123,9 @@ public class GeneratedMessageTest extends TestCase {
public void testGetFieldBuilderWithInitializedValue() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("optional_nested_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("optional_nested_message");
- // Before setting field, builder is initialized by default value.
+ // Before setting field, builder is initialized by default value.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
NestedMessage.Builder fieldBuilder =
(NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
@@ -1099,12 +1133,10 @@ public class GeneratedMessageTest extends TestCase {
// Setting field value with new field builder instance.
builder = TestAllTypes.newBuilder();
- NestedMessage.Builder newFieldBuilder =
- builder.getOptionalNestedMessageBuilder();
+ NestedMessage.Builder newFieldBuilder = builder.getOptionalNestedMessageBuilder();
newFieldBuilder.setBb(2);
// Then get the field builder instance by getFieldBuilder().
- fieldBuilder =
- (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
+ fieldBuilder = (NestedMessage.Builder) builder.getFieldBuilder(fieldDescriptor);
// It should contain new value.
assertEquals(2, fieldBuilder.getBb());
// These two builder should be equal.
@@ -1121,8 +1153,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("optional_nested_enum"));
+ builder.getFieldBuilder(descriptor.findFieldByName("optional_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1134,15 +1165,13 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("repeated_nested_enum"));
+ builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_enum"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
- builder.getFieldBuilder(
- descriptor.findFieldByName("repeated_nested_message"));
+ builder.getFieldBuilder(descriptor.findFieldByName("repeated_nested_message"));
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1157,25 +1186,25 @@ public class GeneratedMessageTest extends TestCase {
// expected name. There is nothing else to test.
OuterClassNameTestOuterClass.OuterClassNameTest message =
OuterClassNameTestOuterClass.OuterClassNameTest.newBuilder().build();
- assertTrue(message.getDescriptorForType() ==
- OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor());
+ assertTrue(
+ message.getDescriptorForType()
+ == OuterClassNameTestOuterClass.OuterClassNameTest.getDescriptor());
- OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2
- message2 = OuterClassNameTest2OuterClass.TestMessage2.NestedMessage
- .OuterClassNameTest2.newBuilder().build();
+ OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2 message2 =
+ OuterClassNameTest2OuterClass.TestMessage2.NestedMessage.OuterClassNameTest2.newBuilder()
+ .build();
assertEquals(0, message2.getSerializedSize());
- OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3
- enumValue = OuterClassNameTest3OuterClass.TestMessage3.NestedMessage
- .OuterClassNameTest3.DUMMY_VALUE;
+ OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3 enumValue =
+ OuterClassNameTest3OuterClass.TestMessage3.NestedMessage.OuterClassNameTest3.DUMMY_VALUE;
assertEquals(1, enumValue.getNumber());
}
// =================================================================
// oneof generated code test
public void testOneofEnumCase() throws Exception {
- TestOneof2 message = TestOneof2.newBuilder()
- .setFooInt(123).setFooString("foo").setFooCord("bar").build();
+ TestOneof2 message =
+ TestOneof2.newBuilder().setFooInt(123).setFooString("foo").setFooCord("bar").build();
TestUtil.assertAtMostOneFieldSetOneof(message);
}
@@ -1188,8 +1217,7 @@ public class GeneratedMessageTest extends TestCase {
public void testSetOneofClearsOthers() throws Exception {
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message =
- builder.setFooInt(123).setFooString("foo").buildPartial();
+ TestOneof2 message = builder.setFooInt(123).setFooString("foo").buildPartial();
assertTrue(message.hasFooString());
TestUtil.assertAtMostOneFieldSetOneof(message);
@@ -1209,8 +1237,10 @@ public class GeneratedMessageTest extends TestCase {
assertTrue(message.hasFooEnum());
TestUtil.assertAtMostOneFieldSetOneof(message);
- message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).buildPartial();
+ message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .buildPartial();
assertTrue(message.hasFooMessage());
TestUtil.assertAtMostOneFieldSetOneof(message);
@@ -1326,8 +1356,7 @@ public class GeneratedMessageTest extends TestCase {
// set
TestOneof2.Builder builder = TestOneof2.newBuilder();
assertEquals(0, builder.getFooMessage().getQuxInt());
- builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
+ builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build());
assertTrue(builder.hasFooMessage());
assertEquals(234, builder.getFooMessage().getQuxInt());
TestOneof2 message = builder.buildPartial();
@@ -1342,8 +1371,7 @@ public class GeneratedMessageTest extends TestCase {
// nested builder
builder = TestOneof2.newBuilder();
- assertSame(builder.getFooMessageOrBuilder(),
- TestOneof2.NestedMessage.getDefaultInstance());
+ assertSame(builder.getFooMessageOrBuilder(), TestOneof2.NestedMessage.getDefaultInstance());
assertFalse(builder.hasFooMessage());
builder.getFooMessageBuilder().setQuxInt(123);
assertTrue(builder.hasFooMessage());
@@ -1387,8 +1415,10 @@ public class GeneratedMessageTest extends TestCase {
// Message
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
+ TestOneof2 message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .build();
TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build();
assertTrue(message2.hasFooMessage());
assertEquals(234, message2.getFooMessage().getQuxInt());
@@ -1429,8 +1459,10 @@ public class GeneratedMessageTest extends TestCase {
// Message
{
TestOneof2.Builder builder = TestOneof2.newBuilder();
- TestOneof2 message = builder.setFooMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build();
+ TestOneof2 message =
+ builder
+ .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build())
+ .build();
ByteString serialized = message.toByteString();
TestOneof2 message2 = TestOneof2.parseFrom(serialized);
assertTrue(message2.hasFooMessage());
@@ -1452,40 +1484,32 @@ public class GeneratedMessageTest extends TestCase {
public void testGetRepeatedFieldBuilder() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("repeated_nested_message");
- FieldDescriptor foreignFieldDescriptor =
- descriptor.findFieldByName("repeated_foreign_message");
- FieldDescriptor importFieldDescriptor =
- descriptor.findFieldByName("repeated_import_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message");
+ FieldDescriptor foreignFieldDescriptor = descriptor.findFieldByName("repeated_foreign_message");
+ FieldDescriptor importFieldDescriptor = descriptor.findFieldByName("repeated_import_message");
// Mutate the message with new field builder
// Mutate nested message
TestAllTypes.Builder builder1 = TestAllTypes.newBuilder();
- Message.Builder fieldBuilder1 = builder1.newBuilderForField(
- fieldDescriptor);
+ Message.Builder fieldBuilder1 = builder1.newBuilderForField(fieldDescriptor);
FieldDescriptor subFieldDescriptor1 =
fieldBuilder1.getDescriptorForType().findFieldByName("bb");
fieldBuilder1.setField(subFieldDescriptor1, 1);
builder1.addRepeatedField(fieldDescriptor, fieldBuilder1.build());
// Mutate foreign message
- Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(
- foreignFieldDescriptor);
+ Message.Builder foreignFieldBuilder1 = builder1.newBuilderForField(foreignFieldDescriptor);
FieldDescriptor subForeignFieldDescriptor1 =
foreignFieldBuilder1.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder1.setField(subForeignFieldDescriptor1, 2);
- builder1.addRepeatedField(foreignFieldDescriptor,
- foreignFieldBuilder1.build());
+ builder1.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder1.build());
// Mutate import message
- Message.Builder importFieldBuilder1 = builder1.newBuilderForField(
- importFieldDescriptor);
+ Message.Builder importFieldBuilder1 = builder1.newBuilderForField(importFieldDescriptor);
FieldDescriptor subImportFieldDescriptor1 =
importFieldBuilder1.getDescriptorForType().findFieldByName("d");
importFieldBuilder1.setField(subImportFieldDescriptor1, 3);
- builder1.addRepeatedField(importFieldDescriptor,
- importFieldBuilder1.build());
+ builder1.addRepeatedField(importFieldDescriptor, importFieldBuilder1.build());
Message newMessage1 = builder1.build();
@@ -1493,29 +1517,24 @@ public class GeneratedMessageTest extends TestCase {
// Mutate nested message
TestAllTypes.Builder builder2 = TestAllTypes.newBuilder();
builder2.addRepeatedNestedMessageBuilder();
- Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(
- fieldDescriptor, 0);
+ Message.Builder fieldBuilder2 = builder2.getRepeatedFieldBuilder(fieldDescriptor, 0);
FieldDescriptor subFieldDescriptor2 =
fieldBuilder2.getDescriptorForType().findFieldByName("bb");
fieldBuilder2.setField(subFieldDescriptor2, 1);
// Mutate foreign message
- Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(
- foreignFieldDescriptor);
+ Message.Builder foreignFieldBuilder2 = builder2.newBuilderForField(foreignFieldDescriptor);
FieldDescriptor subForeignFieldDescriptor2 =
foreignFieldBuilder2.getDescriptorForType().findFieldByName("c");
foreignFieldBuilder2.setField(subForeignFieldDescriptor2, 2);
- builder2.addRepeatedField(foreignFieldDescriptor,
- foreignFieldBuilder2.build());
+ builder2.addRepeatedField(foreignFieldDescriptor, foreignFieldBuilder2.build());
// Mutate import message
- Message.Builder importFieldBuilder2 = builder2.newBuilderForField(
- importFieldDescriptor);
+ Message.Builder importFieldBuilder2 = builder2.newBuilderForField(importFieldDescriptor);
FieldDescriptor subImportFieldDescriptor2 =
importFieldBuilder2.getDescriptorForType().findFieldByName("d");
importFieldBuilder2.setField(subImportFieldDescriptor2, 3);
- builder2.addRepeatedField(importFieldDescriptor,
- importFieldBuilder2.build());
+ builder2.addRepeatedField(importFieldDescriptor, importFieldBuilder2.build());
Message newMessage2 = builder2.build();
@@ -1525,10 +1544,9 @@ public class GeneratedMessageTest extends TestCase {
public void testGetRepeatedFieldBuilderWithInitializedValue() {
Descriptor descriptor = TestAllTypes.getDescriptor();
- FieldDescriptor fieldDescriptor =
- descriptor.findFieldByName("repeated_nested_message");
+ FieldDescriptor fieldDescriptor = descriptor.findFieldByName("repeated_nested_message");
- // Before setting field, builder is initialized by default value.
+ // Before setting field, builder is initialized by default value.
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.addRepeatedNestedMessageBuilder();
NestedMessage.Builder fieldBuilder =
@@ -1537,12 +1555,10 @@ public class GeneratedMessageTest extends TestCase {
// Setting field value with new field builder instance.
builder = TestAllTypes.newBuilder();
- NestedMessage.Builder newFieldBuilder =
- builder.addRepeatedNestedMessageBuilder();
+ NestedMessage.Builder newFieldBuilder = builder.addRepeatedNestedMessageBuilder();
newFieldBuilder.setBb(2);
// Then get the field builder instance by getRepeatedFieldBuilder().
- fieldBuilder =
- (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
+ fieldBuilder = (NestedMessage.Builder) builder.getRepeatedFieldBuilder(fieldDescriptor, 0);
// It should contain new value.
assertEquals(2, fieldBuilder.getBb());
// These two builder should be equal.
@@ -1559,8 +1575,7 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("repeated_nested_enum"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("repeated_nested_enum"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
@@ -1572,15 +1587,13 @@ public class GeneratedMessageTest extends TestCase {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("optional_nested_enum"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_enum"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
}
try {
- builder.getRepeatedFieldBuilder(
- descriptor.findFieldByName("optional_nested_message"), 0);
+ builder.getRepeatedFieldBuilder(descriptor.findFieldByName("optional_nested_message"), 0);
fail("Exception was not thrown");
} catch (UnsupportedOperationException e) {
// We expect this exception.
diff --git a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
index d8e97d4f..d6943e02 100644
--- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class IntArrayListTest extends TestCase {
- private static final IntArrayList UNARY_LIST =
- newImmutableIntArrayList(1);
- private static final IntArrayList TERTIARY_LIST =
- newImmutableIntArrayList(1, 2, 3);
+ private static final IntArrayList UNARY_LIST = newImmutableIntArrayList(1);
+ private static final IntArrayList TERTIARY_LIST = newImmutableIntArrayList(1, 2, 3);
private IntArrayList list;
@@ -225,9 +223,7 @@ public class IntArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Integer.valueOf(5 + i));
}
- assertEquals(
- asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10),
- list);
+ assertEquals(asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10), list);
try {
list.add(-1, 5);
@@ -312,7 +308,7 @@ public class IntArrayListTest extends TestCase {
assertEquals(0, toRemove.size());
}
- private void assertImmutable(IntArrayList list) {
+ private void assertImmutable(IntList list) {
if (list.contains(1)) {
throw new RuntimeException("Cannot test the immutability of lists that contain 1.");
}
diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
index 756049b4..2518f20d 100644
--- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
+++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8Test.java
@@ -39,45 +39,36 @@ import static com.google.protobuf.IsValidUtf8TestUtil.testBytes;
import com.google.protobuf.IsValidUtf8TestUtil.ByteStringFactory;
import com.google.protobuf.IsValidUtf8TestUtil.Shard;
-
import junit.framework.TestCase;
/**
- * Tests cases for {@link ByteString#isValidUtf8()}. This includes three
- * brute force tests that actually test every permutation of one byte, two byte,
- * and three byte sequences to ensure that the method produces the right result
- * for every possible byte encoding where "right" means it's consistent with
- * java's UTF-8 string encoding/decoding such that the method returns true for
- * any sequence that will round trip when converted to a String and then back to
- * bytes and will return false for any sequence that will not round trip.
- * See also {@link IsValidUtf8FourByteTest}. It also includes some
- * other more targeted tests.
+ * Tests cases for {@link ByteString#isValidUtf8()}. This includes three brute force tests that
+ * actually test every permutation of one byte, two byte, and three byte sequences to ensure that
+ * the method produces the right result for every possible byte encoding where "right" means it's
+ * consistent with java's UTF-8 string encoding/decoding such that the method returns true for any
+ * sequence that will round trip when converted to a String and then back to bytes and will return
+ * false for any sequence that will not round trip. See also {@link IsValidUtf8FourByteTest}. It
+ * also includes some other more targeted tests.
*
* @author jonp@google.com (Jon Perlow)
* @author martinrb@google.com (Martin Buchholz)
*/
public class IsValidUtf8Test extends TestCase {
- /**
- * Tests that round tripping of all two byte permutations work.
- */
+ /** Tests that round tripping of all two byte permutations work. */
public void testIsValidUtf8_1Byte() {
testBytes(LITERAL_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(HEAP_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(DIRECT_NIO_FACTORY, 1, EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT);
}
- /**
- * Tests that round tripping of all two byte permutations work.
- */
+ /** Tests that round tripping of all two byte permutations work. */
public void testIsValidUtf8_2Bytes() {
testBytes(LITERAL_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(HEAP_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
testBytes(DIRECT_NIO_FACTORY, 2, IsValidUtf8TestUtil.EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT);
}
- /**
- * Tests that round tripping of all three byte permutations work.
- */
+ /** Tests that round tripping of all three byte permutations work. */
public void testIsValidUtf8_3Bytes() {
// Travis' OOM killer doesn't like this test
if (System.getenv("TRAVIS") == null) {
@@ -88,10 +79,9 @@ public class IsValidUtf8Test extends TestCase {
}
/**
- * Tests that round tripping of a sample of four byte permutations work.
- * All permutations are prohibitively expensive to test for automated runs;
- * {@link IsValidUtf8FourByteTest} is used for full coverage. This method
- * tests specific four-byte cases.
+ * Tests that round tripping of a sample of four byte permutations work. All permutations are
+ * prohibitively expensive to test for automated runs; {@link IsValidUtf8FourByteTest} is used for
+ * full coverage. This method tests specific four-byte cases.
*/
public void testIsValidUtf8_4BytesSamples() {
// Valid 4 byte.
@@ -106,9 +96,7 @@ public class IsValidUtf8Test extends TestCase {
assertInvalidUtf8(0xF4, 0x90, 0xAD, 0xA2);
}
- /**
- * Tests some hard-coded test cases.
- */
+ /** Tests some hard-coded test cases. */
public void testSomeSequences() {
// Empty
assertTrue(asBytes("").isValidUtf8());
@@ -149,11 +137,12 @@ public class IsValidUtf8Test extends TestCase {
assertTrue(not ^ leaf.isValidUtf8());
assertTrue(not ^ sub.isValidUtf8());
ByteString[] ropes = {
- RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf),
- RopeByteString.newInstanceForTest(ByteString.EMPTY, sub),
- RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(sub, ByteString.EMPTY),
- RopeByteString.newInstanceForTest(sub, leaf)};
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, leaf),
+ RopeByteString.newInstanceForTest(ByteString.EMPTY, sub),
+ RopeByteString.newInstanceForTest(leaf, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(sub, ByteString.EMPTY),
+ RopeByteString.newInstanceForTest(sub, leaf)
+ };
for (ByteString rope : ropes) {
assertTrue(not ^ rope.isValidUtf8());
}
diff --git a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
index 1bcf63e7..2c086e11 100644
--- a/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java
@@ -50,8 +50,7 @@ import java.util.Random;
import java.util.logging.Logger;
/**
- * Shared testing code for {@link IsValidUtf8Test} and
- * {@link IsValidUtf8FourByteTest}.
+ * Shared testing code for {@link IsValidUtf8Test} and {@link IsValidUtf8FourByteTest}.
*
* @author jonp@google.com (Jon Perlow)
* @author martinrb@google.com (Martin Buchholz)
@@ -65,44 +64,47 @@ final class IsValidUtf8TestUtil {
ByteString newByteString(byte[] bytes);
}
- static final ByteStringFactory LITERAL_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- return ByteString.wrap(bytes);
- }
- };
+ static final ByteStringFactory LITERAL_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ return ByteString.wrap(bytes);
+ }
+ };
- static final ByteStringFactory HEAP_NIO_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- return new NioByteString(ByteBuffer.wrap(bytes));
- }
- };
+ static final ByteStringFactory HEAP_NIO_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ return new NioByteString(ByteBuffer.wrap(bytes));
+ }
+ };
private static ThreadLocal<SoftReference<ByteBuffer>> directBuffer =
new ThreadLocal<SoftReference<ByteBuffer>>();
/**
- * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this
- * uses a thread local direct buffer. This means that each call will overwrite the buffer's
- * contents from the previous call, so the calling code must be careful not to continue using
- * a buffer returned from a previous invocation.
+ * Factory for direct {@link ByteBuffer} instances. To reduce direct memory usage, this uses a
+ * thread local direct buffer. This means that each call will overwrite the buffer's contents from
+ * the previous call, so the calling code must be careful not to continue using a buffer returned
+ * from a previous invocation.
*/
- static final ByteStringFactory DIRECT_NIO_FACTORY = new ByteStringFactory() {
- @Override
- public ByteString newByteString(byte[] bytes) {
- SoftReference<ByteBuffer> ref = directBuffer.get();
- ByteBuffer buffer = ref == null ? null : ref.get();
- if (buffer == null || buffer.capacity() < bytes.length) {
- buffer = ByteBuffer.allocateDirect(bytes.length);
- directBuffer.set(new SoftReference<ByteBuffer>(buffer));
- }
- buffer.clear();
- buffer.put(bytes);
- buffer.flip();
- return new NioByteString(buffer);
- }
- };
+ static final ByteStringFactory DIRECT_NIO_FACTORY =
+ new ByteStringFactory() {
+ @Override
+ public ByteString newByteString(byte[] bytes) {
+ SoftReference<ByteBuffer> ref = directBuffer.get();
+ ByteBuffer buffer = ref == null ? null : ref.get();
+ if (buffer == null || buffer.capacity() < bytes.length) {
+ buffer = ByteBuffer.allocateDirect(bytes.length);
+ directBuffer.set(new SoftReference<ByteBuffer>(buffer));
+ }
+ buffer.clear();
+ buffer.put(bytes);
+ buffer.flip();
+ return new NioByteString(buffer);
+ }
+ };
// 128 - [chars 0x0000 to 0x007f]
static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x007f - 0x0000 + 1;
@@ -116,9 +118,10 @@ final class IsValidUtf8TestUtil {
// 18,304
static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT =
// Both bytes are one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) +
- // The possible number of two byte characters
- TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2)
+ +
+ // The possible number of two byte characters
+ TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 2048
static final long THREE_BYTE_SURROGATES = 2 * 1024;
@@ -130,11 +133,13 @@ final class IsValidUtf8TestUtil {
// 2,650,112
static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) +
- // One two byte character and a one byte character
- 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Three byte characters
- THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3)
+ +
+ // One two byte character and a one byte character
+ 2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Three byte characters
+ THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 1,048,576 [chars 0x10000L to 0x10FFFF]
static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS = 0x10FFFF - 0x10000L + 1;
@@ -142,17 +147,22 @@ final class IsValidUtf8TestUtil {
// 289,571,839
static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
- (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) +
- // One and three byte characters
- 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Two two byte characters
- TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS +
- // Permutations of one and two byte characters
- 3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
- * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
- +
- // Four byte characters
- FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
+ (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4)
+ +
+ // One and three byte characters
+ 2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Two two byte characters
+ TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Permutations of one and two byte characters
+ 3
+ * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS
+ +
+ // Four byte characters
+ FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
static final class Shard {
final long index;
@@ -160,7 +170,6 @@ final class IsValidUtf8TestUtil {
final long lim;
final long expected;
-
public Shard(long index, long start, long lim, long expected) {
assertTrue(start < lim);
this.index = index;
@@ -206,7 +215,6 @@ final class IsValidUtf8TestUtil {
static final List<Shard> FOUR_BYTE_SHARDS =
generateFourByteShards(128, FOUR_BYTE_SHARDS_EXPECTED_ROUNTRIPPABLES);
-
private static List<Shard> generateFourByteShards(int numShards, long[] expected) {
assertEquals(numShards, expected.length);
List<Shard> shards = new ArrayList<Shard>(numShards);
@@ -220,8 +228,7 @@ final class IsValidUtf8TestUtil {
}
/**
- * Helper to run the loop to test all the permutations for the number of bytes
- * specified.
+ * Helper to run the loop to test all the permutations for the number of bytes specified.
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
@@ -232,16 +239,15 @@ final class IsValidUtf8TestUtil {
}
/**
- * Helper to run the loop to test all the permutations for the number of bytes
- * specified. This overload is useful for debugging to get the loop to start
- * at a certain character.
+ * Helper to run the loop to test all the permutations for the number of bytes specified. This
+ * overload is useful for debugging to get the loop to start at a certain character.
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
* @param start the starting bytes encoded as a long as big-endian
- * @param lim the limit of bytes to process encoded as a long as big-endian,
- * or -1 to mean the max limit for numBytes
+ * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
+ * limit for numBytes
*/
static void testBytes(
ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) {
@@ -301,9 +307,10 @@ final class IsValidUtf8TestUtil {
assertEquals(isRoundTrippable, (state3 == Utf8.COMPLETE));
// Test ropes built out of small partial sequences
- ByteString rope = RopeByteString.newInstanceForTest(
- bs.substring(0, i),
- RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes)));
+ ByteString rope =
+ RopeByteString.newInstanceForTest(
+ bs.substring(0, i),
+ RopeByteString.newInstanceForTest(bs.substring(i, j), bs.substring(j, numBytes)));
assertSame(RopeByteString.class, rope.getClass());
ByteString[] byteStrings = {bs, bs.substring(0, numBytes), rope};
@@ -336,27 +343,28 @@ final class IsValidUtf8TestUtil {
}
/**
- * Variation of {@link #testBytes} that does less allocation using the
- * low-level encoders/decoders directly. Checked in because it's useful for
- * debugging when trying to process bytes faster, but since it doesn't use the
- * actual String class, it's possible for incompatibilities to develop
+ * Variation of {@link #testBytes} that does less allocation using the low-level encoders/decoders
+ * directly. Checked in because it's useful for debugging when trying to process bytes faster, but
+ * since it doesn't use the actual String class, it's possible for incompatibilities to develop
* (although unlikely).
*
* @param factory the factory for {@link ByteString} instances.
* @param numBytes the number of bytes in the byte array
* @param expectedCount the expected number of roundtrippable permutations
* @param start the starting bytes encoded as a long as big-endian
- * @param lim the limit of bytes to process encoded as a long as big-endian,
- * or -1 to mean the max limit for numBytes
+ * @param lim the limit of bytes to process encoded as a long as big-endian, or -1 to mean the max
+ * limit for numBytes
*/
static void testBytesUsingByteBuffers(
ByteStringFactory factory, int numBytes, long expectedCount, long start, long lim) {
CharsetDecoder decoder =
- Internal.UTF_8.newDecoder()
+ Internal.UTF_8
+ .newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
CharsetEncoder encoder =
- Internal.UTF_8.newEncoder()
+ Internal.UTF_8
+ .newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
byte[] bytes = new byte[numBytes];
@@ -434,8 +442,10 @@ final class IsValidUtf8TestUtil {
}
private static void outputFailure(long byteChar, byte[] bytes, byte[] after, int len) {
- fail("Failure: (" + Long.toHexString(byteChar) + ") " + toHexString(bytes) + " => "
- + toHexString(after, len));
+ fail(
+ String.format(
+ "Failure: (%s) %s => %s",
+ Long.toHexString(byteChar), toHexString(bytes), toHexString(after, len)));
}
private static String toHexString(byte[] b) {
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 f27e8e51..a3901e91 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
@@ -42,8 +42,7 @@ import junit.framework.TestCase;
public class LazyFieldTest extends TestCase {
public void testHashCode() {
MessageLite message = TestUtil.getAllSet();
- LazyField lazyField =
- createLazyFieldFromMessage(message);
+ LazyField lazyField = createLazyFieldFromMessage(message);
assertEquals(message.hashCode(), lazyField.hashCode());
lazyField.getValue();
assertEquals(message.hashCode(), lazyField.hashCode());
@@ -102,8 +101,8 @@ public class LazyFieldTest extends TestCase {
private LazyField createLazyFieldFromMessage(MessageLite message) {
ByteString bytes = message.toByteString();
- return new LazyField(message.getDefaultInstanceForType(),
- TestUtil.getExtensionRegistry(), bytes);
+ return new LazyField(
+ message.getDefaultInstanceForType(), TestUtil.getExtensionRegistry(), bytes);
}
private void changeValue(LazyField lazyField) {
@@ -114,7 +113,6 @@ public class LazyFieldTest extends TestCase {
}
private void assertNotEqual(Object unexpected, Object actual) {
- assertFalse(unexpected == actual
- || (unexpected != null && unexpected.equals(actual)));
+ assertFalse(unexpected == actual || (unexpected != null && unexpected.equals(actual)));
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
index 968ca206..c5880d50 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
@@ -44,8 +44,6 @@ import junit.framework.TestCase;
*/
public class LazyMessageLiteTest extends TestCase {
- private Parser<LazyInnerMessageLite> originalLazyInnerMessageLiteParser;
-
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -57,19 +55,16 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSetValues() {
- LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder()
- .setNum(3)
- .build();
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(2)
- .setNested(nested)
- .build();
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .setInner(inner)
- .setOneofNum(123)
- .setOneofInner(inner)
- .build();
+ LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build();
+ LazyInnerMessageLite inner =
+ LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .setNum(1)
+ .setInner(inner)
+ .setOneofNum(123)
+ .setOneofInner(inner)
+ .build();
assertEquals(1, outer.getNum());
assertEquals(421, outer.getNumWithDefault());
@@ -90,44 +85,43 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSetRepeatedValues() {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
- .build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .setNum(1)
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
+ .build();
assertEquals(1, outer.getNum());
assertEquals(2, outer.getRepeatedInnerCount());
assertEquals(119, outer.getRepeatedInner(0).getNum());
assertEquals(122, outer.getRepeatedInner(1).getNum());
}
-
+
public void testRepeatedMutability() throws Exception {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
- .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
- .build();
-
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder()
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
+ .addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
+ .build();
+
outer = LazyMessageLite.parseFrom(outer.toByteArray());
try {
outer.getRepeatedInnerList().set(1, null);
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
public void testAddAll() {
- ArrayList<LazyInnerMessageLite> inners = new ArrayList<LazyInnerMessageLite>();
+ ArrayList<LazyInnerMessageLite> inners = new ArrayList<>();
int count = 4;
for (int i = 0; i < count; i++) {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(i)
- .build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(i).build();
inners.add(inner);
}
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .addAllRepeatedInner(inners)
- .build();
+ LazyMessageLite outer = LazyMessageLite.newBuilder().addAllRepeatedInner(inners).build();
assertEquals(count, outer.getRepeatedInnerCount());
for (int i = 0; i < count; i++) {
assertEquals(i, outer.getRepeatedInner(i).getNum());
@@ -135,8 +129,7 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testGetDefaultValues() {
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .build();
+ LazyMessageLite outer = LazyMessageLite.getDefaultInstance();
assertEquals(0, outer.getNum());
assertEquals(421, outer.getNumWithDefault());
@@ -156,15 +149,12 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testClearValues() {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().setNum(115).build();
LazyMessageLite.Builder outerBuilder = LazyMessageLite.newBuilder();
assertEquals(0, outerBuilder.build().getNum());
-
// Set/Clear num
outerBuilder.setNum(100);
@@ -178,9 +168,9 @@ public class LazyMessageLiteTest extends TestCase {
assertEquals(421, outerBuilder.build().getNumWithDefault());
assertFalse(outerBuilder.build().hasInner());
-
// Set/Clear all
- outerBuilder.setNum(100)
+ outerBuilder
+ .setNum(100)
.setInner(inner)
.addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(119))
.addRepeatedInner(LazyInnerMessageLite.newBuilder().setNum(122))
@@ -210,23 +200,17 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testMergeValues() {
- LazyMessageLite outerBase = LazyMessageLite.newBuilder()
- .setNumWithDefault(122)
- .build();
-
- LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
- LazyMessageLite outerMerging = LazyMessageLite.newBuilder()
- .setNum(119)
- .setInner(innerMerging)
- .setOneofInner(innerMerging)
- .build();
-
- LazyMessageLite merged = LazyMessageLite
- .newBuilder(outerBase)
- .mergeFrom(outerMerging)
- .build();
+ LazyMessageLite outerBase = LazyMessageLite.newBuilder().setNumWithDefault(122).build();
+
+ LazyInnerMessageLite innerMerging = LazyInnerMessageLite.newBuilder().setNum(115).build();
+ LazyMessageLite outerMerging =
+ LazyMessageLite.newBuilder()
+ .setNum(119)
+ .setInner(innerMerging)
+ .setOneofInner(innerMerging)
+ .build();
+
+ LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build();
assertEquals(119, merged.getNum());
assertEquals(122, merged.getNumWithDefault());
assertEquals(115, merged.getInner().getNum());
@@ -236,23 +220,18 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testMergeDefaultValues() {
- LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder()
- .setNum(115)
- .build();
- LazyMessageLite outerBase = LazyMessageLite.newBuilder()
- .setNum(119)
- .setNumWithDefault(122)
- .setInner(innerBase)
- .setOneofInner(innerBase)
- .build();
-
- LazyMessageLite outerMerging = LazyMessageLite.newBuilder()
- .build();
-
- LazyMessageLite merged = LazyMessageLite
- .newBuilder(outerBase)
- .mergeFrom(outerMerging)
- .build();
+ LazyInnerMessageLite innerBase = LazyInnerMessageLite.newBuilder().setNum(115).build();
+ LazyMessageLite outerBase =
+ LazyMessageLite.newBuilder()
+ .setNum(119)
+ .setNumWithDefault(122)
+ .setInner(innerBase)
+ .setOneofInner(innerBase)
+ .build();
+
+ LazyMessageLite outerMerging = LazyMessageLite.getDefaultInstance();
+
+ LazyMessageLite merged = LazyMessageLite.newBuilder(outerBase).mergeFrom(outerMerging).build();
// Merging default-instance shouldn't overwrite values in the base message.
assertEquals(119, merged.getNum());
assertEquals(122, merged.getNumWithDefault());
@@ -264,7 +243,7 @@ public class LazyMessageLiteTest extends TestCase {
// Regression test for b/28198805.
public void testMergeOneofMessages() throws Exception {
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder().build();
+ LazyInnerMessageLite inner = LazyInnerMessageLite.getDefaultInstance();
LazyMessageLite outer = LazyMessageLite.newBuilder().setOneofInner(inner).build();
ByteString data1 = outer.toByteString();
@@ -280,18 +259,11 @@ public class LazyMessageLiteTest extends TestCase {
}
public void testSerialize() throws InvalidProtocolBufferException {
- LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder()
- .setNum(3)
- .build();
- LazyInnerMessageLite inner = LazyInnerMessageLite.newBuilder()
- .setNum(2)
- .setNested(nested)
- .build();
- LazyMessageLite outer = LazyMessageLite.newBuilder()
- .setNum(1)
- .setInner(inner)
- .setOneofInner(inner)
- .build();
+ LazyNestedInnerMessageLite nested = LazyNestedInnerMessageLite.newBuilder().setNum(3).build();
+ LazyInnerMessageLite inner =
+ LazyInnerMessageLite.newBuilder().setNum(2).setNested(nested).build();
+ LazyMessageLite outer =
+ LazyMessageLite.newBuilder().setNum(1).setInner(inner).setOneofInner(inner).build();
ByteString bytes = outer.toByteString();
assertEquals(bytes.size(), outer.getSerializedSize());
@@ -299,18 +271,18 @@ public class LazyMessageLiteTest extends TestCase {
LazyMessageLite deserialized = LazyMessageLite.parseFrom(bytes);
assertEquals(1, deserialized.getNum());
- assertEquals(421, deserialized.getNumWithDefault());
+ assertEquals(421, deserialized.getNumWithDefault());
- assertEquals(2, deserialized.getInner().getNum());
- assertEquals(42, deserialized.getInner().getNumWithDefault());
+ assertEquals(2, deserialized.getInner().getNum());
+ assertEquals(42, deserialized.getInner().getNumWithDefault());
- assertEquals(3, deserialized.getInner().getNested().getNum());
- assertEquals(4, deserialized.getInner().getNested().getNumWithDefault());
+ assertEquals(3, deserialized.getInner().getNested().getNum());
+ assertEquals(4, deserialized.getInner().getNested().getNumWithDefault());
- assertEquals(2, deserialized.getOneofInner().getNum());
- assertEquals(42, deserialized.getOneofInner().getNumWithDefault());
- assertEquals(3, deserialized.getOneofInner().getNested().getNum());
- assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault());
+ assertEquals(2, deserialized.getOneofInner().getNum());
+ assertEquals(42, deserialized.getOneofInner().getNumWithDefault());
+ assertEquals(3, deserialized.getOneofInner().getNested().getNum());
+ assertEquals(4, deserialized.getOneofInner().getNested().getNumWithDefault());
assertEquals(bytes, deserialized.toByteString());
}
@@ -318,8 +290,7 @@ public class LazyMessageLiteTest extends TestCase {
public void testExtensions() throws Exception {
LazyInnerMessageLite.Builder innerBuilder = LazyInnerMessageLite.newBuilder();
innerBuilder.setExtension(
- LazyExtension.extension, LazyExtension.newBuilder()
- .setName("name").build());
+ LazyExtension.extension, LazyExtension.newBuilder().setName("name").build());
assertTrue(innerBuilder.hasExtension(LazyExtension.extension));
assertEquals("name", innerBuilder.getExtension(LazyExtension.extension).getName());
@@ -327,8 +298,7 @@ public class LazyMessageLiteTest extends TestCase {
assertTrue(innerMessage.hasExtension(LazyExtension.extension));
assertEquals("name", innerMessage.getExtension(LazyExtension.extension).getName());
- LazyMessageLite lite = LazyMessageLite.newBuilder()
- .setInner(innerMessage).build();
+ LazyMessageLite lite = LazyMessageLite.newBuilder().setInner(innerMessage).build();
assertTrue(lite.getInner().hasExtension(LazyExtension.extension));
assertEquals("name", lite.getInner().getExtension(LazyExtension.extension).getName());
}
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 2fc3124d..24d0038b 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
@@ -46,13 +46,13 @@ import junit.framework.TestCase;
*/
public class LazyStringArrayListTest extends TestCase {
- private static String STRING_A = "A";
- private static String STRING_B = "B";
- private static String STRING_C = "C";
+ private static final String STRING_A = "A";
+ private static final String STRING_B = "B";
+ private static final String STRING_C = "C";
- private static ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
- private static ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
- private static ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
+ private static final ByteString BYTE_STRING_A = ByteString.copyFromUtf8("A");
+ private static final ByteString BYTE_STRING_B = ByteString.copyFromUtf8("B");
+ private static final ByteString BYTE_STRING_C = ByteString.copyFromUtf8("C");
public void testJustStrings() {
LazyStringArrayList list = new LazyStringArrayList();
@@ -175,7 +175,7 @@ public class LazyStringArrayListTest extends TestCase {
assertSame(BYTE_STRING_B, list2.getByteString(1));
assertSame(BYTE_STRING_C, list2.getByteString(2));
}
-
+
public void testModificationWithIteration() {
LazyStringArrayList list = new LazyStringArrayList();
list.addAll(asList(STRING_A, STRING_B, STRING_C));
@@ -183,12 +183,12 @@ public class LazyStringArrayListTest extends TestCase {
assertEquals(3, list.size());
assertEquals(STRING_A, list.get(0));
assertEquals(STRING_A, iterator.next());
-
+
// Does not structurally modify.
iterator = list.iterator();
list.set(0, STRING_B);
iterator.next();
-
+
list.remove(0);
try {
iterator.next();
@@ -196,7 +196,7 @@ public class LazyStringArrayListTest extends TestCase {
} catch (ConcurrentModificationException e) {
// expected
}
-
+
iterator = list.iterator();
list.add(0, STRING_C);
try {
@@ -206,7 +206,7 @@ public class LazyStringArrayListTest extends TestCase {
// expected
}
}
-
+
public void testMakeImmutable() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
@@ -214,52 +214,52 @@ public class LazyStringArrayListTest extends TestCase {
list.add(STRING_C);
list.makeImmutable();
assertGenericListImmutable(list, STRING_A);
-
+
// LazyStringArrayList has extra methods not covered in the generic
// assertion.
-
+
try {
list.add(BYTE_STRING_A.toByteArray());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.add(BYTE_STRING_A);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAllByteArray(Collections.singletonList(BYTE_STRING_A.toByteArray()));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAllByteString(asList(BYTE_STRING_A));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.mergeFrom(new LazyStringArrayList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, BYTE_STRING_A.toByteArray());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, BYTE_STRING_A);
fail();
@@ -267,20 +267,20 @@ public class LazyStringArrayListTest extends TestCase {
// expected
}
}
-
+
public void testImmutabilityPropagation() {
LazyStringArrayList list = new LazyStringArrayList();
list.add(STRING_A);
list.makeImmutable();
assertGenericListImmutable(list.asByteStringList(), BYTE_STRING_A);
-
+
// Arrays use reference equality so need to retrieve the underlying value
// to properly test deep immutability.
List<byte[]> byteArrayList = list.asByteArrayList();
assertGenericListImmutable(byteArrayList, byteArrayList.get(0));
}
-
+
@SuppressWarnings("unchecked")
private static <T> void assertGenericListImmutable(List<T> list, T value) {
try {
@@ -289,21 +289,21 @@ public class LazyStringArrayListTest extends TestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.add(0, value);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(asList(value));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(0, asList(value));
fail();
@@ -317,42 +317,42 @@ public class LazyStringArrayListTest extends TestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.remove(0);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.remove(value);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.removeAll(asList(value));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(asList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(asList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, value);
fail();
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
index 006e4933..18c9c74e 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
@@ -30,44 +30,42 @@
package com.google.protobuf;
-
import protobuf_unittest.UnittestProto;
import java.io.IOException;
import junit.framework.TestCase;
/**
- * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to
- * strings works correctly.
+ * Tests to make sure the lazy conversion of UTF8-encoded byte arrays to strings works correctly.
*
* @author jonp@google.com (Jon Perlow)
*/
public class LazyStringEndToEndTest extends TestCase {
- private static ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
- ByteString.copyFrom(new byte[] {
- 114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
- 0, -1, 0, -30, 2, 4, -1, 0, -1, 0, });
+ private static final ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
+ ByteString.copyFrom(
+ new byte[] {
+ 114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
+ 0, -1, 0, -30, 2, 4, -1, 0, -1, 0,
+ });
private ByteString encodedTestAllTypes;
@Override
protected void setUp() throws Exception {
super.setUp();
- this.encodedTestAllTypes = UnittestProto.TestAllTypes.newBuilder()
- .setOptionalString("foo")
- .addRepeatedString("bar")
- .addRepeatedString("baz")
- .build()
- .toByteString();
+ this.encodedTestAllTypes =
+ UnittestProto.TestAllTypes.newBuilder()
+ .setOptionalString("foo")
+ .addRepeatedString("bar")
+ .addRepeatedString("baz")
+ .build()
+ .toByteString();
}
- /**
- * Tests that an invalid UTF8 string will roundtrip through a parse
- * and serialization.
- */
+ /** Tests that an invalid UTF8 string will roundtrip through a parse and serialization. */
public void testParseAndSerialize() throws InvalidProtocolBufferException {
- UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
+ UnittestProto.TestAllTypes tV2 =
+ UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
ByteString bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
@@ -77,33 +75,31 @@ public class LazyStringEndToEndTest extends TestCase {
}
public void testParseAndWrite() throws IOException {
- UnittestProto.TestAllTypes tV2 = UnittestProto.TestAllTypes.parseFrom(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
+ UnittestProto.TestAllTypes tV2 =
+ UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
byte[] sink = new byte[TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8.size()];
CodedOutputStream outputStream = CodedOutputStream.newInstance(sink);
tV2.writeTo(outputStream);
outputStream.flush();
- assertEquals(
- TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8,
- ByteString.copyFrom(sink));
+ assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, ByteString.copyFrom(sink));
}
-
+
public void testCaching() {
String a = "a";
String b = "b";
String c = "c";
- UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.newBuilder()
- .setOptionalString(a)
- .addRepeatedString(b)
- .addRepeatedString(c)
- .build();
+ UnittestProto.TestAllTypes proto =
+ UnittestProto.TestAllTypes.newBuilder()
+ .setOptionalString(a)
+ .addRepeatedString(b)
+ .addRepeatedString(c)
+ .build();
// String should be the one we passed it.
assertSame(a, proto.getOptionalString());
assertSame(b, proto.getRepeatedString(0));
assertSame(c, proto.getRepeatedString(1));
-
// Ensure serialization keeps strings cached.
proto.toByteString();
@@ -114,8 +110,7 @@ public class LazyStringEndToEndTest extends TestCase {
}
public void testNoStringCachingIfOnlyBytesAccessed() throws Exception {
- UnittestProto.TestAllTypes proto =
- UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
+ UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
ByteString optional = proto.getOptionalStringBytes();
assertSame(optional, proto.getOptionalStringBytes());
assertSame(optional, proto.toBuilder().getOptionalStringBytes());
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 5ab80ca2..b20114e0 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java
@@ -57,6 +57,8 @@ import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestOneofEquals;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.TestRecursiveOneof;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -2378,4 +2380,63 @@ public class LiteTest extends TestCase {
} catch (NullPointerException expected) {
}
}
+
+ public void testSerializeToOutputStreamThrowsIOException() {
+ try {
+ TestAllTypesLite.newBuilder()
+ .setOptionalBytes(ByteString.copyFromUtf8("hello"))
+ .build()
+ .writeTo(
+ new OutputStream() {
+
+ @Override
+ public void write(int b) throws IOException {
+ throw new IOException();
+ }
+ });
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testUnpairedSurrogatesReplacedByQuestionMark() throws InvalidProtocolBufferException {
+ String testString = "foo \ud83d bar";
+ String expectedString = "foo ? bar";
+
+ TestAllTypesLite testMessage =
+ TestAllTypesLite.newBuilder().setOptionalString(testString).build();
+ ByteString serializedMessage = testMessage.toByteString();
+
+ // Behavior is compatible with String.getBytes("UTF-8"), which replaces
+ // unpaired surrogates with a question mark.
+ TestAllTypesLite parsedMessage = TestAllTypesLite.parseFrom(serializedMessage);
+ assertEquals(expectedString, parsedMessage.getOptionalString());
+
+ // Conversion happens during serialization.
+ ByteString expectedBytes = ByteString.copyFromUtf8(expectedString);
+ assertTrue(
+ String.format(
+ "Expected serializedMessage (%s) to contain \"%s\" (%s).",
+ encodeHex(serializedMessage), expectedString, encodeHex(expectedBytes)),
+ contains(serializedMessage, expectedBytes));
+ }
+
+ private String encodeHex(ByteString bytes) {
+ String hexDigits = "0123456789abcdef";
+ StringBuilder stringBuilder = new StringBuilder(bytes.size() * 2);
+ for (byte b : bytes) {
+ stringBuilder.append(hexDigits.charAt((b & 0xf0) >> 4));
+ stringBuilder.append(hexDigits.charAt(b & 0x0f));
+ }
+ return stringBuilder.toString();
+ }
+
+ private boolean contains(ByteString a, ByteString b) {
+ for (int i = 0; i <= a.size() - b.size(); ++i) {
+ if (a.substring(i, i + b.size()).equals(b)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
index eac47448..9e5adb70 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
@@ -46,9 +46,9 @@ import java.util.NoSuchElementException;
import junit.framework.TestCase;
/**
- * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}.
- * This class is designed to be extended for testing extensions of {@code LiteralByteString}
- * such as {@code BoundedByteString}, see {@link BoundedByteStringTest}.
+ * Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}. This class
+ * is designed to be extended for testing extensions of {@code LiteralByteString} such as {@code
+ * BoundedByteString}, see {@link BoundedByteStringTest}.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -114,7 +114,9 @@ public class LiteralByteStringTest extends TestCase {
}
public void testSize() {
- assertEquals(classUnderTest + " must have the expected size", referenceBytes.length,
+ assertEquals(
+ classUnderTest + " must have the expected size",
+ referenceBytes.length,
stringUnderTest.size());
}
@@ -146,10 +148,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy one too many bytes
- stringUnderTest.copyTo(destination, stringUnderTest.size() + 1 - length,
- destinationOffset, length);
- fail("Should have thrown an exception when copying too many bytes of a "
- + classUnderTest);
+ stringUnderTest.copyTo(
+ destination, stringUnderTest.size() + 1 - length, destinationOffset, length);
+ fail("Should have thrown an exception when copying too many bytes of a " + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -157,8 +158,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative sourceOffset
stringUnderTest.copyTo(destination, -1, destinationOffset, length);
- fail("Should have thrown an exception when given a negative sourceOffset in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when given a negative sourceOffset in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -166,8 +168,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative destinationOffset
stringUnderTest.copyTo(destination, 0, -1, length);
- fail("Should have thrown an exception when given a negative destinationOffset in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when given a negative destinationOffset in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -175,8 +178,7 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal negative size
stringUnderTest.copyTo(destination, 0, 0, -1);
- fail("Should have thrown an exception when given a negative size in "
- + classUnderTest);
+ fail("Should have thrown an exception when given a negative size in " + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -184,8 +186,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal too-large sourceOffset
stringUnderTest.copyTo(destination, 2 * stringUnderTest.size(), 0, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -193,8 +196,9 @@ public class LiteralByteStringTest extends TestCase {
try {
// Copy with illegal too-large destinationOffset
stringUnderTest.copyTo(destination, 0, 2 * destination.length, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + classUnderTest);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + classUnderTest);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -203,7 +207,8 @@ public class LiteralByteStringTest extends TestCase {
public void testCopyTo_ByteBuffer() {
ByteBuffer myBuffer = ByteBuffer.allocate(referenceBytes.length);
stringUnderTest.copyTo(myBuffer);
- assertTrue(classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".copyTo(ByteBuffer) must give back the same bytes",
Arrays.equals(referenceBytes, myBuffer.array()));
}
@@ -233,17 +238,15 @@ public class LiteralByteStringTest extends TestCase {
}
/**
- * Discards {@code n} bytes of data from the input stream. This method
- * will block until the full amount has been skipped. Does not close the
- * stream.
+ * Discards {@code n} bytes of data from the input stream. This method will block until the full
+ * amount has been skipped. Does not close the stream.
+ *
* <p>Copied from com.google.common.io.ByteStreams to avoid adding dependency.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
- * @throws EOFException if this stream reaches the end before skipping all
- * the bytes
- * @throws IOException if an I/O error occurs, or the stream does not
- * support skipping
+ * @throws EOFException if this stream reaches the end before skipping all the bytes
+ * @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
static void skipFully(InputStream in, long n) throws IOException {
long toSkip = n;
@@ -253,8 +256,12 @@ public class LiteralByteStringTest extends TestCase {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
long skipped = toSkip - n;
- throw new EOFException("reached end of stream after skipping "
- + skipped + " bytes; " + toSkip + " bytes expected");
+ throw new EOFException(
+ "reached end of stream after skipping "
+ + skipped
+ + " bytes; "
+ + toSkip
+ + " bytes expected");
}
n--;
} else {
@@ -269,7 +276,8 @@ public class LiteralByteStringTest extends TestCase {
assertTrue(byteBuffer.remaining() == referenceBytes.length);
assertTrue(byteBuffer.isReadOnly());
byteBuffer.get(roundTripBytes);
- assertTrue(classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".asReadOnlyByteBuffer() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
@@ -285,13 +293,15 @@ public class LiteralByteStringTest extends TestCase {
bytesSeen += thisLength;
}
assertTrue(bytesSeen == referenceBytes.length);
- assertTrue(classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".asReadOnlyByteBufferTest() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testToByteArray() {
byte[] roundTripBytes = stringUnderTest.toByteArray();
- assertTrue(classUnderTest + ".toByteArray() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".toByteArray() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
@@ -299,78 +309,85 @@ public class LiteralByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
stringUnderTest.writeTo(bos);
byte[] roundTripBytes = bos.toByteArray();
- assertTrue(classUnderTest + ".writeTo() must give back the same bytes",
+ assertTrue(
+ classUnderTest + ".writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, roundTripBytes));
}
public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeTo(os);
- assertTrue(classUnderTest + ".writeTo() must not grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeTo() must not grant access to underlying array",
Arrays.equals(referenceBytes, stringUnderTest.toByteArray()));
}
public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeToInternal(os, 0, stringUnderTest.size());
byte[] allZeros = new byte[stringUnderTest.size()];
- assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeToInternal() must grant access to underlying array",
Arrays.equals(allZeros, stringUnderTest.toByteArray()));
}
public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException {
- ByteOutput out = new ByteOutput() {
- @Override
- public void write(byte value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(byte[] value, int offset, int length) throws IOException {
- Arrays.fill(value, offset, offset + length, (byte) 0);
- }
-
- @Override
- public void write(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
- };
+ ByteOutput out =
+ new ByteOutput() {
+ @Override
+ public void write(byte value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(byte[] value, int offset, int length) throws IOException {
+ Arrays.fill(value, offset, offset + length, (byte) 0);
+ }
+
+ @Override
+ public void write(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ };
stringUnderTest.writeTo(out);
byte[] allZeros = new byte[stringUnderTest.size()];
- assertTrue(classUnderTest + ".writeToInternal() must grant access to underlying array",
+ assertTrue(
+ classUnderTest + ".writeToInternal() must grant access to underlying array",
Arrays.equals(allZeros, stringUnderTest.toByteArray()));
}
@@ -378,21 +395,22 @@ public class LiteralByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteString.Output output = ByteString.newOutput();
stringUnderTest.writeTo(output);
- assertEquals("Output Size returns correct result",
- output.size(), stringUnderTest.size());
+ assertEquals("Output Size returns correct result", output.size(), stringUnderTest.size());
output.writeTo(bos);
- assertTrue("Output.writeTo() must give back the same bytes",
+ assertTrue(
+ "Output.writeTo() must give back the same bytes",
Arrays.equals(referenceBytes, bos.toByteArray()));
// write the output stream to itself! This should cause it to double
output.writeTo(output);
- assertEquals("Writing an output stream to itself is successful",
- stringUnderTest.concat(stringUnderTest), output.toByteString());
+ assertEquals(
+ "Writing an output stream to itself is successful",
+ stringUnderTest.concat(stringUnderTest),
+ output.toByteString());
output.reset();
assertEquals("Output.reset() resets the output", 0, output.size());
- assertEquals("Output.reset() resets the output",
- ByteString.EMPTY, output.toByteString());
+ assertEquals("Output.reset() resets the output", ByteString.EMPTY, output.toByteString());
}
public void testToString() throws UnsupportedEncodingException {
@@ -410,9 +428,10 @@ public class LiteralByteStringTest extends TestCase {
}
public void testToString_returnsCanonicalEmptyString() {
- assertSame(classUnderTest + " must be the same string references",
+ assertSame(
+ classUnderTest + " must be the same string references",
ByteString.EMPTY.toString(Internal.UTF_8),
- ByteString.wrap(new byte[]{}).toString(Internal.UTF_8));
+ ByteString.wrap(new byte[] {}).toString(Internal.UTF_8));
}
public void testToString_raisesException() {
@@ -434,17 +453,23 @@ public class LiteralByteStringTest extends TestCase {
public void testEquals() {
assertEquals(classUnderTest + " must not equal null", false, stringUnderTest.equals(null));
assertEquals(classUnderTest + " must equal self", stringUnderTest, stringUnderTest);
- assertFalse(classUnderTest + " must not equal the empty string",
+ assertFalse(
+ classUnderTest + " must not equal the empty string",
stringUnderTest.equals(ByteString.EMPTY));
- assertEquals(classUnderTest + " empty strings must be equal",
- ByteString.wrap(new byte[]{}), stringUnderTest.substring(55, 55));
- assertEquals(classUnderTest + " must equal another string with the same value",
- stringUnderTest, ByteString.wrap(referenceBytes));
+ assertEquals(
+ classUnderTest + " empty strings must be equal",
+ ByteString.wrap(new byte[] {}),
+ stringUnderTest.substring(55, 55));
+ assertEquals(
+ classUnderTest + " must equal another string with the same value",
+ stringUnderTest,
+ ByteString.wrap(referenceBytes));
byte[] mungedBytes = new byte[referenceBytes.length];
System.arraycopy(referenceBytes, 0, mungedBytes, 0, referenceBytes.length);
mungedBytes[mungedBytes.length - 5] = (byte) (mungedBytes[mungedBytes.length - 5] ^ 0xFF);
- assertFalse(classUnderTest + " must not equal every string with the same length",
+ assertFalse(
+ classUnderTest + " must not equal every string with the same length",
stringUnderTest.equals(ByteString.wrap(mungedBytes)));
}
@@ -454,32 +479,35 @@ public class LiteralByteStringTest extends TestCase {
}
public void testPeekCachedHashCode() {
- assertEquals(classUnderTest + ".peekCachedHashCode() should return zero at first", 0,
+ assertEquals(
+ classUnderTest + ".peekCachedHashCode() should return zero at first",
+ 0,
stringUnderTest.peekCachedHashCode());
stringUnderTest.hashCode();
- assertEquals(classUnderTest + ".peekCachedHashCode should return zero at first",
- expectedHashCode, stringUnderTest.peekCachedHashCode());
+ assertEquals(
+ classUnderTest + ".peekCachedHashCode should return zero at first",
+ expectedHashCode,
+ stringUnderTest.peekCachedHashCode());
}
public void testPartialHash() {
// partialHash() is more strenuously tested elsewhere by testing hashes of substrings.
// This test would fail if the expected hash were 1. It's not.
int hash = stringUnderTest.partialHash(stringUnderTest.size(), 0, stringUnderTest.size());
- assertEquals(classUnderTest + ".partialHash() must yield expected hashCode",
- expectedHashCode, hash);
+ assertEquals(
+ classUnderTest + ".partialHash() must yield expected hashCode", expectedHashCode, hash);
}
public void testNewInput() throws IOException {
InputStream input = stringUnderTest.newInput();
- assertEquals("InputStream.available() returns correct value",
- stringUnderTest.size(), input.available());
+ assertEquals(
+ "InputStream.available() returns correct value", stringUnderTest.size(), input.available());
boolean stillEqual = true;
for (byte referenceByte : referenceBytes) {
int expectedInt = (referenceByte & 0xFF);
stillEqual = (expectedInt == input.read());
}
- assertEquals("InputStream.available() returns correct value",
- 0, input.available());
+ assertEquals("InputStream.available() returns correct value", 0, input.available());
assertTrue(classUnderTest + " must give the same bytes from the InputStream", stillEqual);
assertEquals(classUnderTest + " InputStream must now be exhausted", -1, input.read());
}
@@ -490,43 +518,44 @@ public class LiteralByteStringTest extends TestCase {
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
- assertEquals("InputStream.available()",
- stringSize - skipped1, input.available());
+ assertEquals("InputStream.available()", stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
- assertEquals("InputStream.skip(), read()",
- stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
- assertEquals("InputStream.available()",
- stringSize - skipped1 - 1, input.available());
+ assertEquals(
+ "InputStream.skip(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
- assertEquals("InputStream.skip() incomplete",
- skipped2, stringSize - skipped1 - 1);
+ assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded",
- stringSize - skipped1, input.available());
- assertEquals("InputStream.reset(), read()",
- stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals(
+ "InputStream.reset(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}
public void testNewCodedInput() throws IOException {
CodedInputStream cis = stringUnderTest.newCodedInput();
byte[] roundTripBytes = cis.readRawBytes(referenceBytes.length);
- assertTrue(classUnderTest + " must give the same bytes back from the CodedInputStream",
+ assertTrue(
+ classUnderTest + " must give the same bytes back from the CodedInputStream",
Arrays.equals(referenceBytes, roundTripBytes));
assertTrue(classUnderTest + " CodedInputStream must now be exhausted", cis.isAtEnd());
}
/**
- * Make sure we keep things simple when concatenating with empty. See also
- * {@link ByteStringTest#testConcat_empty()}.
+ * Make sure we keep things simple when concatenating with empty. See also {@link
+ * ByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
- assertSame(classUnderTest + " concatenated with empty must give " + classUnderTest,
- stringUnderTest.concat(ByteString.EMPTY), stringUnderTest);
- assertSame("empty concatenated with " + classUnderTest + " must give " + classUnderTest,
- ByteString.EMPTY.concat(stringUnderTest), stringUnderTest);
+ assertSame(
+ classUnderTest + " concatenated with empty must give " + classUnderTest,
+ stringUnderTest.concat(ByteString.EMPTY),
+ stringUnderTest);
+ assertSame(
+ "empty concatenated with " + classUnderTest + " must give " + classUnderTest,
+ ByteString.EMPTY.concat(stringUnderTest),
+ stringUnderTest);
}
public void testJavaSerialization() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
index e50c7d1e..4b5e6c78 100644
--- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
@@ -45,10 +45,8 @@ import junit.framework.TestCase;
*/
public class LongArrayListTest extends TestCase {
- private static final LongArrayList UNARY_LIST =
- newImmutableLongArrayList(1);
- private static final LongArrayList TERTIARY_LIST =
- newImmutableLongArrayList(1, 2, 3);
+ private static final LongArrayList UNARY_LIST = newImmutableLongArrayList(1);
+ private static final LongArrayList TERTIARY_LIST = newImmutableLongArrayList(1, 2, 3);
private LongArrayList list;
@@ -225,9 +223,7 @@ public class LongArrayListTest extends TestCase {
for (int i = 0; i < 6; i++) {
list.add(Long.valueOf(5 + i));
}
- assertEquals(
- asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L),
- list);
+ assertEquals(asList(0L, 1L, 4L, 2L, 3L, 5L, 6L, 7L, 8L, 9L, 10L), list);
try {
list.add(-1, 5L);
@@ -312,7 +308,7 @@ public class LongArrayListTest extends TestCase {
assertEquals(0, toRemove.size());
}
- private void assertImmutable(LongArrayList list) {
+ private void assertImmutable(LongList list) {
if (list.contains(1L)) {
throw new RuntimeException("Cannot test the immutability of lists that contain 1.");
}
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 da9195f9..41fef073 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
@@ -43,9 +43,7 @@ import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
-/**
- * Unit tests for map fields.
- */
+/** Unit tests for map fields. */
public final class MapForProto2LiteTest extends TestCase {
private void setMapValues(TestMap.Builder builder) {
@@ -53,23 +51,18 @@ public final class MapForProto2LiteTest extends TestCase {
.putInt32ToInt32Field(1, 11)
.putInt32ToInt32Field(2, 22)
.putInt32ToInt32Field(3, 33)
-
.putInt32ToStringField(1, "11")
.putInt32ToStringField(2, "22")
.putInt32ToStringField(3, "33")
-
.putInt32ToBytesField(1, TestUtil.toBytes("11"))
.putInt32ToBytesField(2, TestUtil.toBytes("22"))
.putInt32ToBytesField(3, TestUtil.toBytes("33"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.FOO)
.putInt32ToEnumField(2, TestMap.EnumValue.BAR)
.putInt32ToEnumField(3, TestMap.EnumValue.BAZ)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build())
.putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build())
.putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build())
-
.putStringToInt32Field("1", 11)
.putStringToInt32Field("2", 22)
.putStringToInt32Field("3", 33);
@@ -129,23 +122,18 @@ public final class MapForProto2LiteTest extends TestCase {
.putInt32ToInt32Field(1, 111)
.removeInt32ToInt32Field(2)
.putInt32ToInt32Field(4, 44)
-
.putInt32ToStringField(1, "111")
.removeInt32ToStringField(2)
.putInt32ToStringField(4, "44")
-
.putInt32ToBytesField(1, TestUtil.toBytes("111"))
.removeInt32ToBytesField(2)
.putInt32ToBytesField(4, TestUtil.toBytes("44"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.BAR)
.removeInt32ToEnumField(2)
.putInt32ToEnumField(4, TestMap.EnumValue.QUX)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build())
.removeInt32ToMessageField(2)
.putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build())
-
.putStringToInt32Field("1", 111)
.removeStringToInt32Field("2")
.putStringToInt32Field("4", 44);
@@ -265,8 +253,7 @@ public final class MapForProto2LiteTest extends TestCase {
}
public void testMutableMapLifecycle() {
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2);
+ TestMap.Builder builder = TestMap.newBuilder().putInt32ToInt32Field(1, 2);
assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
assertEquals(newMap(1, 2), builder.getInt32ToInt32Field());
builder.putInt32ToInt32Field(2, 3);
@@ -277,8 +264,7 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.getInt32ToEnumField());
builder.putInt32ToEnumField(2, TestMap.EnumValue.FOO);
assertEquals(
- newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO),
- builder.getInt32ToEnumField());
+ newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO), builder.getInt32ToEnumField());
builder.putInt32ToStringField(1, "1");
assertEquals(newMap(1, "1"), builder.build().getInt32ToStringField());
@@ -287,14 +273,18 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(newMap(1, "1", 2, "2"), builder.getInt32ToStringField());
builder.putInt32ToMessageField(1, TestMap.MessageValue.getDefaultInstance());
- assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
+ assertEquals(
+ newMap(1, TestMap.MessageValue.getDefaultInstance()),
builder.build().getInt32ToMessageField());
- assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()),
- builder.getInt32ToMessageField());
+ assertEquals(
+ newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField());
builder.putInt32ToMessageField(2, TestMap.MessageValue.getDefaultInstance());
assertEquals(
- newMap(1, TestMap.MessageValue.getDefaultInstance(),
- 2, TestMap.MessageValue.getDefaultInstance()),
+ newMap(
+ 1,
+ TestMap.MessageValue.getDefaultInstance(),
+ 2,
+ TestMap.MessageValue.getDefaultInstance()),
builder.getInt32ToMessageField());
}
@@ -405,30 +395,22 @@ public final class MapForProto2LiteTest extends TestCase {
ByteString bytes = TestUtil.toBytes("SOME BYTES");
String stringKey = "a string key";
- TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToInt32Field(5, bytes)
- .build());
+ TestMap map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build());
assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToStringField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build());
assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToBytesField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build());
assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY);
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToEnumField(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build());
assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
- tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToMessageField(stringKey, bytes)
- .build());
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build());
fail();
} catch (InvalidProtocolBufferException expected) {
assertTrue(expected.getUnfinishedMessage() instanceof TestMap);
@@ -436,9 +418,9 @@ public final class MapForProto2LiteTest extends TestCase {
assertTrue(map.getInt32ToMessageField().isEmpty());
}
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putStringToInt32Field(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(
+ BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build());
assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
@@ -458,16 +440,18 @@ public final class MapForProto2LiteTest extends TestCase {
// We can't control the order of elements in a HashMap. The best we can do
// here is to add elements in different order.
- TestMap.Builder b1 = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToInt32Field(5, 6);
+ TestMap.Builder b1 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToInt32Field(5, 6);
TestMap m1 = b1.build();
- TestMap.Builder b2 = TestMap.newBuilder()
- .putInt32ToInt32Field(5, 6)
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4);
+ TestMap.Builder b2 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(5, 6)
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4);
TestMap m2 = b2.build();
assertEquals(m1, m2);
@@ -482,9 +466,8 @@ public final class MapForProto2LiteTest extends TestCase {
}
public void testUnknownEnumValues() throws Exception {
- TestUnknownEnumValue.Builder builder = TestUnknownEnumValue.newBuilder()
- .putInt32ToInt32Field(1, 1)
- .putInt32ToInt32Field(2, 54321);
+ TestUnknownEnumValue.Builder builder =
+ TestUnknownEnumValue.newBuilder().putInt32ToInt32Field(1, 1).putInt32ToInt32Field(2, 54321);
ByteString data = builder.build().toByteString();
TestMap message = TestMap.parseFrom(data);
@@ -494,8 +477,7 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
// Serializing and parsing should preserve the unknown entry.
data = message.toByteString();
- TestUnknownEnumValue messageWithUnknownEnums =
- TestUnknownEnumValue.parseFrom(data);
+ TestUnknownEnumValue messageWithUnknownEnums = TestUnknownEnumValue.parseFrom(data);
assertEquals(2, messageWithUnknownEnums.getInt32ToInt32Field().size());
assertEquals(1, messageWithUnknownEnums.getInt32ToInt32Field().get(1).intValue());
assertEquals(54321, messageWithUnknownEnums.getInt32ToInt32Field().get(2).intValue());
@@ -506,18 +488,19 @@ public final class MapForProto2LiteTest extends TestCase {
setMapValues(builder);
TestMap message = builder.build();
- assertEquals(Arrays.asList("1", "2", "3"),
+ assertEquals(
+ Arrays.asList("1", "2", "3"),
new ArrayList<String>(message.getStringToInt32Field().keySet()));
}
private static <K, V> Map<K, V> newMap(K key1, V value1) {
- Map<K, V> map = new HashMap<K, V>();
+ Map<K, V> map = new HashMap<>();
map.put(key1, value1);
return map;
}
private static <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
- Map<K, V> map = new HashMap<K, V>();
+ Map<K, V> map = new HashMap<>();
map.put(key1, value1);
map.put(key2, value2);
return map;
@@ -527,18 +510,10 @@ public final class MapForProto2LiteTest extends TestCase {
TestMap.Builder builder = TestMap.newBuilder();
setMapValues(builder);
TestMap message = builder.build();
- assertEquals(
- message.getStringToInt32Field(),
- message.getStringToInt32FieldMap());
- assertEquals(
- message.getInt32ToBytesField(),
- message.getInt32ToBytesFieldMap());
- assertEquals(
- message.getInt32ToEnumField(),
- message.getInt32ToEnumFieldMap());
- assertEquals(
- message.getInt32ToMessageField(),
- message.getInt32ToMessageFieldMap());
+ assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap());
+ assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap());
+ assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap());
+ assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap());
}
public void testContains() {
@@ -629,7 +604,8 @@ public final class MapForProto2LiteTest extends TestCase {
assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToEnumFieldOrDefault(-1, null));
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null));
@@ -687,7 +663,8 @@ public final class MapForProto2LiteTest extends TestCase {
// expected
}
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrThrow(1));
try {
testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1);
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 58efce92..ef8b27e8 100644
--- a/java/core/src/test/java/com/google/protobuf/MapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -31,6 +31,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;
@@ -51,9 +52,7 @@ import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
-/**
- * Unit tests for map fields.
- */
+/** Unit tests for map fields. */
public class MapTest extends TestCase {
private void setMapValuesUsingMutableMap(TestMap.Builder builder) {
@@ -90,23 +89,18 @@ public class MapTest extends TestCase {
.putInt32ToInt32Field(1, 11)
.putInt32ToInt32Field(2, 22)
.putInt32ToInt32Field(3, 33)
-
.putInt32ToStringField(1, "11")
.putInt32ToStringField(2, "22")
.putInt32ToStringField(3, "33")
-
.putInt32ToBytesField(1, TestUtil.toBytes("11"))
.putInt32ToBytesField(2, TestUtil.toBytes("22"))
.putInt32ToBytesField(3, TestUtil.toBytes("33"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.FOO)
.putInt32ToEnumField(2, TestMap.EnumValue.BAR)
.putInt32ToEnumField(3, TestMap.EnumValue.BAZ)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build())
.putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build())
.putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build())
-
.putStringToInt32Field("1", 11)
.putStringToInt32Field("2", 22)
.putStringToInt32Field("3", 33);
@@ -201,23 +195,18 @@ public class MapTest extends TestCase {
.putInt32ToInt32Field(1, 111)
.removeInt32ToInt32Field(2)
.putInt32ToInt32Field(4, 44)
-
.putInt32ToStringField(1, "111")
.removeInt32ToStringField(2)
.putInt32ToStringField(4, "44")
-
.putInt32ToBytesField(1, TestUtil.toBytes("111"))
.removeInt32ToBytesField(2)
.putInt32ToBytesField(4, TestUtil.toBytes("44"))
-
.putInt32ToEnumField(1, TestMap.EnumValue.BAR)
.removeInt32ToEnumField(2)
.putInt32ToEnumField(4, TestMap.EnumValue.QUX)
-
.putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build())
.removeInt32ToMessageField(2)
.putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build())
-
.putStringToInt32Field("1", 111)
.removeStringToInt32Field("2")
.putStringToInt32Field("4", 44);
@@ -435,7 +424,6 @@ public class MapTest extends TestCase {
assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field());
}
-
public void testGettersAndSetters() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
TestMap message = builder.build();
@@ -470,16 +458,17 @@ public class MapTest extends TestCase {
}
public void testPutAllForUnknownEnumValues() throws Exception {
- TestMap source = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(newMap(
- 0, 0,
- 1, 1,
- 2, 1000)) // unknown value.
- .build();
+ TestMap source =
+ TestMap.newBuilder()
+ .putAllInt32ToEnumFieldValue(
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000)) // unknown value.
+ .build();
- TestMap destination = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue())
- .build();
+ TestMap destination =
+ TestMap.newBuilder().putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue()).build();
assertEquals(0, destination.getInt32ToEnumFieldValue().get(0).intValue());
assertEquals(1, destination.getInt32ToEnumFieldValue().get(1).intValue());
@@ -488,10 +477,11 @@ public class MapTest extends TestCase {
}
public void testPutForUnknownEnumValues() throws Exception {
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToEnumFieldValue(0, 0)
- .putInt32ToEnumFieldValue(1, 1)
- .putInt32ToEnumFieldValue(2, 1000); // unknown value.
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putInt32ToEnumFieldValue(0, 0)
+ .putInt32ToEnumFieldValue(1, 1)
+ .putInt32ToEnumFieldValue(2, 1000); // unknown value.
TestMap message = builder.build();
assertEquals(0, message.getInt32ToEnumFieldValueOrThrow(0));
assertEquals(1, message.getInt32ToEnumFieldValueOrThrow(1));
@@ -573,30 +563,22 @@ public class MapTest extends TestCase {
ByteString bytes = TestUtil.toBytes("SOME BYTES");
String stringKey = "a string key";
- TestMap map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToInt32Field(5, bytes)
- .build());
+ TestMap map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build());
assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToStringField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build());
assertEquals("", map.getInt32ToStringFieldOrDefault(0, null));
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToBytesField(stringKey, 5)
- .build());
+ map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build());
assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY);
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToEnumField(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build());
assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null));
try {
- tryParseTestMap(BizarroTestMap.newBuilder()
- .putInt32ToMessageField(stringKey, bytes)
- .build());
+ tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build());
fail();
} catch (InvalidProtocolBufferException expected) {
assertTrue(expected.getUnfinishedMessage() instanceof TestMap);
@@ -604,9 +586,9 @@ public class MapTest extends TestCase {
assertTrue(map.getInt32ToMessageField().isEmpty());
}
- map = tryParseTestMap(BizarroTestMap.newBuilder()
- .putStringToInt32Field(stringKey, bytes)
- .build());
+ map =
+ tryParseTestMap(
+ BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build());
assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1));
}
@@ -626,16 +608,18 @@ public class MapTest extends TestCase {
// We can't control the order of elements in a HashMap. The best we can do
// here is to add elements in different order.
- TestMap.Builder b1 = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToInt32Field(5, 6);
+ TestMap.Builder b1 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToInt32Field(5, 6);
TestMap m1 = b1.build();
- TestMap.Builder b2 = TestMap.newBuilder()
- .putInt32ToInt32Field(5, 6)
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4);
+ TestMap.Builder b2 =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(5, 6)
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4);
TestMap m2 = b2.build();
assertEquals(m1, m2);
@@ -657,8 +641,7 @@ public class MapTest extends TestCase {
}
public void testNestedBuilderOnChangeEventPropagation() {
- TestOnChangeEventPropagation.Builder parent =
- TestOnChangeEventPropagation.newBuilder();
+ TestOnChangeEventPropagation.Builder parent = TestOnChangeEventPropagation.newBuilder();
parent.getOptionalMessageBuilder().putInt32ToInt32Field(1, 2);
TestOnChangeEventPropagation message = parent.build();
assertEquals(2, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
@@ -689,16 +672,14 @@ public class MapTest extends TestCase {
public void testNestedBuilderOnChangeEventPropagationReflection() {
FieldDescriptor intMapField = f("int32_to_int32_field");
// Create an outer message builder with nested builder.
- TestOnChangeEventPropagation.Builder parentBuilder =
- TestOnChangeEventPropagation.newBuilder();
+ TestOnChangeEventPropagation.Builder parentBuilder = TestOnChangeEventPropagation.newBuilder();
TestMap.Builder testMapBuilder = parentBuilder.getOptionalMessageBuilder();
// Create a map entry message.
TestMap.Builder entryBuilder = TestMap.newBuilder().putInt32ToInt32Field(1, 1);
// Put the entry into the nested builder.
- testMapBuilder.addRepeatedField(
- intMapField, entryBuilder.getRepeatedField(intMapField, 0));
+ testMapBuilder.addRepeatedField(intMapField, entryBuilder.getRepeatedField(intMapField, 0));
// Should be able to observe the change.
TestOnChangeEventPropagation message = parentBuilder.build();
@@ -707,13 +688,11 @@ public class MapTest extends TestCase {
// Change the entry value.
entryBuilder.putInt32ToInt32Field(1, 4);
testMapBuilder = parentBuilder.getOptionalMessageBuilder();
- testMapBuilder.setRepeatedField(
- intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0));
+ testMapBuilder.setRepeatedField(intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0));
// Should be able to observe the change.
message = parentBuilder.build();
- assertEquals(4,
- message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
+ assertEquals(4, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue());
// Clear the nested builder.
testMapBuilder = parentBuilder.getOptionalMessageBuilder();
@@ -761,8 +740,7 @@ public class MapTest extends TestCase {
}
}
- private static <KeyType, ValueType>
- Message newMapEntry(Message.Builder builder, String name, KeyType key, ValueType value) {
+ private static <K, V> Message newMapEntry(Message.Builder builder, String name, K key, V value) {
FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name);
Message.Builder entryBuilder = builder.newBuilderForField(field);
FieldDescriptor keyField = entryBuilder.getDescriptorForType().findFieldByName("key");
@@ -781,10 +759,8 @@ public class MapTest extends TestCase {
builder.setField(field, entryList);
}
- private static <KeyType, ValueType>
- Map<KeyType, ValueType> mapForValues(
- KeyType key1, ValueType value1, KeyType key2, ValueType value2) {
- Map<KeyType, ValueType> map = new HashMap<KeyType, ValueType>();
+ private static <K, V> Map<K, V> mapForValues(K key1, V value1, K key2, V value2) {
+ Map<K, V> map = new HashMap<K, V>();
map.put(key1, value1);
map.put(key2, value2);
return map;
@@ -792,17 +768,19 @@ public class MapTest extends TestCase {
public void testReflectionApi() throws Exception {
// In reflection API, map fields are just repeated message fields.
- TestMap.Builder builder = TestMap.newBuilder()
- .putInt32ToInt32Field(1, 2)
- .putInt32ToInt32Field(3, 4)
- .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build())
- .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build());
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putInt32ToInt32Field(1, 2)
+ .putInt32ToInt32Field(3, 4)
+ .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build())
+ .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build());
TestMap message = builder.build();
// Test getField(), getRepeatedFieldCount(), getRepeatedField().
- assertHasMapValues(message, "int32_to_int32_field",
- mapForValues(1, 2, 3, 4));
- assertHasMapValues(message, "int32_to_message_field",
+ assertHasMapValues(message, "int32_to_int32_field", mapForValues(1, 2, 3, 4));
+ assertHasMapValues(
+ message,
+ "int32_to_message_field",
mapForValues(
11, MessageValue.newBuilder().setValue(22).build(),
33, MessageValue.newBuilder().setValue(44).build()));
@@ -815,9 +793,10 @@ public class MapTest extends TestCase {
assertEquals(0, message.getInt32ToMessageField().size());
// Test setField()
- setMapValues(builder, "int32_to_int32_field",
- mapForValues(11, 22, 33, 44));
- setMapValues(builder, "int32_to_message_field",
+ setMapValues(builder, "int32_to_int32_field", mapForValues(11, 22, 33, 44));
+ setMapValues(
+ builder,
+ "int32_to_message_field",
mapForValues(
111, MessageValue.newBuilder().setValue(222).build(),
333, MessageValue.newBuilder().setValue(444).build()));
@@ -828,20 +807,28 @@ public class MapTest extends TestCase {
assertEquals(444, message.getInt32ToMessageField().get(333).getValue());
// Test addRepeatedField
- builder.addRepeatedField(f("int32_to_int32_field"),
- newMapEntry(builder, "int32_to_int32_field", 55, 66));
- builder.addRepeatedField(f("int32_to_message_field"),
- newMapEntry(builder, "int32_to_message_field", 555,
+ builder.addRepeatedField(
+ f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 66));
+ builder.addRepeatedField(
+ f("int32_to_message_field"),
+ newMapEntry(
+ builder,
+ "int32_to_message_field",
+ 555,
MessageValue.newBuilder().setValue(666).build()));
message = builder.build();
assertEquals(66, message.getInt32ToInt32Field().get(55).intValue());
assertEquals(666, message.getInt32ToMessageField().get(555).getValue());
// Test addRepeatedField (overriding existing values)
- builder.addRepeatedField(f("int32_to_int32_field"),
- newMapEntry(builder, "int32_to_int32_field", 55, 55));
- builder.addRepeatedField(f("int32_to_message_field"),
- newMapEntry(builder, "int32_to_message_field", 555,
+ builder.addRepeatedField(
+ f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 55));
+ builder.addRepeatedField(
+ f("int32_to_message_field"),
+ newMapEntry(
+ builder,
+ "int32_to_message_field",
+ 555,
MessageValue.newBuilder().setValue(555).build()));
message = builder.build();
assertEquals(55, message.getInt32ToInt32Field().get(55).intValue());
@@ -884,10 +871,9 @@ public class MapTest extends TestCase {
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
- Message dynamicMessage = dynamicDefaultInstance
- .newBuilderForType().mergeFrom(message.toByteString()).build();
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicMessage =
+ dynamicDefaultInstance.newBuilderForType().mergeFrom(message.toByteString()).build();
assertEquals(message, dynamicMessage);
assertEquals(message.hashCode(), dynamicMessage.hashCode());
@@ -898,8 +884,7 @@ public class MapTest extends TestCase {
public void testDynamicMessageUnsetKeyAndValue() throws Exception {
FieldDescriptor field = f("int32_to_int32_field");
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
Message.Builder builder = dynamicDefaultInstance.newBuilderForType();
// Add an entry without key and value.
builder.addRepeatedField(field, builder.newBuilderForField(field).build());
@@ -916,8 +901,7 @@ public class MapTest extends TestCase {
// of map entries when comparing/hashing map fields.
// We use DynamicMessage to test reflection based equals()/hashCode().
- Message dynamicDefaultInstance =
- DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
+ Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor());
FieldDescriptor field = f("int32_to_int32_field");
Message.Builder b1 = dynamicDefaultInstance.newBuilderForType();
@@ -944,19 +928,18 @@ public class MapTest extends TestCase {
}
public void testUnknownEnumValues() throws Exception {
- TestMap.Builder builder = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(newMap(
- 0, 0,
- 1, 1,
- 2, 1000)); // unknown value.
+ TestMap.Builder builder =
+ TestMap.newBuilder()
+ .putAllInt32ToEnumFieldValue(
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000)); // unknown value.
TestMap message = builder.build();
- assertEquals(TestMap.EnumValue.FOO,
- message.getInt32ToEnumField().get(0));
- assertEquals(TestMap.EnumValue.BAR,
- message.getInt32ToEnumField().get(1));
- assertEquals(TestMap.EnumValue.UNRECOGNIZED,
- message.getInt32ToEnumField().get(2));
+ assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(0));
+ assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1));
+ assertEquals(TestMap.EnumValue.UNRECOGNIZED, message.getInt32ToEnumField().get(2));
assertEquals(1000, message.getInt32ToEnumFieldValue().get(2).intValue());
// Unknown enum values should be preserved after:
@@ -977,7 +960,7 @@ public class MapTest extends TestCase {
assertFalse(message.equals(message2));
// Unknown values will be converted to UNRECOGNIZED so the resulted enum map
// should be the same.
- assertTrue(message.getInt32ToEnumField().equals(message2.getInt32ToEnumField()));
+ assertEquals(message2.getInt32ToEnumField(), message.getInt32ToEnumField());
}
public void testUnknownEnumValuesInReflectionApi() throws Exception {
@@ -985,13 +968,13 @@ public class MapTest extends TestCase {
EnumDescriptor enumDescriptor = TestMap.EnumValue.getDescriptor();
FieldDescriptor field = descriptor.findFieldByName("int32_to_enum_field");
- Map<Integer, Integer> data = newMap(
- 0, 0,
- 1, 1,
- 2, 1000); // unknown value
+ Map<Integer, Integer> data =
+ newMap(
+ 0, 0,
+ 1, 1,
+ 2, 1000); // unknown value
- TestMap.Builder builder = TestMap.newBuilder()
- .putAllInt32ToEnumFieldValue(data);
+ TestMap.Builder builder = TestMap.newBuilder().putAllInt32ToEnumFieldValue(data);
// Try to read unknown enum values using reflection API.
for (int i = 0; i < builder.getRepeatedFieldCount(field); i++) {
@@ -1001,8 +984,8 @@ public class MapTest extends TestCase {
assertEquals(data.get(key).intValue(), value);
Message.Builder mapEntryBuilder = mapEntry.toBuilder();
// Increase the value by 1.
- setFieldValue(mapEntryBuilder, "value",
- enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1));
+ setFieldValue(
+ mapEntryBuilder, "value", enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1));
builder.setRepeatedField(field, i, mapEntryBuilder.build());
}
@@ -1018,7 +1001,8 @@ public class MapTest extends TestCase {
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- assertEquals(Arrays.asList("1", "2", "3"),
+ assertEquals(
+ Arrays.asList("1", "2", "3"),
new ArrayList<String>(message.getStringToInt32Field().keySet()));
}
@@ -1026,21 +1010,11 @@ public class MapTest extends TestCase {
TestMap.Builder builder = TestMap.newBuilder();
setMapValuesUsingAccessors(builder);
TestMap message = builder.build();
- assertEquals(
- message.getStringToInt32Field(),
- message.getStringToInt32FieldMap());
- assertEquals(
- message.getInt32ToBytesField(),
- message.getInt32ToBytesFieldMap());
- assertEquals(
- message.getInt32ToEnumField(),
- message.getInt32ToEnumFieldMap());
- assertEquals(
- message.getInt32ToEnumFieldValue(),
- message.getInt32ToEnumFieldValueMap());
- assertEquals(
- message.getInt32ToMessageField(),
- message.getInt32ToMessageFieldMap());
+ assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap());
+ assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap());
+ assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap());
+ assertEquals(message.getInt32ToEnumFieldValue(), message.getInt32ToEnumFieldValueMap());
+ assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap());
}
public void testContains() {
@@ -1133,10 +1107,11 @@ public class MapTest extends TestCase {
assertEquals(
TestMap.EnumValue.BAR.getNumber(),
- (int) testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1));
+ testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1));
assertEquals(-1, testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(-1000, -1));
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null));
assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null));
@@ -1203,7 +1178,8 @@ public class MapTest extends TestCase {
// expected
}
- assertEquals(MessageValue.newBuilder().setValue(11).build(),
+ assertEquals(
+ MessageValue.newBuilder().setValue(11).build(),
testMapOrBuilder.getInt32ToMessageFieldOrThrow(1));
try {
testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1);
@@ -1261,8 +1237,7 @@ public class MapTest extends TestCase {
}
builder.putInt32ToEnumFieldValue(1, TestMap.EnumValue.BAR.getNumber());
- assertEquals(
- TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1));
+ assertEquals(TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1));
builder.putInt32ToEnumFieldValue(1, -1);
assertEquals(-1, builder.getInt32ToEnumFieldValueOrThrow(1));
assertEquals(TestMap.EnumValue.UNRECOGNIZED, builder.getInt32ToEnumFieldOrThrow(1));
@@ -1391,18 +1366,10 @@ public class MapTest extends TestCase {
}
input.popLimit(oldLimit);
}
- assertEquals(
- Arrays.asList(-2, 0, 1, 4, 5),
- int32Keys);
- assertEquals(
- Arrays.asList(-2, 0, 1, 4, 5),
- uint32Keys);
- assertEquals(
- Arrays.asList(-2L, 0L, 1L, 4L, 5L),
- int64Keys);
- assertEquals(
- Arrays.asList("", "bar", "baz", "foo", "hello", "world"),
- stringKeys);
+ assertEquals(Arrays.asList(-2, 0, 1, 4, 5), int32Keys);
+ assertEquals(Arrays.asList(-2, 0, 1, 4, 5), uint32Keys);
+ assertEquals(Arrays.asList(-2L, 0L, 1L, 4L, 5L), int64Keys);
+ assertEquals(Arrays.asList("", "bar", "baz", "foo", "hello", "world"), stringKeys);
}
public void testInitFromPartialDynamicMessage() {
@@ -1525,8 +1492,7 @@ public class MapTest extends TestCase {
}
try {
- builder.putAllInt32ToMessageField(
- MapTest.<Integer, MessageValue>newMap(4, null, 5, null));
+ builder.putAllInt32ToMessageField(MapTest.<Integer, MessageValue>newMap(4, null, 5, null));
fail();
} catch (NullPointerException expected) {
}
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 4fc8f78e..760511b6 100644
--- a/java/core/src/test/java/com/google/protobuf/MessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java
@@ -39,8 +39,7 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Misc. unit tests for message operations that apply to both generated
- * and dynamic messages.
+ * Misc. unit tests for message operations that apply to both generated and dynamic messages.
*
* @author kenton@google.com Kenton Varda
*/
@@ -49,30 +48,31 @@ public class MessageTest extends TestCase {
// Message-merging tests.
static final TestAllTypes MERGE_SOURCE =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .build();
static final TestAllTypes MERGE_DEST =
- TestAllTypes.newBuilder()
- .setOptionalInt64(2)
- .setOptionalString("baz")
- .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
- .addRepeatedString("qux")
- .build();
+ TestAllTypes.newBuilder()
+ .setOptionalInt64(2)
+ .setOptionalString("baz")
+ .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
+ .addRepeatedString("qux")
+ .build();
static final String MERGE_RESULT_TEXT =
- "optional_int32: 1\n" +
- "optional_int64: 2\n" +
- "optional_string: \"foo\"\n" +
- "optional_foreign_message {\n" +
- " c: 3\n" +
- "}\n" +
- "repeated_string: \"qux\"\n" +
- "repeated_string: \"bar\"\n";
+ ""
+ + "optional_int32: 1\n"
+ + "optional_int64: 2\n"
+ + "optional_string: \"foo\"\n"
+ + "optional_foreign_message {\n"
+ + " c: 3\n"
+ + "}\n"
+ + "repeated_string: \"qux\"\n"
+ + "repeated_string: \"bar\"\n";
public void testParsingWithNullExtensionRegistry() throws Exception {
try {
@@ -83,23 +83,20 @@ public class MessageTest extends TestCase {
}
public void testMergeFrom() throws Exception {
- TestAllTypes result =
- TestAllTypes.newBuilder(MERGE_DEST)
- .mergeFrom(MERGE_SOURCE).build();
+ TestAllTypes result = TestAllTypes.newBuilder(MERGE_DEST).mergeFrom(MERGE_SOURCE).build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
/**
- * Test merging a DynamicMessage into a GeneratedMessage. As long as they
- * have the same descriptor, this should work, but it is an entirely different
- * code path.
+ * Test merging a DynamicMessage into a GeneratedMessage. As long as they have the same
+ * descriptor, this should work, but it is an entirely different code path.
*/
public void testMergeFromDynamic() throws Exception {
TestAllTypes result =
- TestAllTypes.newBuilder(MERGE_DEST)
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ TestAllTypes.newBuilder(MERGE_DEST)
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -107,9 +104,9 @@ public class MessageTest extends TestCase {
/** Test merging two DynamicMessages. */
public void testDynamicMergeFrom() throws Exception {
DynamicMessage result =
- DynamicMessage.newBuilder(MERGE_DEST)
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ DynamicMessage.newBuilder(MERGE_DEST)
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
assertEquals(MERGE_RESULT_TEXT, result.toString());
}
@@ -117,10 +114,9 @@ public class MessageTest extends TestCase {
// =================================================================
// Required-field-related tests.
- private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
- TestRequired.getDefaultInstance();
+ private static final TestRequired TEST_REQUIRED_UNINITIALIZED = TestRequired.getDefaultInstance();
private static final TestRequired TEST_REQUIRED_INITIALIZED =
- TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
+ TestRequired.newBuilder().setA(1).setB(2).setC(3).build();
public void testRequired() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
@@ -189,20 +185,18 @@ public class MessageTest extends TestCase {
assertTrue(builder.isInitialized());
- builder.setField(descriptor.findFieldByName("optional_message"),
- TEST_REQUIRED_UNINITIALIZED);
+ builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
- builder.setField(descriptor.findFieldByName("optional_message"),
- TEST_REQUIRED_INITIALIZED);
+ builder.setField(descriptor.findFieldByName("optional_message"), TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
- builder.addRepeatedField(descriptor.findFieldByName("repeated_message"),
- TEST_REQUIRED_UNINITIALIZED);
+ builder.addRepeatedField(
+ descriptor.findFieldByName("repeated_message"), TEST_REQUIRED_UNINITIALIZED);
assertFalse(builder.isInitialized());
- builder.setRepeatedField(descriptor.findFieldByName("repeated_message"), 0,
- TEST_REQUIRED_INITIALIZED);
+ builder.setRepeatedField(
+ descriptor.findFieldByName("repeated_message"), 0, TEST_REQUIRED_INITIALIZED);
assertTrue(builder.isInitialized());
}
@@ -224,35 +218,35 @@ public class MessageTest extends TestCase {
public void testNestedUninitializedException() throws Exception {
try {
TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .build();
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .build();
fail("Should have thrown an exception.");
} catch (UninitializedMessageException e) {
assertEquals(
- "Message missing required fields: " +
- "optional_message.a, " +
- "optional_message.b, " +
- "optional_message.c, " +
- "repeated_message[0].a, " +
- "repeated_message[0].b, " +
- "repeated_message[0].c, " +
- "repeated_message[1].a, " +
- "repeated_message[1].b, " +
- "repeated_message[1].c",
- e.getMessage());
+ "Message missing required fields: "
+ + "optional_message.a, "
+ + "optional_message.b, "
+ + "optional_message.c, "
+ + "repeated_message[0].a, "
+ + "repeated_message[0].b, "
+ + "repeated_message[0].c, "
+ + "repeated_message[1].a, "
+ + "repeated_message[1].b, "
+ + "repeated_message[1].c",
+ e.getMessage());
}
}
public void testBuildNestedPartial() throws Exception {
// We're mostly testing that no exception is thrown.
TestRequiredForeign message =
- TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .buildPartial();
+ TestRequiredForeign.newBuilder()
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .buildPartial();
assertFalse(message.isInitialized());
}
@@ -267,28 +261,29 @@ public class MessageTest extends TestCase {
public void testParseNestedUnititialized() throws Exception {
ByteString data =
- TestRequiredForeign.newBuilder()
- .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
- .buildPartial().toByteString();
+ TestRequiredForeign.newBuilder()
+ .setOptionalMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED)
+ .buildPartial()
+ .toByteString();
try {
TestRequiredForeign.parseFrom(data);
fail("Should have thrown an exception.");
} catch (InvalidProtocolBufferException e) {
assertEquals(
- "Message missing required fields: " +
- "optional_message.a, " +
- "optional_message.b, " +
- "optional_message.c, " +
- "repeated_message[0].a, " +
- "repeated_message[0].b, " +
- "repeated_message[0].c, " +
- "repeated_message[1].a, " +
- "repeated_message[1].b, " +
- "repeated_message[1].c",
- e.getMessage());
+ "Message missing required fields: "
+ + "optional_message.a, "
+ + "optional_message.b, "
+ + "optional_message.c, "
+ + "repeated_message[0].a, "
+ + "repeated_message[0].b, "
+ + "repeated_message[0].c, "
+ + "repeated_message[1].a, "
+ + "repeated_message[1].b, "
+ + "repeated_message[1].c",
+ e.getMessage());
}
}
@@ -303,9 +298,7 @@ public class MessageTest extends TestCase {
public void testDynamicBuildPartial() throws Exception {
// We're mostly testing that no exception is thrown.
- DynamicMessage message =
- DynamicMessage.newBuilder(TestRequired.getDescriptor())
- .buildPartial();
+ DynamicMessage message = DynamicMessage.newBuilder(TestRequired.getDescriptor()).buildPartial();
assertFalse(message.isInitialized());
}
@@ -318,43 +311,44 @@ public class MessageTest extends TestCase {
assertEquals("Message missing required fields: a, b, c", e.getMessage());
}
}
-
+
/** Test reading unset repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNull() throws Exception {
- Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
+ TestRequired.getDescriptor();
DynamicMessage result =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
- .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
- .build();
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
+ .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
+ .build();
- assertTrue(result.getField(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")) instanceof List<?>);
+ assertTrue(
+ result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message"))
+ instanceof List<?>);
assertEquals(
0,
result.getRepeatedFieldCount(
result.getDescriptorForType().findFieldByName("repeated_foreign_message")));
}
-
+
/** Test reading repeated message from DynamicMessage. */
public void testDynamicRepeatedMessageNotNull() throws Exception {
-
- TestAllTypes REPEATED_NESTED =
- TestAllTypes.newBuilder()
- .setOptionalInt32(1)
- .setOptionalString("foo")
- .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedString("bar")
- .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
- .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
- .build();
- Descriptors.Descriptor descriptor = TestRequired.getDescriptor();
+ TestAllTypes repeatedNested =
+ TestAllTypes.newBuilder()
+ .setOptionalInt32(1)
+ .setOptionalString("foo")
+ .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedString("bar")
+ .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
+ .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance())
+ .build();
+ TestRequired.getDescriptor();
DynamicMessage result =
- DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
- .mergeFrom(DynamicMessage.newBuilder(REPEATED_NESTED).build())
- .build();
+ DynamicMessage.newBuilder(TestAllTypes.getDescriptor())
+ .mergeFrom(DynamicMessage.newBuilder(repeatedNested).build())
+ .build();
- assertTrue(result.getField(result.getDescriptorForType()
- .findFieldByName("repeated_foreign_message")) instanceof List<?>);
+ assertTrue(
+ result.getField(result.getDescriptorForType().findFieldByName("repeated_foreign_message"))
+ instanceof List<?>);
assertEquals(
2,
result.getRepeatedFieldCount(
diff --git a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
index 03ed65a5..7bfeaf17 100644
--- a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
@@ -37,8 +37,8 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Test cases that exercise end-to-end use cases involving
- * {@link SingleFieldBuilder} and {@link RepeatedFieldBuilder}.
+ * Test cases that exercise end-to-end use cases involving {@link SingleFieldBuilder} and {@link
+ * RepeatedFieldBuilder}.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -46,20 +46,11 @@ public class NestedBuildersTest extends TestCase {
public void testMessagesAndBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(1);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(2);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(3);
- vehicleBuilder.addWheelBuilder()
- .setRadius(4)
- .setWidth(4);
- vehicleBuilder.getEngineBuilder()
- .setLiters(10);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(1);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(3);
+ vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(4);
+ vehicleBuilder.getEngineBuilder().setLiters(10);
Vehicle vehicle = vehicleBuilder.build();
assertEquals(4, vehicle.getWheelCount());
@@ -71,9 +62,7 @@ public class NestedBuildersTest extends TestCase {
assertEquals(10, vehicle.getEngine().getLiters());
for (int i = 0; i < 4; i++) {
- vehicleBuilder.getWheelBuilder(i)
- .setRadius(5)
- .setWidth(i + 10);
+ vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);
}
vehicleBuilder.getEngineBuilder().setLiters(20);
@@ -89,18 +78,10 @@ public class NestedBuildersTest extends TestCase {
public void testMessagesAreCached() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(1)
- .setWidth(2);
- vehicleBuilder.addWheelBuilder()
- .setRadius(3)
- .setWidth(4);
- vehicleBuilder.addWheelBuilder()
- .setRadius(5)
- .setWidth(6);
- vehicleBuilder.addWheelBuilder()
- .setRadius(7)
- .setWidth(8);
+ vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(3).setWidth(4);
+ vehicleBuilder.addWheelBuilder().setRadius(5).setWidth(6);
+ vehicleBuilder.addWheelBuilder().setRadius(7).setWidth(8);
// Make sure messages are cached.
List<Wheel> wheels = new ArrayList<Wheel>(vehicleBuilder.getWheelList());
@@ -117,8 +98,7 @@ public class NestedBuildersTest extends TestCase {
}
// Change just one
- vehicleBuilder.getWheelBuilder(3)
- .setRadius(20).setWidth(20);
+ vehicleBuilder.getWheelBuilder(3).setRadius(20).setWidth(20);
// Now get wheels and check that only that one changed
for (int i = 0; i < wheels.size(); i++) {
@@ -132,12 +112,8 @@ public class NestedBuildersTest extends TestCase {
public void testRemove_WithNestedBuilders() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheelBuilder()
- .setRadius(1)
- .setWidth(1);
- vehicleBuilder.addWheelBuilder()
- .setRadius(2)
- .setWidth(2);
+ vehicleBuilder.addWheelBuilder().setRadius(1).setWidth(1);
+ vehicleBuilder.addWheelBuilder().setRadius(2).setWidth(2);
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
@@ -146,12 +122,8 @@ public class NestedBuildersTest extends TestCase {
public void testRemove_WithNestedMessages() {
Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
- vehicleBuilder.addWheel(Wheel.newBuilder()
- .setRadius(1)
- .setWidth(1));
- vehicleBuilder.addWheel(Wheel.newBuilder()
- .setRadius(2)
- .setWidth(2));
+ vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(1).setWidth(1));
+ vehicleBuilder.addWheel(Wheel.newBuilder().setRadius(2).setWidth(2));
vehicleBuilder.removeWheel(0);
assertEquals(1, vehicleBuilder.getWheelCount());
@@ -159,14 +131,13 @@ public class NestedBuildersTest extends TestCase {
}
public void testMerge() {
- Vehicle vehicle1 = Vehicle.newBuilder()
- .addWheel(Wheel.newBuilder().setRadius(1).build())
- .addWheel(Wheel.newBuilder().setRadius(2).build())
- .build();
-
- Vehicle vehicle2 = Vehicle.newBuilder()
- .mergeFrom(vehicle1)
- .build();
+ Vehicle vehicle1 =
+ Vehicle.newBuilder()
+ .addWheel(Wheel.newBuilder().setRadius(1).build())
+ .addWheel(Wheel.newBuilder().setRadius(2).build())
+ .build();
+
+ Vehicle vehicle2 = Vehicle.newBuilder().mergeFrom(vehicle1).build();
// List should be the same -- no allocation
assertSame(vehicle1.getWheelList(), vehicle2.getWheelList());
diff --git a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
index c388bd05..4a68c8b8 100644
--- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
@@ -48,9 +48,7 @@ import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
-/**
- * Tests for {@link NioByteString}.
- */
+/** Tests for {@link NioByteString}. */
public class NioByteStringTest extends TestCase {
private static final ByteString EMPTY = new NioByteString(ByteBuffer.wrap(new byte[0]));
private static final String CLASSNAME = NioByteString.class.getSimpleName();
@@ -108,8 +106,7 @@ public class NioByteStringTest extends TestCase {
}
public void testSize() {
- assertEquals(CLASSNAME + " must have the expected size", BYTES.length,
- testString.size());
+ assertEquals(CLASSNAME + " must have the expected size", BYTES.length, testString.size());
}
public void testGetTreeDepth() {
@@ -140,10 +137,8 @@ public class NioByteStringTest extends TestCase {
try {
// Copy one too many bytes
- testString.copyTo(destination, testString.size() + 1 - length,
- destinationOffset, length);
- fail("Should have thrown an exception when copying too many bytes of a "
- + CLASSNAME);
+ testString.copyTo(destination, testString.size() + 1 - length, destinationOffset, length);
+ fail("Should have thrown an exception when copying too many bytes of a " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -151,8 +146,7 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative sourceOffset
testString.copyTo(destination, -1, destinationOffset, length);
- fail("Should have thrown an exception when given a negative sourceOffset in "
- + CLASSNAME);
+ fail("Should have thrown an exception when given a negative sourceOffset in " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -160,8 +154,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative destinationOffset
testString.copyTo(destination, 0, -1, length);
- fail("Should have thrown an exception when given a negative destinationOffset in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when given a negative destinationOffset in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -169,8 +164,7 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal negative size
testString.copyTo(destination, 0, 0, -1);
- fail("Should have thrown an exception when given a negative size in "
- + CLASSNAME);
+ fail("Should have thrown an exception when given a negative size in " + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -178,8 +172,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal too-large sourceOffset
testString.copyTo(destination, 2 * testString.size(), 0, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -187,8 +182,9 @@ public class NioByteStringTest extends TestCase {
try {
// Copy with illegal too-large destinationOffset
testString.copyTo(destination, 0, 2 * destination.length, length);
- fail("Should have thrown an exception when the destinationOffset is too large in "
- + CLASSNAME);
+ fail(
+ "Should have thrown an exception when the destinationOffset is too large in "
+ + CLASSNAME);
} catch (IndexOutOfBoundsException expected) {
// This is success
}
@@ -199,8 +195,8 @@ public class NioByteStringTest extends TestCase {
ByteBuffer myBuffer = ByteBuffer.allocate(BYTES.length);
testString.copyTo(myBuffer);
myBuffer.flip();
- assertEquals(CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes",
- backingBuffer, myBuffer);
+ assertEquals(
+ CLASSNAME + ".copyTo(ByteBuffer) must give back the same bytes", backingBuffer, myBuffer);
// Target buffer bigger than required.
myBuffer = ByteBuffer.allocate(testString.size() + 1);
@@ -241,30 +237,31 @@ public class NioByteStringTest extends TestCase {
skipFully(stream, fraction); // Skip a large fraction, but not all.
assertEquals(
CLASSNAME + ": after skipping to the 'middle', half the bytes are available",
- (testString.size() - fraction), stream.available());
+ (testString.size() - fraction),
+ stream.available());
stream.reset();
assertEquals(
CLASSNAME + ": after resetting, all bytes are available",
- testString.size(), stream.available());
+ testString.size(),
+ stream.available());
skipFully(stream, testString.size()); // Skip to the end.
assertEquals(
CLASSNAME + ": after skipping to the end, no more bytes are available",
- 0, stream.available());
+ 0,
+ stream.available());
}
/**
- * Discards {@code n} bytes of data from the input stream. This method
- * will block until the full amount has been skipped. Does not close the
- * stream.
+ * Discards {@code n} bytes of data from the input stream. This method will block until the full
+ * amount has been skipped. Does not close the stream.
+ *
* <p>Copied from com.google.common.io.ByteStreams to avoid adding dependency.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
- * @throws EOFException if this stream reaches the end before skipping all
- * the bytes
- * @throws IOException if an I/O error occurs, or the stream does not
- * support skipping
+ * @throws EOFException if this stream reaches the end before skipping all the bytes
+ * @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
static void skipFully(InputStream in, long n) throws IOException {
long toSkip = n;
@@ -274,8 +271,12 @@ public class NioByteStringTest extends TestCase {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
long skipped = toSkip - n;
- throw new EOFException("reached end of stream after skipping "
- + skipped + " bytes; " + toSkip + " bytes expected");
+ throw new EOFException(
+ "reached end of stream after skipping "
+ + skipped
+ + " bytes; "
+ + toSkip
+ + " bytes expected");
}
n--;
} else {
@@ -290,7 +291,8 @@ public class NioByteStringTest extends TestCase {
assertTrue(byteBuffer.remaining() == BYTES.length);
assertTrue(byteBuffer.isReadOnly());
byteBuffer.get(roundTripBytes);
- assertTrue(CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".asReadOnlyByteBuffer() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
@@ -306,13 +308,15 @@ public class NioByteStringTest extends TestCase {
bytesSeen += thisLength;
}
assertTrue(bytesSeen == BYTES.length);
- assertTrue(CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".asReadOnlyByteBufferTest() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
public void testToByteArray() {
byte[] roundTripBytes = testString.toByteArray();
- assertTrue(CLASSNAME + ".toByteArray() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".toByteArray() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
@@ -320,80 +324,87 @@ public class NioByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
testString.writeTo(bos);
byte[] roundTripBytes = bos.toByteArray();
- assertTrue(CLASSNAME + ".writeTo() must give back the same bytes",
+ assertTrue(
+ CLASSNAME + ".writeTo() must give back the same bytes",
Arrays.equals(BYTES, roundTripBytes));
}
public void testWriteToShouldNotExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
byte[] original = Arrays.copyOf(BYTES, BYTES.length);
testString.writeTo(os);
- assertTrue(CLASSNAME + ".writeTo() must NOT grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeTo() must NOT grant access to underlying buffer",
Arrays.equals(original, BYTES));
}
public void testWriteToInternalShouldExposeInternalBufferToOutputStream() throws IOException {
- OutputStream os = new OutputStream() {
- @Override
- public void write(byte[] b, int off, int len) {
- Arrays.fill(b, off, off + len, (byte) 0);
- }
-
- @Override
- public void write(int b) {
- throw new UnsupportedOperationException();
- }
- };
+ OutputStream os =
+ new OutputStream() {
+ @Override
+ public void write(byte[] b, int off, int len) {
+ Arrays.fill(b, off, off + len, (byte) 0);
+ }
+
+ @Override
+ public void write(int b) {
+ throw new UnsupportedOperationException();
+ }
+ };
testString.writeToInternal(os, 0, testString.size());
byte[] allZeros = new byte[testString.size()];
- assertTrue(CLASSNAME + ".writeToInternal() must grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeToInternal() must grant access to underlying buffer",
Arrays.equals(allZeros, backingBuffer.array()));
}
public void testWriteToShouldExposeInternalBufferToByteOutput() throws IOException {
- ByteOutput out = new ByteOutput() {
- @Override
- public void write(byte value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(byte[] value, int offset, int length) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void write(ByteBuffer value) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void writeLazy(ByteBuffer value) throws IOException {
- Arrays.fill(value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(),
- (byte) 0);
- }
- };
+ ByteOutput out =
+ new ByteOutput() {
+ @Override
+ public void write(byte value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(byte[] value, int offset, int length) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(ByteBuffer value) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLazy(ByteBuffer value) throws IOException {
+ Arrays.fill(
+ value.array(), value.arrayOffset(), value.arrayOffset() + value.limit(), (byte) 0);
+ }
+ };
testString.writeTo(out);
byte[] allZeros = new byte[testString.size()];
- assertTrue(CLASSNAME + ".writeTo() must grant access to underlying buffer",
+ assertTrue(
+ CLASSNAME + ".writeTo() must grant access to underlying buffer",
Arrays.equals(allZeros, backingBuffer.array()));
}
@@ -401,21 +412,21 @@ public class NioByteStringTest extends TestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteString.Output output = ByteString.newOutput();
testString.writeTo(output);
- assertEquals("Output Size returns correct result",
- output.size(), testString.size());
+ assertEquals("Output Size returns correct result", output.size(), testString.size());
output.writeTo(bos);
- assertTrue("Output.writeTo() must give back the same bytes",
- Arrays.equals(BYTES, bos.toByteArray()));
+ assertTrue(
+ "Output.writeTo() must give back the same bytes", Arrays.equals(BYTES, bos.toByteArray()));
// write the output stream to itself! This should cause it to double
output.writeTo(output);
- assertEquals("Writing an output stream to itself is successful",
- testString.concat(testString), output.toByteString());
+ assertEquals(
+ "Writing an output stream to itself is successful",
+ testString.concat(testString),
+ output.toByteString());
output.reset();
assertEquals("Output.reset() resets the output", 0, output.size());
- assertEquals("Output.reset() resets the output",
- EMPTY, output.toByteString());
+ assertEquals("Output.reset() resets the output", EMPTY, output.toByteString());
}
public void testToString() {
@@ -433,7 +444,8 @@ public class NioByteStringTest extends TestCase {
}
public void testToString_returnsCanonicalEmptyString() {
- assertSame(CLASSNAME + " must be the same string references",
+ assertSame(
+ CLASSNAME + " must be the same string references",
EMPTY.toString(UTF_8),
new NioByteString(ByteBuffer.wrap(new byte[0])).toString(UTF_8));
}
@@ -457,33 +469,34 @@ public class NioByteStringTest extends TestCase {
public void testEquals() {
assertEquals(CLASSNAME + " must not equal null", false, testString.equals(null));
assertEquals(CLASSNAME + " must equal self", testString, testString);
- assertFalse(CLASSNAME + " must not equal the empty string",
- testString.equals(EMPTY));
- assertEquals(CLASSNAME + " empty strings must be equal",
- EMPTY, testString.substring(55, 55));
- assertEquals(CLASSNAME + " must equal another string with the same value",
- testString, new NioByteString(backingBuffer));
+ assertFalse(CLASSNAME + " must not equal the empty string", testString.equals(EMPTY));
+ assertEquals(CLASSNAME + " empty strings must be equal", EMPTY, testString.substring(55, 55));
+ assertEquals(
+ CLASSNAME + " must equal another string with the same value",
+ testString,
+ new NioByteString(backingBuffer));
byte[] mungedBytes = mungedBytes();
- assertFalse(CLASSNAME + " must not equal every string with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every string with the same length",
testString.equals(new NioByteString(ByteBuffer.wrap(mungedBytes))));
}
public void testEqualsLiteralByteString() {
ByteString literal = ByteString.copyFrom(BYTES);
- assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal,
- testString);
- assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString,
- literal);
- assertFalse(CLASSNAME + " must not equal the empty string",
- testString.equals(ByteString.EMPTY));
- assertEquals(CLASSNAME + " empty strings must be equal",
- ByteString.EMPTY, testString.substring(55, 55));
+ assertEquals(CLASSNAME + " must equal LiteralByteString with same value", literal, testString);
+ assertEquals(CLASSNAME + " must equal LiteralByteString with same value", testString, literal);
+ assertFalse(
+ CLASSNAME + " must not equal the empty string", testString.equals(ByteString.EMPTY));
+ assertEquals(
+ CLASSNAME + " empty strings must be equal", ByteString.EMPTY, testString.substring(55, 55));
literal = ByteString.copyFrom(mungedBytes());
- assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every LiteralByteString with the same length",
testString.equals(literal));
- assertFalse(CLASSNAME + " must not equal every LiteralByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every LiteralByteString with the same length",
literal.equals(testString));
}
@@ -492,22 +505,25 @@ public class NioByteStringTest extends TestCase {
ByteString p2 = ByteString.copyFrom(BYTES, 5, BYTES.length - 5);
ByteString rope = p1.concat(p2);
- assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope,
- testString);
- assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString,
- rope);
- assertFalse(CLASSNAME + " must not equal the empty string",
+ assertEquals(CLASSNAME + " must equal RopeByteString with same value", rope, testString);
+ assertEquals(CLASSNAME + " must equal RopeByteString with same value", testString, rope);
+ assertFalse(
+ CLASSNAME + " must not equal the empty string",
testString.equals(ByteString.EMPTY.concat(ByteString.EMPTY)));
- assertEquals(CLASSNAME + " empty strings must be equal",
- ByteString.EMPTY.concat(ByteString.EMPTY), testString.substring(55, 55));
+ assertEquals(
+ CLASSNAME + " empty strings must be equal",
+ ByteString.EMPTY.concat(ByteString.EMPTY),
+ testString.substring(55, 55));
byte[] mungedBytes = mungedBytes();
p1 = ByteString.copyFrom(mungedBytes, 0, 5);
p2 = ByteString.copyFrom(mungedBytes, 5, mungedBytes.length - 5);
rope = p1.concat(p2);
- assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every RopeByteString with the same length",
testString.equals(rope));
- assertFalse(CLASSNAME + " must not equal every RopeByteString with the same length",
+ assertFalse(
+ CLASSNAME + " must not equal every RopeByteString with the same length",
rope.equals(testString));
}
@@ -525,32 +541,34 @@ public class NioByteStringTest extends TestCase {
public void testPeekCachedHashCode() {
ByteString newString = new NioByteString(backingBuffer);
- assertEquals(CLASSNAME + ".peekCachedHashCode() should return zero at first", 0,
+ assertEquals(
+ CLASSNAME + ".peekCachedHashCode() should return zero at first",
+ 0,
newString.peekCachedHashCode());
newString.hashCode();
- assertEquals(CLASSNAME + ".peekCachedHashCode should return zero at first",
- EXPECTED_HASH, newString.peekCachedHashCode());
+ assertEquals(
+ CLASSNAME + ".peekCachedHashCode should return zero at first",
+ EXPECTED_HASH,
+ newString.peekCachedHashCode());
}
public void testPartialHash() {
// partialHash() is more strenuously tested elsewhere by testing hashes of substrings.
// This test would fail if the expected hash were 1. It's not.
int hash = testString.partialHash(testString.size(), 0, testString.size());
- assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode",
- EXPECTED_HASH, hash);
+ assertEquals(CLASSNAME + ".partialHash() must yield expected hashCode", EXPECTED_HASH, hash);
}
public void testNewInput() throws IOException {
InputStream input = testString.newInput();
- assertEquals("InputStream.available() returns correct value",
- testString.size(), input.available());
+ assertEquals(
+ "InputStream.available() returns correct value", testString.size(), input.available());
boolean stillEqual = true;
for (byte referenceByte : BYTES) {
int expectedInt = (referenceByte & 0xFF);
stillEqual = (expectedInt == input.read());
}
- assertEquals("InputStream.available() returns correct value",
- 0, input.available());
+ assertEquals("InputStream.available() returns correct value", 0, input.available());
assertTrue(CLASSNAME + " must give the same bytes from the InputStream", stillEqual);
assertEquals(CLASSNAME + " InputStream must now be exhausted", -1, input.read());
}
@@ -561,43 +579,44 @@ public class NioByteStringTest extends TestCase {
int nearEndIndex = stringSize * 2 / 3;
long skipped1 = input.skip(nearEndIndex);
assertEquals("InputStream.skip()", skipped1, nearEndIndex);
- assertEquals("InputStream.available()",
- stringSize - skipped1, input.available());
+ assertEquals("InputStream.available()", stringSize - skipped1, input.available());
assertTrue("InputStream.mark() is available", input.markSupported());
input.mark(0);
- assertEquals("InputStream.skip(), read()",
- testString.byteAt(nearEndIndex) & 0xFF, input.read());
- assertEquals("InputStream.available()",
- stringSize - skipped1 - 1, input.available());
+ assertEquals(
+ "InputStream.skip(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available());
long skipped2 = input.skip(stringSize);
- assertEquals("InputStream.skip() incomplete",
- skipped2, stringSize - skipped1 - 1);
+ assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1);
assertEquals("InputStream.skip(), no more input", 0, input.available());
assertEquals("InputStream.skip(), no more input", -1, input.read());
input.reset();
- assertEquals("InputStream.reset() succeded",
- stringSize - skipped1, input.available());
- assertEquals("InputStream.reset(), read()",
- testString.byteAt(nearEndIndex) & 0xFF, input.read());
+ assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
+ assertEquals(
+ "InputStream.reset(), read()", testString.byteAt(nearEndIndex) & 0xFF, input.read());
}
public void testNewCodedInput() throws IOException {
CodedInputStream cis = testString.newCodedInput();
byte[] roundTripBytes = cis.readRawBytes(BYTES.length);
- assertTrue(CLASSNAME + " must give the same bytes back from the CodedInputStream",
+ assertTrue(
+ CLASSNAME + " must give the same bytes back from the CodedInputStream",
Arrays.equals(BYTES, roundTripBytes));
assertTrue(CLASSNAME + " CodedInputStream must now be exhausted", cis.isAtEnd());
}
/**
- * Make sure we keep things simple when concatenating with empty. See also
- * {@link ByteStringTest#testConcat_empty()}.
+ * Make sure we keep things simple when concatenating with empty. See also {@link
+ * ByteStringTest#testConcat_empty()}.
*/
public void testConcat_empty() {
- assertSame(CLASSNAME + " concatenated with empty must give " + CLASSNAME,
- testString.concat(EMPTY), testString);
- assertSame("empty concatenated with " + CLASSNAME + " must give " + CLASSNAME,
- EMPTY.concat(testString), testString);
+ assertSame(
+ CLASSNAME + " concatenated with empty must give " + CLASSNAME,
+ testString.concat(EMPTY),
+ testString);
+ assertSame(
+ "empty concatenated with " + CLASSNAME + " must give " + CLASSNAME,
+ EMPTY.concat(testString),
+ testString);
}
public void testJavaSerialization() throws Exception {
diff --git a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
index e376b1cd..20b93809 100644
--- a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
@@ -48,9 +48,9 @@ import org.junit.runners.JUnit4;
/**
* Tests the exceptions thrown when parsing from a stream. The methods on the {@link Parser}
* interface are specified to only throw {@link InvalidProtocolBufferException}. But we really want
- * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a
- * socket, etc.). So, when we're not using the parser directly, an {@link IOException} should be
- * thrown where appropriate, instead of always an {@link InvalidProtocolBufferException}.
+ * to distinguish between invalid protos vs. actual I/O errors (like failures reading from a socket,
+ * etc.). So, when we're not using the parser directly, an {@link IOException} should be thrown
+ * where appropriate, instead of always an {@link InvalidProtocolBufferException}.
*
* @author jh@squareup.com (Joshua Humphries)
*/
@@ -61,7 +61,7 @@ public class ParseExceptionsTest {
DescriptorProto parse(InputStream in) throws IOException;
}
- private byte serializedProto[];
+ private byte[] serializedProto;
private void setup() {
serializedProto = DescriptorProto.getDescriptor().toProto().toByteArray();
@@ -77,7 +77,8 @@ public class ParseExceptionsTest {
serializedProto = bos.toByteArray();
}
- @Test public void message_parseFrom_InputStream() {
+ @Test
+ public void message_parseFrom_InputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -88,7 +89,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseFrom_InputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -99,7 +101,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_CodedInputStream() {
+ @Test
+ public void message_parseFrom_CodedInputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -110,7 +113,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseFrom_CodedInputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseFrom_CodedInputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -122,7 +126,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseDelimitedFrom_InputStream() {
+ @Test
+ public void message_parseDelimitedFrom_InputStream() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -133,7 +138,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void message_parseDelimitedFrom_InputStreamAndExtensionRegistry() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -144,7 +150,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_InputStream() {
+ @Test
+ public void messageBuilder_mergeFrom_InputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -155,7 +162,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeFrom_InputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -168,7 +176,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_CodedInputStream() {
+ @Test
+ public void messageBuilder_mergeFrom_CodedInputStream() {
setup();
verifyExceptions(
new ParseTester() {
@@ -179,7 +188,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeFrom_CodedInputStreamAndExtensionRegistry() {
setup();
verifyExceptions(
new ParseTester() {
@@ -192,7 +202,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeDelimitedFrom_InputStream() {
+ @Test
+ public void messageBuilder_mergeDelimitedFrom_InputStream() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -205,7 +216,8 @@ public class ParseExceptionsTest {
});
}
- @Test public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() {
+ @Test
+ public void messageBuilder_mergeDelimitedFrom_InputStreamAndExtensionRegistry() {
setupDelimited();
verifyExceptions(
new ParseTester() {
@@ -221,7 +233,8 @@ public class ParseExceptionsTest {
private void verifyExceptions(ParseTester parseTester) {
// No exception
try {
- assertEquals(DescriptorProto.getDescriptor().toProto(),
+ assertEquals(
+ DescriptorProto.getDescriptor().toProto(),
parseTester.parse(new ByteArrayInputStream(serializedProto)));
} catch (IOException e) {
fail("No exception expected: " + e);
@@ -253,14 +266,16 @@ public class ParseExceptionsTest {
return new FilterInputStream(i) {
int count = 0;
- @Override public int read() throws IOException {
+ @Override
+ public int read() throws IOException {
if (count++ >= 50) {
throw new IOException("I'm broken!");
}
return super.read();
}
- @Override public int read(byte b[], int off, int len) throws IOException {
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
if ((count += len) >= 50) {
throw new IOException("I'm broken!");
}
diff --git a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
index af717bfd..67b2881a 100644
--- a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
@@ -38,37 +38,35 @@ import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
-/**
- * Tests for {@link ProtobufArrayList}.
- */
+/** Tests for {@link ProtobufArrayList}. */
public class ProtobufArrayListTest extends TestCase {
-
+
private static final ProtobufArrayList<Integer> UNARY_LIST = newImmutableProtoArrayList(1);
private static final ProtobufArrayList<Integer> TERTIARY_LIST =
newImmutableProtoArrayList(1, 2, 3);
-
+
private ProtobufArrayList<Integer> list;
-
+
@Override
protected void setUp() throws Exception {
list = new ProtobufArrayList<Integer>();
}
-
+
public void testEmptyListReturnsSameInstance() {
assertSame(ProtobufArrayList.emptyList(), ProtobufArrayList.emptyList());
}
-
+
public void testEmptyListIsImmutable() {
assertImmutable(ProtobufArrayList.<Integer>emptyList());
}
-
+
public void testModificationWithIteration() {
list.addAll(asList(1, 2, 3, 4));
Iterator<Integer> iterator = list.iterator();
assertEquals(4, list.size());
assertEquals(1, (int) list.get(0));
assertEquals(1, (int) iterator.next());
-
+
list.remove(0);
try {
iterator.next();
@@ -76,7 +74,7 @@ public class ProtobufArrayListTest extends TestCase {
} catch (ConcurrentModificationException e) {
// expected
}
-
+
iterator = list.iterator();
list.set(0, 1);
try {
@@ -85,7 +83,7 @@ public class ProtobufArrayListTest extends TestCase {
} catch (ConcurrentModificationException e) {
// expected
}
-
+
iterator = list.iterator();
list.add(0, 0);
try {
@@ -95,7 +93,7 @@ public class ProtobufArrayListTest extends TestCase {
// expected
}
}
-
+
public void testMakeImmutable() {
list.add(2);
list.add(4);
@@ -104,107 +102,213 @@ public class ProtobufArrayListTest extends TestCase {
list.makeImmutable();
assertImmutable(list);
}
-
+
public void testRemove() {
- list.add(2);
- list.add(4);
- list.add(6);
+ list.addAll(TERTIARY_LIST);
+ assertEquals(1, (int) list.remove(0));
+ assertEquals(asList(2, 3), list);
- list.remove(1);
- assertEquals(asList(2, 6), list);
+ assertTrue(list.remove(Integer.valueOf(3)));
+ assertEquals(asList(2), list);
- list.remove(1);
+ assertFalse(list.remove(Integer.valueOf(3)));
assertEquals(asList(2), list);
- list.remove(0);
+ assertEquals(2, (int) list.remove(0));
assertEquals(asList(), list);
+
+ try {
+ list.remove(-1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ list.remove(0);
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
}
-
+
public void testGet() {
- list.add(2);
- list.add(6);
-
- assertEquals(2, (int) list.get(0));
- assertEquals(6, (int) list.get(1));
+ assertEquals(1, (int) TERTIARY_LIST.get(0));
+ assertEquals(2, (int) TERTIARY_LIST.get(1));
+ assertEquals(3, (int) TERTIARY_LIST.get(2));
+
+ try {
+ TERTIARY_LIST.get(-1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ TERTIARY_LIST.get(3);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
}
-
+
public void testSet() {
list.add(2);
- list.add(6);
-
- list.set(0, 1);
+ list.add(4);
+
+ assertEquals(2, (int) list.set(0, 3));
+ assertEquals(3, (int) list.get(0));
+
+ assertEquals(4, (int) list.set(1, 0));
+ assertEquals(0, (int) list.get(1));
+
+ try {
+ list.set(-1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ list.set(2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testAdd() {
+ assertEquals(0, list.size());
+
+ assertTrue(list.add(2));
+ assertEquals(asList(2), list);
+
+ assertTrue(list.add(3));
+ list.add(0, 4);
+ assertEquals(asList(4, 2, 3), list);
+
+ list.add(0, 1);
+ list.add(0, 0);
+ // Force a resize by getting up to 11 elements.
+ for (int i = 0; i < 6; i++) {
+ list.add(Integer.valueOf(5 + i));
+ }
+ assertEquals(asList(0, 1, 4, 2, 3, 5, 6, 7, 8, 9, 10), list);
+
+ try {
+ list.add(-1, 5);
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ list.add(4, 5);
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testAddAll() {
+ assertEquals(0, list.size());
+
+ assertTrue(list.addAll(Collections.singleton(1)));
+ assertEquals(1, list.size());
assertEquals(1, (int) list.get(0));
- list.set(1, 2);
- assertEquals(2, (int) list.get(1));
+
+ assertTrue(list.addAll(asList(2, 3, 4, 5, 6)));
+ assertEquals(asList(1, 2, 3, 4, 5, 6), list);
+
+ assertTrue(list.addAll(TERTIARY_LIST));
+ assertEquals(asList(1, 2, 3, 4, 5, 6, 1, 2, 3), list);
+
+ assertFalse(list.addAll(Collections.<Integer>emptyList()));
+ assertFalse(list.addAll(IntArrayList.emptyList()));
+ }
+
+ public void testSize() {
+ assertEquals(0, ProtobufArrayList.emptyList().size());
+ assertEquals(1, UNARY_LIST.size());
+ assertEquals(3, TERTIARY_LIST.size());
+
+ list.add(3);
+ list.add(4);
+ list.add(6);
+ list.add(8);
+ assertEquals(4, list.size());
+
+ list.remove(0);
+ assertEquals(3, list.size());
+
+ list.add(17);
+ assertEquals(4, list.size());
}
private void assertImmutable(List<Integer> list) {
if (list.contains(1)) {
throw new RuntimeException("Cannot test the immutability of lists that contain 1.");
}
-
+
try {
list.add(1);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.add(0, 1);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(Collections.<Integer>emptyList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(Collections.singletonList(1));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(new ProtobufArrayList<Integer>());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(UNARY_LIST);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(0, Collections.singleton(1));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(0, UNARY_LIST);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.addAll(0, Collections.<Integer>emptyList());
fail();
} catch (UnsupportedOperationException e) {
// expected
- }
+ }
try {
list.clear();
@@ -219,56 +323,56 @@ public class ProtobufArrayListTest extends TestCase {
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.remove(new Object());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.removeAll(Collections.emptyList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.removeAll(Collections.singleton(1));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.removeAll(UNARY_LIST);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(Collections.emptyList());
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(Collections.singleton(1));
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.retainAll(UNARY_LIST);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
-
+
try {
list.set(0, 0);
fail();
@@ -276,7 +380,7 @@ public class ProtobufArrayListTest extends TestCase {
// expected
}
}
-
+
private static ProtobufArrayList<Integer> newImmutableProtoArrayList(int... elements) {
ProtobufArrayList<Integer> list = new ProtobufArrayList<Integer>();
for (int element : elements) {
diff --git a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
index edbd0afd..c42813c8 100644
--- a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
+++ b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
@@ -37,9 +37,8 @@ import java.util.List;
import junit.framework.TestCase;
/**
- * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality.
- * More extensive testing is provided via other tests that exercise the
- * builder.
+ * Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality. More extensive testing is
+ * provided via other tests that exercise the builder.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -47,8 +46,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testBasicUse() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -68,8 +67,8 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testGoingBackAndForth() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -89,7 +88,7 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
list = builder.build();
assertEquals(2, list.size());
assertEquals(0, list.get(0).getOptionalInt32());
- assertEquals("foo", list.get(0).getOptionalString());
+ assertEquals("foo", list.get(0).getOptionalString());
assertEquals(1, list.get(1).getOptionalInt32());
assertIsUnmodifiable(list);
assertEquals(1, mockParent.getInvalidationCount());
@@ -97,12 +96,11 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testVariousMethods() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(2).build());
- builder.addBuilder(0, TestAllTypes.getDefaultInstance())
- .setOptionalInt32(0);
+ builder.addBuilder(0, TestAllTypes.getDefaultInstance()).setOptionalInt32(0);
builder.addBuilder(TestAllTypes.getDefaultInstance()).setOptionalInt32(3);
assertEquals(0, builder.getMessage(0).getOptionalInt32());
@@ -139,11 +137,10 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
public void testLists() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder = newRepeatedFieldBuilderV3(mockParent);
+ RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ newRepeatedFieldBuilderV3(mockParent);
builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
- builder.addMessage(0,
- TestAllTypes.newBuilder().setOptionalInt32(0).build());
+ builder.addMessage(0, TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertEquals(0, builder.getMessage(0).getOptionalInt32());
assertEquals(1, builder.getMessage(1).getOptionalInt32());
@@ -178,11 +175,9 @@ public class RepeatedFieldBuilderV3Test extends TestCase {
}
}
- private RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>
+ private RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>
newRepeatedFieldBuilderV3(GeneratedMessage.BuilderParent parent) {
- return new RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(Collections.<TestAllTypes>emptyList(), false,
- parent, false);
+ return new RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ Collections.<TestAllTypes>emptyList(), false, parent, false);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
index dc56f2e9..d7262161 100644
--- a/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringSubstringTest.java
@@ -34,8 +34,8 @@ import java.io.UnsupportedEncodingException;
import java.util.Iterator;
/**
- * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from
- * {@link LiteralByteStringTest}. Only a couple of methods are overridden.
+ * This class tests {@link RopeByteString#substring(int, int)} by inheriting the tests from {@link
+ * LiteralByteStringTest}. Only a couple of methods are overridden.
*
* @author carlanton@google.com (Carl Haverl)
*/
@@ -61,8 +61,8 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
@Override
public void testGetTreeDepth() {
- assertEquals(classUnderTest + " must have the expected tree depth",
- 3, stringUnderTest.getTreeDepth());
+ assertEquals(
+ classUnderTest + " must have the expected tree depth", 3, stringUnderTest.getTreeDepth());
}
@Override
@@ -84,15 +84,18 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
testString = testString.substring(2, testString.length() - 6);
unicode = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
@@ -114,14 +117,17 @@ public class RopeByteStringSubstringTest extends LiteralByteStringTest {
testString = testString.substring(2, testString.length() - 6);
unicode = unicode.substring(2, unicode.size() - 6);
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
index 4ec3a409..59e8ede1 100644
--- a/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/RopeByteStringTest.java
@@ -40,8 +40,8 @@ import java.util.Arrays;
import java.util.Iterator;
/**
- * This class tests {@link RopeByteString} by inheriting the tests from
- * {@link LiteralByteStringTest}. Only a couple of methods are overridden.
+ * This class tests {@link RopeByteString} by inheriting the tests from {@link
+ * LiteralByteStringTest}. Only a couple of methods are overridden.
*
* <p>A full test of the result of {@link RopeByteString#substring(int, int)} is found in the
* separate class {@link RopeByteStringSubstringTest}.
@@ -64,8 +64,8 @@ public class RopeByteStringTest extends LiteralByteStringTest {
@Override
public void testGetTreeDepth() {
- assertEquals(classUnderTest + " must have the expected tree depth",
- 4, stringUnderTest.getTreeDepth());
+ assertEquals(
+ classUnderTest + " must have the expected tree depth", 4, stringUnderTest.getTreeDepth());
}
public void testBalance() {
@@ -79,17 +79,22 @@ public class RopeByteStringTest extends LiteralByteStringTest {
concatenated = concatenated.concat(ByteString.copyFrom(testBytes, i * pieceSize, pieceSize));
}
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(concatenated));
- assertTrue(classUnderTest + " underlying bytes must match after balancing",
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(concatenated));
+ assertTrue(
+ classUnderTest + " underlying bytes must match after balancing",
Arrays.equals(testBytes, concatenated.toByteArray()));
ByteString testString = ByteString.copyFrom(testBytes);
- assertTrue(classUnderTest + " balanced string must equal flat string",
- concatenated.equals(testString));
- assertTrue(classUnderTest + " flat string must equal balanced string",
- testString.equals(concatenated));
- assertEquals(classUnderTest + " balanced string must have same hash code as flat string",
- testString.hashCode(), concatenated.hashCode());
+ assertEquals(
+ classUnderTest + " balanced string must equal flat string", testString, concatenated);
+ assertEquals(
+ classUnderTest + " flat string must equal balanced string", concatenated, testString);
+ assertEquals(
+ classUnderTest + " balanced string must have same hash code as flat string",
+ testString.hashCode(),
+ concatenated.hashCode());
}
@Override
@@ -107,15 +112,18 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
String testString = builder.toString();
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
@@ -133,30 +141,34 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
String testString = builder.toString();
- assertEquals(classUnderTest + " from string must have the expected type",
- classUnderTest, getActualClassName(unicode));
+ assertEquals(
+ classUnderTest + " from string must have the expected type",
+ classUnderTest,
+ getActualClassName(unicode));
String roundTripString = unicode.toString(Internal.UTF_8);
- assertEquals(classUnderTest + " unicode bytes must match",
- testString, roundTripString);
+ assertEquals(classUnderTest + " unicode bytes must match", testString, roundTripString);
ByteString flatString = ByteString.copyFromUtf8(testString);
assertEquals(classUnderTest + " string must equal the flat string", flatString, unicode);
- assertEquals(classUnderTest + " string must must have same hashCode as the flat string",
- flatString.hashCode(), unicode.hashCode());
+ assertEquals(
+ classUnderTest + " string must must have same hashCode as the flat string",
+ flatString.hashCode(),
+ unicode.hashCode());
}
@Override
public void testToString_returnsCanonicalEmptyString() {
RopeByteString ropeByteString =
RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
- assertSame(classUnderTest + " must be the same string references",
- ByteString.EMPTY.toString(Internal.UTF_8), ropeByteString.toString(Internal.UTF_8));
+ assertSame(
+ classUnderTest + " must be the same string references",
+ ByteString.EMPTY.toString(Internal.UTF_8),
+ ropeByteString.toString(Internal.UTF_8));
}
@Override
public void testToString_raisesException() {
try {
- ByteString byteString =
- RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
+ ByteString byteString = RopeByteString.newInstanceForTest(ByteString.EMPTY, ByteString.EMPTY);
byteString.toString("invalid");
fail("Should have thrown an exception.");
} catch (UnsupportedEncodingException expected) {
@@ -164,8 +176,9 @@ public class RopeByteStringTest extends LiteralByteStringTest {
}
try {
- ByteString byteString = RopeByteString.concatenate(ByteString.copyFromUtf8("foo"),
- ByteString.copyFromUtf8("bar"));
+ ByteString byteString =
+ RopeByteString.concatenate(
+ ByteString.copyFromUtf8("foo"), ByteString.copyFromUtf8("bar"));
byteString.toString("invalid");
fail("Should have thrown an exception.");
} catch (UnsupportedEncodingException expected) {
diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
index b895ad8d..1e583329 100644
--- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
@@ -41,7 +41,6 @@ import protobuf_unittest.UnittestProto.FooRequest;
import protobuf_unittest.UnittestProto.FooResponse;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestService;
-
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
@@ -270,30 +269,27 @@ public class ServiceTest extends TestCase {
}
-
// =================================================================
/**
- * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c)
- * matches a callback if calling that callback causes c to be called.
- * In other words, c wraps the given callback.
+ * wrapsCallback() is an EasyMock argument predicate. wrapsCallback(c) matches a callback if
+ * calling that callback causes c to be called. In other words, c wraps the given callback.
*/
- private <Type extends Message> RpcCallback<Type> wrapsCallback(
- MockCallback<?> callback) {
+ private <T extends Message> RpcCallback<T> wrapsCallback(MockCallback<?> callback) {
EasyMock.reportMatcher(new WrapsCallback(callback));
return null;
}
/** The parameter to wrapsCallback() must be a MockCallback. */
- private static class MockCallback<Type extends Message>
- implements RpcCallback<Type> {
+ private static class MockCallback<T extends Message> implements RpcCallback<T> {
private boolean called = false;
public boolean isCalled() { return called; }
public void reset() { called = false; }
+
@Override
- public void run(Type message) {
+ public void run(T message) {
called = true; }
}
diff --git a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
index e3a8d4f4..f2ae8f9b 100644
--- a/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
+++ b/java/core/src/test/java/com/google/protobuf/SingleFieldBuilderV3Test.java
@@ -32,13 +32,11 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
-
import junit.framework.TestCase;
/**
- * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality.
- * More extensive testing is provided via other tests that exercise the
- * builder.
+ * Tests for {@link SingleFieldBuilderV3}. This tests basic functionality. More extensive testing is
+ * provided via other tests that exercise the builder.
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -46,16 +44,11 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testBasicUseAndInvalidations() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
assertSame(TestAllTypes.getDefaultInstance(), builder.getMessage());
- assertEquals(TestAllTypes.getDefaultInstance(),
- builder.getBuilder().buildPartial());
+ assertEquals(TestAllTypes.getDefaultInstance(), builder.getBuilder().buildPartial());
assertEquals(0, mockParent.getInvalidationCount());
builder.getBuilder().setOptionalInt32(10);
@@ -71,18 +64,13 @@ public class SingleFieldBuilderV3Test extends TestCase {
// Test that we don't keep getting invalidations on every change
builder.getBuilder().setOptionalInt32(30);
assertEquals(1, mockParent.getInvalidationCount());
-
}
public void testSetMessage() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertEquals(0, builder.getMessage().getOptionalInt32());
@@ -102,13 +90,9 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testClear() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
assertNotSame(TestAllTypes.getDefaultInstance(), builder.getMessage());
builder.clear();
@@ -122,13 +106,9 @@ public class SingleFieldBuilderV3Test extends TestCase {
public void testMerge() {
TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
- SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder> builder =
- new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder,
- TestAllTypesOrBuilder>(
- TestAllTypes.getDefaultInstance(),
- mockParent,
- false);
+ SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
+ new SingleFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder>(
+ TestAllTypes.getDefaultInstance(), mockParent, false);
// Merge into default field.
builder.mergeFrom(TestAllTypes.getDefaultInstance());
@@ -136,20 +116,14 @@ public class SingleFieldBuilderV3Test extends TestCase {
// Merge into non-default field on existing builder.
builder.getBuilder().setOptionalInt32(2);
- builder.mergeFrom(TestAllTypes.newBuilder()
- .setOptionalDouble(4.0)
- .buildPartial());
+ builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(4.0).buildPartial());
assertEquals(2, builder.getMessage().getOptionalInt32());
- assertEquals(4.0, builder.getMessage().getOptionalDouble());
+ assertEquals(4.0, builder.getMessage().getOptionalDouble(), 0.0);
// Merge into non-default field on existing message
- builder.setMessage(TestAllTypes.newBuilder()
- .setOptionalInt32(10)
- .buildPartial());
- builder.mergeFrom(TestAllTypes.newBuilder()
- .setOptionalDouble(5.0)
- .buildPartial());
+ builder.setMessage(TestAllTypes.newBuilder().setOptionalInt32(10).buildPartial());
+ builder.mergeFrom(TestAllTypes.newBuilder().setOptionalDouble(5.0).buildPartial());
assertEquals(10, builder.getMessage().getOptionalInt32());
- assertEquals(5.0, builder.getMessage().getOptionalDouble());
+ assertEquals(5.0, builder.getMessage().getOptionalDouble(), 0.0);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
index a7f8342d..a1a7194b 100644
--- a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
@@ -40,9 +40,7 @@ import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
-/**
- * @author darick@google.com Darick Tong
- */
+/** @author darick@google.com Darick Tong */
public class SmallSortedMapTest extends TestCase {
// java.util.AbstractMap.SimpleEntry is private in JDK 1.5. We re-implement it
// here for JDK 1.5 users.
@@ -78,16 +76,16 @@ public class SmallSortedMapTest extends TestCase {
@Override
public boolean equals(Object o) {
- if (!(o instanceof Map.Entry))
+ if (!(o instanceof Map.Entry)) {
return false;
+ }
Map.Entry e = (Map.Entry) o;
return eq(key, e.getKey()) && eq(value, e.getValue());
}
@Override
public int hashCode() {
- return ((key == null) ? 0 : key.hashCode()) ^
- ((value == null) ? 0 : value.hashCode());
+ return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode());
}
}
@@ -101,14 +99,10 @@ public class SmallSortedMapTest extends TestCase {
private void runPutAndGetTest(int numElements) {
// Test with even and odd arraySize
- SmallSortedMap<Integer, Integer> map1 =
- SmallSortedMap.newInstanceForTest(3);
- SmallSortedMap<Integer, Integer> map2 =
- SmallSortedMap.newInstanceForTest(4);
- SmallSortedMap<Integer, Integer> map3 =
- SmallSortedMap.newInstanceForTest(3);
- SmallSortedMap<Integer, Integer> map4 =
- SmallSortedMap.newInstanceForTest(4);
+ SmallSortedMap<Integer, Integer> map1 = SmallSortedMap.newInstanceForTest(3);
+ SmallSortedMap<Integer, Integer> map2 = SmallSortedMap.newInstanceForTest(4);
+ SmallSortedMap<Integer, Integer> map3 = SmallSortedMap.newInstanceForTest(3);
+ SmallSortedMap<Integer, Integer> map4 = SmallSortedMap.newInstanceForTest(4);
// Test with puts in ascending order.
for (int i = 0; i < numElements; i++) {
@@ -136,7 +130,7 @@ public class SmallSortedMapTest extends TestCase {
for (SmallSortedMap<Integer, Integer> map : allMaps) {
assertEquals(numElements, map.size());
for (int i = 0; i < numElements; i++) {
- assertEquals(new Integer(i + 1), map.get(i));
+ assertEquals(Integer.valueOf(i + 1), map.get(i));
}
}
@@ -152,7 +146,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.remove(i + 1));
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 1), map.put(i, i + 2));
+ assertEquals(Integer.valueOf(i + 1), map.put(i, i + 2));
}
}
@@ -165,22 +159,22 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(3, map.getNumArrayEntries());
assertEquals(3, map.getNumOverflowEntries());
- assertEquals(6, map.size());
+ assertEquals(6, map.size());
assertEquals(makeSortedKeySet(0, 1, 2, 3, 4, 5), map.keySet());
- assertEquals(new Integer(2), map.remove(1));
+ assertEquals(Integer.valueOf(2), map.remove(1));
assertEquals(3, map.getNumArrayEntries());
assertEquals(2, map.getNumOverflowEntries());
- assertEquals(5, map.size());
+ assertEquals(5, map.size());
assertEquals(makeSortedKeySet(0, 2, 3, 4, 5), map.keySet());
- assertEquals(new Integer(5), map.remove(4));
+ assertEquals(Integer.valueOf(5), map.remove(4));
assertEquals(3, map.getNumArrayEntries());
assertEquals(1, map.getNumOverflowEntries());
- assertEquals(4, map.size());
+ assertEquals(4, map.size());
assertEquals(makeSortedKeySet(0, 2, 3, 5), map.keySet());
- assertEquals(new Integer(4), map.remove(3));
+ assertEquals(Integer.valueOf(4), map.remove(3));
assertEquals(3, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
assertEquals(3, map.size());
@@ -191,7 +185,7 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(0, map.getNumOverflowEntries());
assertEquals(3, map.size());
- assertEquals(new Integer(1), map.remove(0));
+ assertEquals(Integer.valueOf(1), map.remove(0));
assertEquals(2, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
assertEquals(2, map.size());
@@ -216,16 +210,15 @@ public class SmallSortedMapTest extends TestCase {
assertEquals(3, map.getNumArrayEntries());
for (int i = 0; i < 3; i++) {
Map.Entry<Integer, Integer> entry = map.getArrayEntryAt(i);
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
- Iterator<Map.Entry<Integer, Integer>> it =
- map.getOverflowEntries().iterator();
+ Iterator<Map.Entry<Integer, Integer>> it = map.getOverflowEntries().iterator();
for (int i = 3; i < 6; i++) {
assertTrue(it.hasNext());
Map.Entry<Integer, Integer> entry = it.next();
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
assertFalse(it.hasNext());
}
@@ -237,10 +230,8 @@ public class SmallSortedMapTest extends TestCase {
}
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for (int i = 0; i < 6; i++) {
- assertTrue(
- entrySet.contains(new SimpleEntry<Integer, Integer>(i, i + 1)));
- assertFalse(
- entrySet.contains(new SimpleEntry<Integer, Integer>(i, i)));
+ assertTrue(entrySet.contains(new SimpleEntry<Integer, Integer>(i, i + 1)));
+ assertFalse(entrySet.contains(new SimpleEntry<Integer, Integer>(i, i)));
}
}
@@ -248,13 +239,12 @@ public class SmallSortedMapTest extends TestCase {
SmallSortedMap<Integer, Integer> map = SmallSortedMap.newInstanceForTest(3);
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
for (int i = 0; i < 6; i++) {
- Map.Entry<Integer, Integer> entry =
- new SimpleEntry<Integer, Integer>(i, i + 1);
+ Map.Entry<Integer, Integer> entry = new SimpleEntry<Integer, Integer>(i, i + 1);
assertTrue(entrySet.add(entry));
assertFalse(entrySet.add(entry));
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 1), map.get(i));
+ assertEquals(Integer.valueOf(i + 1), map.get(i));
}
assertEquals(3, map.getNumArrayEntries());
assertEquals(3, map.getNumOverflowEntries());
@@ -268,8 +258,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.put(i, i + 1));
}
for (int i = 0; i < 6; i++) {
- Map.Entry<Integer, Integer> entry =
- new SimpleEntry<Integer, Integer>(i, i + 1);
+ Map.Entry<Integer, Integer> entry = new SimpleEntry<Integer, Integer>(i, i + 1);
assertTrue(entrySet.remove(entry));
assertFalse(entrySet.remove(entry));
}
@@ -284,7 +273,7 @@ public class SmallSortedMapTest extends TestCase {
for (int i = 0; i < 6; i++) {
assertNull(map.put(i, i + 1));
}
- map.entrySet().clear();
+ map.clear();
assertTrue(map.isEmpty());
assertEquals(0, map.getNumArrayEntries());
assertEquals(0, map.getNumOverflowEntries());
@@ -300,8 +289,8 @@ public class SmallSortedMapTest extends TestCase {
for (int i = 0; i < 6; i++) {
assertTrue(it.hasNext());
Map.Entry<Integer, Integer> entry = it.next();
- assertEquals(new Integer(i), entry.getKey());
- assertEquals(new Integer(i + 1), entry.getValue());
+ assertEquals(Integer.valueOf(i), entry.getKey());
+ assertEquals(Integer.valueOf(i + 1), entry.getValue());
}
assertFalse(it.hasNext());
}
@@ -332,7 +321,7 @@ public class SmallSortedMapTest extends TestCase {
entry.setValue(i + 23);
}
for (int i = 0; i < 6; i++) {
- assertEquals(new Integer(i + 23), map.get(i));
+ assertEquals(Integer.valueOf(i + 23), map.get(i));
}
}
@@ -342,7 +331,7 @@ public class SmallSortedMapTest extends TestCase {
assertNull(map.put(i, i + 1));
}
map.makeImmutable();
- assertEquals(new Integer(1), map.get(0));
+ assertEquals(Integer.valueOf(1), map.get(0));
assertEquals(6, map.size());
try {
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 4af55429..3d82c5f9 100644
--- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
@@ -33,9 +33,9 @@ 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).
+ * 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).
*
* @author jonp@google.com (Jon Perlow)
*/
@@ -48,17 +48,11 @@ public class TestBadIdentifiers extends TestCase {
}
public void testGetDescriptor() {
- Descriptors.FileDescriptor fileDescriptor =
- TestBadIdentifiersProto.getDescriptor();
- String descriptorField = TestBadIdentifiersProto.Descriptor
- .getDefaultInstance().getDescriptor();
- Descriptors.Descriptor protoDescriptor = TestBadIdentifiersProto.Descriptor
- .getDefaultInstance().getDescriptorForType();
- String nestedDescriptorField = TestBadIdentifiersProto.Descriptor
- .NestedDescriptor.getDefaultInstance().getDescriptor();
- Descriptors.Descriptor nestedProtoDescriptor = TestBadIdentifiersProto
- .Descriptor.NestedDescriptor.getDefaultInstance()
- .getDescriptorForType();
+ TestBadIdentifiersProto.getDescriptor();
+ TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
+ TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
+ TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
+ TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();
}
public void testConflictingFieldNames() throws Exception {
@@ -87,10 +81,16 @@ public class TestBadIdentifiers extends TestCase {
assertEquals(0, message.getInt32FieldList31());
assertEquals(0, message.getInt64FieldCount());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount)
+ .longValue());
+ assertEquals(
+ 0L,
+ message
+ .getExtension(TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList)
+ .longValue());
assertEquals("", message.getFieldName32());
assertEquals("", message.getFieldName33());
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
index 37f94c03..798d7ca6 100644
--- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
+++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiersLite.java
@@ -75,9 +75,15 @@ public final class TestBadIdentifiersLite extends TestCase {
assertEquals(0, message.getInt32FieldList31());
assertEquals(0, message.getInt64FieldCount());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldCount).longValue());
- assertEquals(0L, message.getExtension(
- TestBadIdentifiersProto.TestConflictingFieldNames.int64FieldList).longValue());
+ 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 b4bc3a3d..48ee9574 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -130,8 +130,6 @@ import static protobuf_unittest.UnittestProto.defaultFixed64Extension;
import static protobuf_unittest.UnittestProto.defaultFloatExtension;
import static protobuf_unittest.UnittestProto.defaultForeignEnumExtension;
import static protobuf_unittest.UnittestProto.defaultImportEnumExtension;
-// The static imports are to avoid 100+ char lines. The following is roughly equivalent to
-// import static protobuf_unittest.UnittestProto.*;
import static protobuf_unittest.UnittestProto.defaultInt32Extension;
import static protobuf_unittest.UnittestProto.defaultInt64Extension;
import static protobuf_unittest.UnittestProto.defaultNestedEnumExtension;
@@ -239,14 +237,12 @@ import java.io.RandomAccessFile;
import junit.framework.Assert;
/**
- * Contains methods for setting all fields of {@code TestAllTypes} to
- * some values as well as checking that all the fields are set to those values.
- * These are useful for testing various protocol message features, e.g.
- * set all fields of a message, serialize it, parse it, and check that all
- * fields are set.
+ * Contains methods for setting all fields of {@code TestAllTypes} to some values as well as
+ * checking that all the fields are set to those values. These are useful for testing various
+ * protocol message features, e.g. set all fields of a message, serialize it, parse it, and check
+ * that all fields are set.
*
- * <p>This code is not to be used outside of {@code com.google.protobuf} and
- * subpackages.
+ * <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages.
*
* @author kenton@google.com Kenton Varda
*/
@@ -263,16 +259,16 @@ public final class TestUtil {
return ByteString.copyFrom(str.getBytes(Internal.UTF_8));
}
- /**
- * Dirties the message by resetting the momoized serialized size.
- */
+ // BEGIN FULL-RUNTIME
+ /** Dirties the message by resetting the momoized serialized size. */
public static void resetMemoizedSize(AbstractMessage message) {
message.memoizedSize = -1;
}
+ // END FULL-RUNTIME
/**
- * Get a {@code TestAllTypes} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}.
+ * Get a {@code TestAllTypes} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypes.Builder)}.
*/
public static TestAllTypes getAllSet() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -281,8 +277,8 @@ public final class TestUtil {
}
/**
- * Get a {@code TestAllTypes.Builder} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}.
+ * Get a {@code TestAllTypes.Builder} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypes.Builder)}.
*/
public static TestAllTypes.Builder getAllSetBuilder() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -291,8 +287,8 @@ public final class TestUtil {
}
/**
- * Get a {@code TestAllExtensions} with all fields set as they would be by
- * {@link #setAllExtensions(TestAllExtensions.Builder)}.
+ * Get a {@code TestAllExtensions} with all fields set as they would be by {@link
+ * #setAllExtensions(TestAllExtensions.Builder)}.
*/
public static TestAllExtensions getAllExtensionsSet() {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
@@ -318,146 +314,126 @@ public final class TestUtil {
return builder.build();
}
- /**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllFieldsSet()}.
- */
+ /** Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()}. */
public static void setAllFields(TestAllTypes.Builder message) {
- message.setOptionalInt32 (101);
- message.setOptionalInt64 (102);
- message.setOptionalUint32 (103);
- message.setOptionalUint64 (104);
- message.setOptionalSint32 (105);
- message.setOptionalSint64 (106);
- message.setOptionalFixed32 (107);
- message.setOptionalFixed64 (108);
+ message.setOptionalInt32(101);
+ message.setOptionalInt64(102);
+ message.setOptionalUint32(103);
+ message.setOptionalUint64(104);
+ message.setOptionalSint32(105);
+ message.setOptionalSint64(106);
+ message.setOptionalFixed32(107);
+ message.setOptionalFixed64(108);
message.setOptionalSfixed32(109);
message.setOptionalSfixed64(110);
- message.setOptionalFloat (111);
- message.setOptionalDouble (112);
- message.setOptionalBool (true);
- message.setOptionalString ("115");
- message.setOptionalBytes (toBytes("116"));
-
- message.setOptionalGroup(
- TestAllTypes.OptionalGroup.newBuilder().setA(117).build());
- message.setOptionalNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
- message.setOptionalForeignMessage(
- ForeignMessage.newBuilder().setC(119).build());
- message.setOptionalImportMessage(
- ImportMessage.newBuilder().setD(120).build());
- message.setOptionalPublicImportMessage(
- PublicImportMessage.newBuilder().setE(126).build());
- message.setOptionalLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
-
- message.setOptionalNestedEnum (TestAllTypes.NestedEnum.BAZ);
+ message.setOptionalFloat(111);
+ message.setOptionalDouble(112);
+ message.setOptionalBool(true);
+ message.setOptionalString("115");
+ message.setOptionalBytes(toBytes("116"));
+
+ message.setOptionalGroup(TestAllTypes.OptionalGroup.newBuilder().setA(117).build());
+ message.setOptionalNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
+ message.setOptionalForeignMessage(ForeignMessage.newBuilder().setC(119).build());
+ message.setOptionalImportMessage(ImportMessage.newBuilder().setD(120).build());
+ message.setOptionalPublicImportMessage(PublicImportMessage.newBuilder().setE(126).build());
+ message.setOptionalLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
+
+ message.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ);
message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ);
- message.setOptionalImportEnum (ImportEnum.IMPORT_BAZ);
+ message.setOptionalImportEnum(ImportEnum.IMPORT_BAZ);
message.setOptionalStringPiece("124");
message.setOptionalCord("125");
// -----------------------------------------------------------------
- message.addRepeatedInt32 (201);
- message.addRepeatedInt64 (202);
- message.addRepeatedUint32 (203);
- message.addRepeatedUint64 (204);
- message.addRepeatedSint32 (205);
- message.addRepeatedSint64 (206);
- message.addRepeatedFixed32 (207);
- message.addRepeatedFixed64 (208);
+ message.addRepeatedInt32(201);
+ message.addRepeatedInt64(202);
+ message.addRepeatedUint32(203);
+ message.addRepeatedUint64(204);
+ message.addRepeatedSint32(205);
+ message.addRepeatedSint64(206);
+ message.addRepeatedFixed32(207);
+ message.addRepeatedFixed64(208);
message.addRepeatedSfixed32(209);
message.addRepeatedSfixed64(210);
- message.addRepeatedFloat (211);
- message.addRepeatedDouble (212);
- message.addRepeatedBool (true);
- message.addRepeatedString ("215");
- message.addRepeatedBytes (toBytes("216"));
-
- message.addRepeatedGroup(
- TestAllTypes.RepeatedGroup.newBuilder().setA(217).build());
- message.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- message.addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(219).build());
- message.addRepeatedImportMessage(
- ImportMessage.newBuilder().setD(220).build());
- message.addRepeatedLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
-
- message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAR);
+ message.addRepeatedFloat(211);
+ message.addRepeatedDouble(212);
+ message.addRepeatedBool(true);
+ message.addRepeatedString("215");
+ message.addRepeatedBytes(toBytes("216"));
+
+ message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(217).build());
+ message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(219).build());
+ message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(220).build());
+ message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
+
+ message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAR);
message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
- message.addRepeatedImportEnum (ImportEnum.IMPORT_BAR);
+ message.addRepeatedImportEnum(ImportEnum.IMPORT_BAR);
message.addRepeatedStringPiece("224");
message.addRepeatedCord("225");
// Add a second one of each field.
- message.addRepeatedInt32 (301);
- message.addRepeatedInt64 (302);
- message.addRepeatedUint32 (303);
- message.addRepeatedUint64 (304);
- message.addRepeatedSint32 (305);
- message.addRepeatedSint64 (306);
- message.addRepeatedFixed32 (307);
- message.addRepeatedFixed64 (308);
+ message.addRepeatedInt32(301);
+ message.addRepeatedInt64(302);
+ message.addRepeatedUint32(303);
+ message.addRepeatedUint64(304);
+ message.addRepeatedSint32(305);
+ message.addRepeatedSint64(306);
+ message.addRepeatedFixed32(307);
+ message.addRepeatedFixed64(308);
message.addRepeatedSfixed32(309);
message.addRepeatedSfixed64(310);
- message.addRepeatedFloat (311);
- message.addRepeatedDouble (312);
- message.addRepeatedBool (false);
- message.addRepeatedString ("315");
- message.addRepeatedBytes (toBytes("316"));
-
- message.addRepeatedGroup(
- TestAllTypes.RepeatedGroup.newBuilder().setA(317).build());
- message.addRepeatedNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
- message.addRepeatedForeignMessage(
- ForeignMessage.newBuilder().setC(319).build());
- message.addRepeatedImportMessage(
- ImportMessage.newBuilder().setD(320).build());
- message.addRepeatedLazyMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
-
- message.addRepeatedNestedEnum (TestAllTypes.NestedEnum.BAZ);
+ message.addRepeatedFloat(311);
+ message.addRepeatedDouble(312);
+ message.addRepeatedBool(false);
+ message.addRepeatedString("315");
+ message.addRepeatedBytes(toBytes("316"));
+
+ message.addRepeatedGroup(TestAllTypes.RepeatedGroup.newBuilder().setA(317).build());
+ message.addRepeatedNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
+ message.addRepeatedForeignMessage(ForeignMessage.newBuilder().setC(319).build());
+ message.addRepeatedImportMessage(ImportMessage.newBuilder().setD(320).build());
+ message.addRepeatedLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
+
+ message.addRepeatedNestedEnum(TestAllTypes.NestedEnum.BAZ);
message.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAZ);
- message.addRepeatedImportEnum (ImportEnum.IMPORT_BAZ);
+ message.addRepeatedImportEnum(ImportEnum.IMPORT_BAZ);
message.addRepeatedStringPiece("324");
message.addRepeatedCord("325");
// -----------------------------------------------------------------
- message.setDefaultInt32 (401);
- message.setDefaultInt64 (402);
- message.setDefaultUint32 (403);
- message.setDefaultUint64 (404);
- message.setDefaultSint32 (405);
- message.setDefaultSint64 (406);
- message.setDefaultFixed32 (407);
- message.setDefaultFixed64 (408);
+ message.setDefaultInt32(401);
+ message.setDefaultInt64(402);
+ message.setDefaultUint32(403);
+ message.setDefaultUint64(404);
+ message.setDefaultSint32(405);
+ message.setDefaultSint64(406);
+ message.setDefaultFixed32(407);
+ message.setDefaultFixed64(408);
message.setDefaultSfixed32(409);
message.setDefaultSfixed64(410);
- message.setDefaultFloat (411);
- message.setDefaultDouble (412);
- message.setDefaultBool (false);
- message.setDefaultString ("415");
- message.setDefaultBytes (toBytes("416"));
+ message.setDefaultFloat(411);
+ message.setDefaultDouble(412);
+ message.setDefaultBool(false);
+ message.setDefaultString("415");
+ message.setDefaultBytes(toBytes("416"));
- message.setDefaultNestedEnum (TestAllTypes.NestedEnum.FOO);
+ message.setDefaultNestedEnum(TestAllTypes.NestedEnum.FOO);
message.setDefaultForeignEnum(ForeignEnum.FOREIGN_FOO);
- message.setDefaultImportEnum (ImportEnum.IMPORT_FOO);
+ message.setDefaultImportEnum(ImportEnum.IMPORT_FOO);
message.setDefaultStringPiece("424");
message.setDefaultCord("425");
message.setOneofUint32(601);
- message.setOneofNestedMessage(
- TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
+ message.setOneofNestedMessage(TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
message.setOneofString("603");
message.setOneofBytes(toBytes("604"));
}
@@ -465,40 +441,35 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Modify the repeated fields of {@code message} to contain the values
- * expected by {@code assertRepeatedFieldsModified()}.
+ * Modify the repeated fields of {@code message} to contain the values expected by {@code
+ * assertRepeatedFieldsModified()}.
*/
public static void modifyRepeatedFields(TestAllTypes.Builder message) {
- message.setRepeatedInt32 (1, 501);
- message.setRepeatedInt64 (1, 502);
- message.setRepeatedUint32 (1, 503);
- message.setRepeatedUint64 (1, 504);
- message.setRepeatedSint32 (1, 505);
- message.setRepeatedSint64 (1, 506);
- message.setRepeatedFixed32 (1, 507);
- message.setRepeatedFixed64 (1, 508);
+ message.setRepeatedInt32(1, 501);
+ message.setRepeatedInt64(1, 502);
+ message.setRepeatedUint32(1, 503);
+ message.setRepeatedUint64(1, 504);
+ message.setRepeatedSint32(1, 505);
+ message.setRepeatedSint64(1, 506);
+ message.setRepeatedFixed32(1, 507);
+ message.setRepeatedFixed64(1, 508);
message.setRepeatedSfixed32(1, 509);
message.setRepeatedSfixed64(1, 510);
- message.setRepeatedFloat (1, 511);
- message.setRepeatedDouble (1, 512);
- message.setRepeatedBool (1, true);
- message.setRepeatedString (1, "515");
- message.setRepeatedBytes (1, toBytes("516"));
-
- message.setRepeatedGroup(1,
- TestAllTypes.RepeatedGroup.newBuilder().setA(517).build());
- message.setRepeatedNestedMessage(1,
- TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
- message.setRepeatedForeignMessage(1,
- ForeignMessage.newBuilder().setC(519).build());
- message.setRepeatedImportMessage(1,
- ImportMessage.newBuilder().setD(520).build());
- message.setRepeatedLazyMessage(1,
- TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
-
- message.setRepeatedNestedEnum (1, TestAllTypes.NestedEnum.FOO);
+ message.setRepeatedFloat(1, 511);
+ message.setRepeatedDouble(1, 512);
+ message.setRepeatedBool(1, true);
+ message.setRepeatedString(1, "515");
+ message.setRepeatedBytes(1, toBytes("516"));
+
+ message.setRepeatedGroup(1, TestAllTypes.RepeatedGroup.newBuilder().setA(517).build());
+ message.setRepeatedNestedMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
+ message.setRepeatedForeignMessage(1, ForeignMessage.newBuilder().setC(519).build());
+ message.setRepeatedImportMessage(1, ImportMessage.newBuilder().setD(520).build());
+ message.setRepeatedLazyMessage(1, TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setRepeatedNestedEnum(1, TestAllTypes.NestedEnum.FOO);
message.setRepeatedForeignEnum(1, ForeignEnum.FOREIGN_FOO);
- message.setRepeatedImportEnum (1, ImportEnum.IMPORT_FOO);
+ message.setRepeatedImportEnum(1, ImportEnum.IMPORT_FOO);
message.setRepeatedStringPiece(1, "524");
message.setRepeatedCord(1, "525");
@@ -507,65 +478,65 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setAllFields}.
*/
public static void assertAllFieldsSet(TestAllTypesOrBuilder message) {
- Assert.assertTrue(message.hasOptionalInt32 ());
- Assert.assertTrue(message.hasOptionalInt64 ());
- Assert.assertTrue(message.hasOptionalUint32 ());
- Assert.assertTrue(message.hasOptionalUint64 ());
- Assert.assertTrue(message.hasOptionalSint32 ());
- Assert.assertTrue(message.hasOptionalSint64 ());
- Assert.assertTrue(message.hasOptionalFixed32 ());
- Assert.assertTrue(message.hasOptionalFixed64 ());
+ Assert.assertTrue(message.hasOptionalInt32());
+ Assert.assertTrue(message.hasOptionalInt64());
+ Assert.assertTrue(message.hasOptionalUint32());
+ Assert.assertTrue(message.hasOptionalUint64());
+ Assert.assertTrue(message.hasOptionalSint32());
+ Assert.assertTrue(message.hasOptionalSint64());
+ Assert.assertTrue(message.hasOptionalFixed32());
+ Assert.assertTrue(message.hasOptionalFixed64());
Assert.assertTrue(message.hasOptionalSfixed32());
Assert.assertTrue(message.hasOptionalSfixed64());
- Assert.assertTrue(message.hasOptionalFloat ());
- Assert.assertTrue(message.hasOptionalDouble ());
- Assert.assertTrue(message.hasOptionalBool ());
- Assert.assertTrue(message.hasOptionalString ());
- Assert.assertTrue(message.hasOptionalBytes ());
-
- Assert.assertTrue(message.hasOptionalGroup ());
- Assert.assertTrue(message.hasOptionalNestedMessage ());
+ Assert.assertTrue(message.hasOptionalFloat());
+ Assert.assertTrue(message.hasOptionalDouble());
+ Assert.assertTrue(message.hasOptionalBool());
+ Assert.assertTrue(message.hasOptionalString());
+ Assert.assertTrue(message.hasOptionalBytes());
+
+ Assert.assertTrue(message.hasOptionalGroup());
+ Assert.assertTrue(message.hasOptionalNestedMessage());
Assert.assertTrue(message.hasOptionalForeignMessage());
- Assert.assertTrue(message.hasOptionalImportMessage ());
+ Assert.assertTrue(message.hasOptionalImportMessage());
- Assert.assertTrue(message.getOptionalGroup ().hasA());
- Assert.assertTrue(message.getOptionalNestedMessage ().hasBb());
+ Assert.assertTrue(message.getOptionalGroup().hasA());
+ Assert.assertTrue(message.getOptionalNestedMessage().hasBb());
Assert.assertTrue(message.getOptionalForeignMessage().hasC());
- Assert.assertTrue(message.getOptionalImportMessage ().hasD());
+ Assert.assertTrue(message.getOptionalImportMessage().hasD());
- Assert.assertTrue(message.hasOptionalNestedEnum ());
+ Assert.assertTrue(message.hasOptionalNestedEnum());
Assert.assertTrue(message.hasOptionalForeignEnum());
- Assert.assertTrue(message.hasOptionalImportEnum ());
+ Assert.assertTrue(message.hasOptionalImportEnum());
Assert.assertTrue(message.hasOptionalStringPiece());
Assert.assertTrue(message.hasOptionalCord());
- Assert.assertEquals(101 , message.getOptionalInt32 ());
- Assert.assertEquals(102 , message.getOptionalInt64 ());
- Assert.assertEquals(103 , message.getOptionalUint32 ());
- Assert.assertEquals(104 , message.getOptionalUint64 ());
- Assert.assertEquals(105 , message.getOptionalSint32 ());
- Assert.assertEquals(106 , message.getOptionalSint64 ());
- Assert.assertEquals(107 , message.getOptionalFixed32 ());
- Assert.assertEquals(108 , message.getOptionalFixed64 ());
- Assert.assertEquals(109 , message.getOptionalSfixed32());
- Assert.assertEquals(110 , message.getOptionalSfixed64());
- Assert.assertEquals(111 , message.getOptionalFloat (), 0.0);
- Assert.assertEquals(112 , message.getOptionalDouble (), 0.0);
- Assert.assertEquals(true , message.getOptionalBool ());
- Assert.assertEquals("115", message.getOptionalString ());
+ Assert.assertEquals(101, message.getOptionalInt32());
+ Assert.assertEquals(102, message.getOptionalInt64());
+ Assert.assertEquals(103, message.getOptionalUint32());
+ Assert.assertEquals(104, message.getOptionalUint64());
+ Assert.assertEquals(105, message.getOptionalSint32());
+ Assert.assertEquals(106, message.getOptionalSint64());
+ Assert.assertEquals(107, message.getOptionalFixed32());
+ Assert.assertEquals(108, message.getOptionalFixed64());
+ Assert.assertEquals(109, message.getOptionalSfixed32());
+ Assert.assertEquals(110, message.getOptionalSfixed64());
+ Assert.assertEquals(111, message.getOptionalFloat(), 0.0);
+ Assert.assertEquals(112, message.getOptionalDouble(), 0.0);
+ Assert.assertEquals(true, message.getOptionalBool());
+ Assert.assertEquals("115", message.getOptionalString());
Assert.assertEquals(toBytes("116"), message.getOptionalBytes());
- Assert.assertEquals(117, message.getOptionalGroup ().getA());
- Assert.assertEquals(118, message.getOptionalNestedMessage ().getBb());
- Assert.assertEquals(119, message.getOptionalForeignMessage ().getC());
- Assert.assertEquals(120, message.getOptionalImportMessage ().getD());
+ Assert.assertEquals(117, message.getOptionalGroup().getA());
+ Assert.assertEquals(118, message.getOptionalNestedMessage().getBb());
+ Assert.assertEquals(119, message.getOptionalForeignMessage().getC());
+ Assert.assertEquals(120, message.getOptionalImportMessage().getD());
Assert.assertEquals(126, message.getOptionalPublicImportMessage().getE());
- Assert.assertEquals(127, message.getOptionalLazyMessage ().getBb());
+ Assert.assertEquals(127, message.getOptionalLazyMessage().getBb());
Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getOptionalNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getOptionalForeignEnum());
@@ -576,86 +547,86 @@ public final class TestUtil {
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getRepeatedInt32Count ());
- Assert.assertEquals(2, message.getRepeatedInt64Count ());
- Assert.assertEquals(2, message.getRepeatedUint32Count ());
- Assert.assertEquals(2, message.getRepeatedUint64Count ());
- Assert.assertEquals(2, message.getRepeatedSint32Count ());
- Assert.assertEquals(2, message.getRepeatedSint64Count ());
- Assert.assertEquals(2, message.getRepeatedFixed32Count ());
- Assert.assertEquals(2, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(2, message.getRepeatedInt32Count());
+ Assert.assertEquals(2, message.getRepeatedInt64Count());
+ Assert.assertEquals(2, message.getRepeatedUint32Count());
+ Assert.assertEquals(2, message.getRepeatedUint64Count());
+ Assert.assertEquals(2, message.getRepeatedSint32Count());
+ Assert.assertEquals(2, message.getRepeatedSint64Count());
+ Assert.assertEquals(2, message.getRepeatedFixed32Count());
+ Assert.assertEquals(2, message.getRepeatedFixed64Count());
Assert.assertEquals(2, message.getRepeatedSfixed32Count());
Assert.assertEquals(2, message.getRepeatedSfixed64Count());
- Assert.assertEquals(2, message.getRepeatedFloatCount ());
- Assert.assertEquals(2, message.getRepeatedDoubleCount ());
- Assert.assertEquals(2, message.getRepeatedBoolCount ());
- Assert.assertEquals(2, message.getRepeatedStringCount ());
- Assert.assertEquals(2, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(2, message.getRepeatedGroupCount ());
- Assert.assertEquals(2, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(2, message.getRepeatedFloatCount());
+ Assert.assertEquals(2, message.getRepeatedDoubleCount());
+ Assert.assertEquals(2, message.getRepeatedBoolCount());
+ Assert.assertEquals(2, message.getRepeatedStringCount());
+ Assert.assertEquals(2, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(2, message.getRepeatedGroupCount());
+ Assert.assertEquals(2, message.getRepeatedNestedMessageCount());
Assert.assertEquals(2, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(2, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(2, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(2, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(2, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(2, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(2, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(2, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(2, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(2, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(2, message.getRepeatedImportEnumCount());
Assert.assertEquals(2, message.getRepeatedStringPieceCount());
Assert.assertEquals(2, message.getRepeatedCordCount());
- Assert.assertEquals(201 , message.getRepeatedInt32 (0));
- Assert.assertEquals(202 , message.getRepeatedInt64 (0));
- Assert.assertEquals(203 , message.getRepeatedUint32 (0));
- Assert.assertEquals(204 , message.getRepeatedUint64 (0));
- Assert.assertEquals(205 , message.getRepeatedSint32 (0));
- Assert.assertEquals(206 , message.getRepeatedSint64 (0));
- Assert.assertEquals(207 , message.getRepeatedFixed32 (0));
- Assert.assertEquals(208 , message.getRepeatedFixed64 (0));
- Assert.assertEquals(209 , message.getRepeatedSfixed32(0));
- Assert.assertEquals(210 , message.getRepeatedSfixed64(0));
- Assert.assertEquals(211 , message.getRepeatedFloat (0), 0.0);
- Assert.assertEquals(212 , message.getRepeatedDouble (0), 0.0);
- Assert.assertEquals(true , message.getRepeatedBool (0));
- Assert.assertEquals("215", message.getRepeatedString (0));
+ Assert.assertEquals(201, message.getRepeatedInt32(0));
+ Assert.assertEquals(202, message.getRepeatedInt64(0));
+ Assert.assertEquals(203, message.getRepeatedUint32(0));
+ Assert.assertEquals(204, message.getRepeatedUint64(0));
+ Assert.assertEquals(205, message.getRepeatedSint32(0));
+ Assert.assertEquals(206, message.getRepeatedSint64(0));
+ Assert.assertEquals(207, message.getRepeatedFixed32(0));
+ Assert.assertEquals(208, message.getRepeatedFixed64(0));
+ Assert.assertEquals(209, message.getRepeatedSfixed32(0));
+ Assert.assertEquals(210, message.getRepeatedSfixed64(0));
+ Assert.assertEquals(211, message.getRepeatedFloat(0), 0.0);
+ Assert.assertEquals(212, message.getRepeatedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getRepeatedBool(0));
+ Assert.assertEquals("215", message.getRepeatedString(0));
Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0));
- Assert.assertEquals(217, message.getRepeatedGroup (0).getA());
- Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb());
+ Assert.assertEquals(217, message.getRepeatedGroup(0).getA());
+ Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb());
Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC());
- Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD());
- Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb());
+ Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD());
+ Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0));
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0));
Assert.assertEquals("224", message.getRepeatedStringPiece(0));
Assert.assertEquals("225", message.getRepeatedCord(0));
- Assert.assertEquals(301 , message.getRepeatedInt32 (1));
- Assert.assertEquals(302 , message.getRepeatedInt64 (1));
- Assert.assertEquals(303 , message.getRepeatedUint32 (1));
- Assert.assertEquals(304 , message.getRepeatedUint64 (1));
- Assert.assertEquals(305 , message.getRepeatedSint32 (1));
- Assert.assertEquals(306 , message.getRepeatedSint64 (1));
- Assert.assertEquals(307 , message.getRepeatedFixed32 (1));
- Assert.assertEquals(308 , message.getRepeatedFixed64 (1));
- Assert.assertEquals(309 , message.getRepeatedSfixed32(1));
- Assert.assertEquals(310 , message.getRepeatedSfixed64(1));
- Assert.assertEquals(311 , message.getRepeatedFloat (1), 0.0);
- Assert.assertEquals(312 , message.getRepeatedDouble (1), 0.0);
- Assert.assertEquals(false, message.getRepeatedBool (1));
- Assert.assertEquals("315", message.getRepeatedString (1));
+ Assert.assertEquals(301, message.getRepeatedInt32(1));
+ Assert.assertEquals(302, message.getRepeatedInt64(1));
+ Assert.assertEquals(303, message.getRepeatedUint32(1));
+ Assert.assertEquals(304, message.getRepeatedUint64(1));
+ Assert.assertEquals(305, message.getRepeatedSint32(1));
+ Assert.assertEquals(306, message.getRepeatedSint64(1));
+ Assert.assertEquals(307, message.getRepeatedFixed32(1));
+ Assert.assertEquals(308, message.getRepeatedFixed64(1));
+ Assert.assertEquals(309, message.getRepeatedSfixed32(1));
+ Assert.assertEquals(310, message.getRepeatedSfixed64(1));
+ Assert.assertEquals(311, message.getRepeatedFloat(1), 0.0);
+ Assert.assertEquals(312, message.getRepeatedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getRepeatedBool(1));
+ Assert.assertEquals("315", message.getRepeatedString(1));
Assert.assertEquals(toBytes("316"), message.getRepeatedBytes(1));
- Assert.assertEquals(317, message.getRepeatedGroup (1).getA());
- Assert.assertEquals(318, message.getRepeatedNestedMessage (1).getBb());
+ Assert.assertEquals(317, message.getRepeatedGroup(1).getA());
+ Assert.assertEquals(318, message.getRepeatedNestedMessage(1).getBb());
Assert.assertEquals(319, message.getRepeatedForeignMessage(1).getC());
- Assert.assertEquals(320, message.getRepeatedImportMessage (1).getD());
- Assert.assertEquals(327, message.getRepeatedLazyMessage (1).getBb());
+ Assert.assertEquals(320, message.getRepeatedImportMessage(1).getD());
+ Assert.assertEquals(327, message.getRepeatedLazyMessage(1).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum (1));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAZ, message.getRepeatedNestedEnum(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getRepeatedForeignEnum(1));
Assert.assertEquals(ImportEnum.IMPORT_BAZ, message.getRepeatedImportEnum(1));
@@ -664,46 +635,46 @@ public final class TestUtil {
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasDefaultInt32 ());
- Assert.assertTrue(message.hasDefaultInt64 ());
- Assert.assertTrue(message.hasDefaultUint32 ());
- Assert.assertTrue(message.hasDefaultUint64 ());
- Assert.assertTrue(message.hasDefaultSint32 ());
- Assert.assertTrue(message.hasDefaultSint64 ());
- Assert.assertTrue(message.hasDefaultFixed32 ());
- Assert.assertTrue(message.hasDefaultFixed64 ());
+ Assert.assertTrue(message.hasDefaultInt32());
+ Assert.assertTrue(message.hasDefaultInt64());
+ Assert.assertTrue(message.hasDefaultUint32());
+ Assert.assertTrue(message.hasDefaultUint64());
+ Assert.assertTrue(message.hasDefaultSint32());
+ Assert.assertTrue(message.hasDefaultSint64());
+ Assert.assertTrue(message.hasDefaultFixed32());
+ Assert.assertTrue(message.hasDefaultFixed64());
Assert.assertTrue(message.hasDefaultSfixed32());
Assert.assertTrue(message.hasDefaultSfixed64());
- Assert.assertTrue(message.hasDefaultFloat ());
- Assert.assertTrue(message.hasDefaultDouble ());
- Assert.assertTrue(message.hasDefaultBool ());
- Assert.assertTrue(message.hasDefaultString ());
- Assert.assertTrue(message.hasDefaultBytes ());
+ Assert.assertTrue(message.hasDefaultFloat());
+ Assert.assertTrue(message.hasDefaultDouble());
+ Assert.assertTrue(message.hasDefaultBool());
+ Assert.assertTrue(message.hasDefaultString());
+ Assert.assertTrue(message.hasDefaultBytes());
- Assert.assertTrue(message.hasDefaultNestedEnum ());
+ Assert.assertTrue(message.hasDefaultNestedEnum());
Assert.assertTrue(message.hasDefaultForeignEnum());
- Assert.assertTrue(message.hasDefaultImportEnum ());
+ Assert.assertTrue(message.hasDefaultImportEnum());
Assert.assertTrue(message.hasDefaultStringPiece());
Assert.assertTrue(message.hasDefaultCord());
- Assert.assertEquals(401 , message.getDefaultInt32 ());
- Assert.assertEquals(402 , message.getDefaultInt64 ());
- Assert.assertEquals(403 , message.getDefaultUint32 ());
- Assert.assertEquals(404 , message.getDefaultUint64 ());
- Assert.assertEquals(405 , message.getDefaultSint32 ());
- Assert.assertEquals(406 , message.getDefaultSint64 ());
- Assert.assertEquals(407 , message.getDefaultFixed32 ());
- Assert.assertEquals(408 , message.getDefaultFixed64 ());
- Assert.assertEquals(409 , message.getDefaultSfixed32());
- Assert.assertEquals(410 , message.getDefaultSfixed64());
- Assert.assertEquals(411 , message.getDefaultFloat (), 0.0);
- Assert.assertEquals(412 , message.getDefaultDouble (), 0.0);
- Assert.assertEquals(false, message.getDefaultBool ());
- Assert.assertEquals("415", message.getDefaultString ());
+ Assert.assertEquals(401, message.getDefaultInt32());
+ Assert.assertEquals(402, message.getDefaultInt64());
+ Assert.assertEquals(403, message.getDefaultUint32());
+ Assert.assertEquals(404, message.getDefaultUint64());
+ Assert.assertEquals(405, message.getDefaultSint32());
+ Assert.assertEquals(406, message.getDefaultSint64());
+ Assert.assertEquals(407, message.getDefaultFixed32());
+ Assert.assertEquals(408, message.getDefaultFixed64());
+ Assert.assertEquals(409, message.getDefaultSfixed32());
+ Assert.assertEquals(410, message.getDefaultSfixed64());
+ Assert.assertEquals(411, message.getDefaultFloat(), 0.0);
+ Assert.assertEquals(412, message.getDefaultDouble(), 0.0);
+ Assert.assertEquals(false, message.getDefaultBool());
+ Assert.assertEquals("415", message.getDefaultString());
Assert.assertEquals(toBytes("416"), message.getDefaultBytes());
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getDefaultNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getDefaultForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getDefaultImportEnum());
@@ -721,74 +692,73 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are cleared, and that getting the fields returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared,
+ * and that getting the fields returns their default values.
*/
public static void assertClear(TestAllTypesOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasOptionalInt32 ());
- Assert.assertFalse(message.hasOptionalInt64 ());
- Assert.assertFalse(message.hasOptionalUint32 ());
- Assert.assertFalse(message.hasOptionalUint64 ());
- Assert.assertFalse(message.hasOptionalSint32 ());
- Assert.assertFalse(message.hasOptionalSint64 ());
- Assert.assertFalse(message.hasOptionalFixed32 ());
- Assert.assertFalse(message.hasOptionalFixed64 ());
+ Assert.assertFalse(message.hasOptionalInt32());
+ Assert.assertFalse(message.hasOptionalInt64());
+ Assert.assertFalse(message.hasOptionalUint32());
+ Assert.assertFalse(message.hasOptionalUint64());
+ Assert.assertFalse(message.hasOptionalSint32());
+ Assert.assertFalse(message.hasOptionalSint64());
+ Assert.assertFalse(message.hasOptionalFixed32());
+ Assert.assertFalse(message.hasOptionalFixed64());
Assert.assertFalse(message.hasOptionalSfixed32());
Assert.assertFalse(message.hasOptionalSfixed64());
- Assert.assertFalse(message.hasOptionalFloat ());
- Assert.assertFalse(message.hasOptionalDouble ());
- Assert.assertFalse(message.hasOptionalBool ());
- Assert.assertFalse(message.hasOptionalString ());
- Assert.assertFalse(message.hasOptionalBytes ());
-
- Assert.assertFalse(message.hasOptionalGroup ());
- Assert.assertFalse(message.hasOptionalNestedMessage ());
+ Assert.assertFalse(message.hasOptionalFloat());
+ Assert.assertFalse(message.hasOptionalDouble());
+ Assert.assertFalse(message.hasOptionalBool());
+ Assert.assertFalse(message.hasOptionalString());
+ Assert.assertFalse(message.hasOptionalBytes());
+
+ Assert.assertFalse(message.hasOptionalGroup());
+ Assert.assertFalse(message.hasOptionalNestedMessage());
Assert.assertFalse(message.hasOptionalForeignMessage());
- Assert.assertFalse(message.hasOptionalImportMessage ());
+ Assert.assertFalse(message.hasOptionalImportMessage());
- Assert.assertFalse(message.hasOptionalNestedEnum ());
+ Assert.assertFalse(message.hasOptionalNestedEnum());
Assert.assertFalse(message.hasOptionalForeignEnum());
- Assert.assertFalse(message.hasOptionalImportEnum ());
+ Assert.assertFalse(message.hasOptionalImportEnum());
Assert.assertFalse(message.hasOptionalStringPiece());
Assert.assertFalse(message.hasOptionalCord());
// Optional fields without defaults are set to zero or something like it.
- Assert.assertEquals(0 , message.getOptionalInt32 ());
- Assert.assertEquals(0 , message.getOptionalInt64 ());
- Assert.assertEquals(0 , message.getOptionalUint32 ());
- Assert.assertEquals(0 , message.getOptionalUint64 ());
- Assert.assertEquals(0 , message.getOptionalSint32 ());
- Assert.assertEquals(0 , message.getOptionalSint64 ());
- Assert.assertEquals(0 , message.getOptionalFixed32 ());
- Assert.assertEquals(0 , message.getOptionalFixed64 ());
- Assert.assertEquals(0 , message.getOptionalSfixed32());
- Assert.assertEquals(0 , message.getOptionalSfixed64());
- Assert.assertEquals(0 , message.getOptionalFloat (), 0.0);
- Assert.assertEquals(0 , message.getOptionalDouble (), 0.0);
- Assert.assertEquals(false, message.getOptionalBool ());
- Assert.assertEquals("" , message.getOptionalString ());
+ Assert.assertEquals(0, message.getOptionalInt32());
+ Assert.assertEquals(0, message.getOptionalInt64());
+ Assert.assertEquals(0, message.getOptionalUint32());
+ Assert.assertEquals(0, message.getOptionalUint64());
+ Assert.assertEquals(0, message.getOptionalSint32());
+ Assert.assertEquals(0, message.getOptionalSint64());
+ Assert.assertEquals(0, message.getOptionalFixed32());
+ Assert.assertEquals(0, message.getOptionalFixed64());
+ Assert.assertEquals(0, message.getOptionalSfixed32());
+ Assert.assertEquals(0, message.getOptionalSfixed64());
+ Assert.assertEquals(0, message.getOptionalFloat(), 0.0);
+ Assert.assertEquals(0, message.getOptionalDouble(), 0.0);
+ Assert.assertEquals(false, message.getOptionalBool());
+ Assert.assertEquals("", message.getOptionalString());
Assert.assertEquals(ByteString.EMPTY, message.getOptionalBytes());
// Embedded messages should also be clear.
- Assert.assertFalse(message.getOptionalGroup ().hasA());
- Assert.assertFalse(message.getOptionalNestedMessage ().hasBb());
- Assert.assertFalse(message.getOptionalForeignMessage ().hasC());
- Assert.assertFalse(message.getOptionalImportMessage ().hasD());
+ Assert.assertFalse(message.getOptionalGroup().hasA());
+ Assert.assertFalse(message.getOptionalNestedMessage().hasBb());
+ Assert.assertFalse(message.getOptionalForeignMessage().hasC());
+ Assert.assertFalse(message.getOptionalImportMessage().hasD());
Assert.assertFalse(message.getOptionalPublicImportMessage().hasE());
- Assert.assertFalse(message.getOptionalLazyMessage ().hasBb());
+ Assert.assertFalse(message.getOptionalLazyMessage().hasBb());
- Assert.assertEquals(0, message.getOptionalGroup ().getA());
- Assert.assertEquals(0, message.getOptionalNestedMessage ().getBb());
- Assert.assertEquals(0, message.getOptionalForeignMessage ().getC());
- Assert.assertEquals(0, message.getOptionalImportMessage ().getD());
+ Assert.assertEquals(0, message.getOptionalGroup().getA());
+ Assert.assertEquals(0, message.getOptionalNestedMessage().getBb());
+ Assert.assertEquals(0, message.getOptionalForeignMessage().getC());
+ Assert.assertEquals(0, message.getOptionalImportMessage().getD());
Assert.assertEquals(0, message.getOptionalPublicImportMessage().getE());
- Assert.assertEquals(0, message.getOptionalLazyMessage ().getBb());
+ Assert.assertEquals(0, message.getOptionalLazyMessage().getBb());
// Enums without defaults are set to the first value in the enum.
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getOptionalNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getOptionalForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getOptionalImportEnum());
@@ -796,76 +766,76 @@ public final class TestUtil {
Assert.assertEquals("", message.getOptionalCord());
// Repeated fields are empty.
- Assert.assertEquals(0, message.getRepeatedInt32Count ());
- Assert.assertEquals(0, message.getRepeatedInt64Count ());
- Assert.assertEquals(0, message.getRepeatedUint32Count ());
- Assert.assertEquals(0, message.getRepeatedUint64Count ());
- Assert.assertEquals(0, message.getRepeatedSint32Count ());
- Assert.assertEquals(0, message.getRepeatedSint64Count ());
- Assert.assertEquals(0, message.getRepeatedFixed32Count ());
- Assert.assertEquals(0, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(0, message.getRepeatedInt32Count());
+ Assert.assertEquals(0, message.getRepeatedInt64Count());
+ Assert.assertEquals(0, message.getRepeatedUint32Count());
+ Assert.assertEquals(0, message.getRepeatedUint64Count());
+ Assert.assertEquals(0, message.getRepeatedSint32Count());
+ Assert.assertEquals(0, message.getRepeatedSint64Count());
+ Assert.assertEquals(0, message.getRepeatedFixed32Count());
+ Assert.assertEquals(0, message.getRepeatedFixed64Count());
Assert.assertEquals(0, message.getRepeatedSfixed32Count());
Assert.assertEquals(0, message.getRepeatedSfixed64Count());
- Assert.assertEquals(0, message.getRepeatedFloatCount ());
- Assert.assertEquals(0, message.getRepeatedDoubleCount ());
- Assert.assertEquals(0, message.getRepeatedBoolCount ());
- Assert.assertEquals(0, message.getRepeatedStringCount ());
- Assert.assertEquals(0, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(0, message.getRepeatedGroupCount ());
- Assert.assertEquals(0, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(0, message.getRepeatedFloatCount());
+ Assert.assertEquals(0, message.getRepeatedDoubleCount());
+ Assert.assertEquals(0, message.getRepeatedBoolCount());
+ Assert.assertEquals(0, message.getRepeatedStringCount());
+ Assert.assertEquals(0, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(0, message.getRepeatedGroupCount());
+ Assert.assertEquals(0, message.getRepeatedNestedMessageCount());
Assert.assertEquals(0, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(0, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(0, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(0, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(0, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(0, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(0, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(0, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(0, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(0, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(0, message.getRepeatedImportEnumCount());
Assert.assertEquals(0, message.getRepeatedStringPieceCount());
Assert.assertEquals(0, message.getRepeatedCordCount());
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasDefaultInt32 ());
- Assert.assertFalse(message.hasDefaultInt64 ());
- Assert.assertFalse(message.hasDefaultUint32 ());
- Assert.assertFalse(message.hasDefaultUint64 ());
- Assert.assertFalse(message.hasDefaultSint32 ());
- Assert.assertFalse(message.hasDefaultSint64 ());
- Assert.assertFalse(message.hasDefaultFixed32 ());
- Assert.assertFalse(message.hasDefaultFixed64 ());
+ Assert.assertFalse(message.hasDefaultInt32());
+ Assert.assertFalse(message.hasDefaultInt64());
+ Assert.assertFalse(message.hasDefaultUint32());
+ Assert.assertFalse(message.hasDefaultUint64());
+ Assert.assertFalse(message.hasDefaultSint32());
+ Assert.assertFalse(message.hasDefaultSint64());
+ Assert.assertFalse(message.hasDefaultFixed32());
+ Assert.assertFalse(message.hasDefaultFixed64());
Assert.assertFalse(message.hasDefaultSfixed32());
Assert.assertFalse(message.hasDefaultSfixed64());
- Assert.assertFalse(message.hasDefaultFloat ());
- Assert.assertFalse(message.hasDefaultDouble ());
- Assert.assertFalse(message.hasDefaultBool ());
- Assert.assertFalse(message.hasDefaultString ());
- Assert.assertFalse(message.hasDefaultBytes ());
+ Assert.assertFalse(message.hasDefaultFloat());
+ Assert.assertFalse(message.hasDefaultDouble());
+ Assert.assertFalse(message.hasDefaultBool());
+ Assert.assertFalse(message.hasDefaultString());
+ Assert.assertFalse(message.hasDefaultBytes());
- Assert.assertFalse(message.hasDefaultNestedEnum ());
+ Assert.assertFalse(message.hasDefaultNestedEnum());
Assert.assertFalse(message.hasDefaultForeignEnum());
- Assert.assertFalse(message.hasDefaultImportEnum ());
+ Assert.assertFalse(message.hasDefaultImportEnum());
Assert.assertFalse(message.hasDefaultStringPiece());
Assert.assertFalse(message.hasDefaultCord());
// Fields with defaults have their default values (duh).
- Assert.assertEquals( 41 , message.getDefaultInt32 ());
- Assert.assertEquals( 42 , message.getDefaultInt64 ());
- Assert.assertEquals( 43 , message.getDefaultUint32 ());
- Assert.assertEquals( 44 , message.getDefaultUint64 ());
- Assert.assertEquals(-45 , message.getDefaultSint32 ());
- Assert.assertEquals( 46 , message.getDefaultSint64 ());
- Assert.assertEquals( 47 , message.getDefaultFixed32 ());
- Assert.assertEquals( 48 , message.getDefaultFixed64 ());
- Assert.assertEquals( 49 , message.getDefaultSfixed32());
- Assert.assertEquals(-50 , message.getDefaultSfixed64());
- Assert.assertEquals( 51.5 , message.getDefaultFloat (), 0.0);
- Assert.assertEquals( 52e3 , message.getDefaultDouble (), 0.0);
- Assert.assertEquals(true , message.getDefaultBool ());
- Assert.assertEquals("hello", message.getDefaultString ());
+ Assert.assertEquals(41, message.getDefaultInt32());
+ Assert.assertEquals(42, message.getDefaultInt64());
+ Assert.assertEquals(43, message.getDefaultUint32());
+ Assert.assertEquals(44, message.getDefaultUint64());
+ Assert.assertEquals(-45, message.getDefaultSint32());
+ Assert.assertEquals(46, message.getDefaultSint64());
+ Assert.assertEquals(47, message.getDefaultFixed32());
+ Assert.assertEquals(48, message.getDefaultFixed64());
+ Assert.assertEquals(49, message.getDefaultSfixed32());
+ Assert.assertEquals(-50, message.getDefaultSfixed64());
+ Assert.assertEquals(51.5, message.getDefaultFloat(), 0.0);
+ Assert.assertEquals(52e3, message.getDefaultDouble(), 0.0);
+ Assert.assertEquals(true, message.getDefaultBool());
+ Assert.assertEquals("hello", message.getDefaultString());
Assert.assertEquals(toBytes("world"), message.getDefaultBytes());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum ());
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getDefaultNestedEnum());
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getDefaultForeignEnum());
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getDefaultImportEnum());
@@ -881,66 +851,64 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields}
- * followed by {@code modifyRepeatedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setAllFields} followed by {@code modifyRepeatedFields}.
*/
- public static void assertRepeatedFieldsModified(
- TestAllTypesOrBuilder message) {
+ public static void assertRepeatedFieldsModified(TestAllTypesOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getRepeatedInt32Count ());
- Assert.assertEquals(2, message.getRepeatedInt64Count ());
- Assert.assertEquals(2, message.getRepeatedUint32Count ());
- Assert.assertEquals(2, message.getRepeatedUint64Count ());
- Assert.assertEquals(2, message.getRepeatedSint32Count ());
- Assert.assertEquals(2, message.getRepeatedSint64Count ());
- Assert.assertEquals(2, message.getRepeatedFixed32Count ());
- Assert.assertEquals(2, message.getRepeatedFixed64Count ());
+ Assert.assertEquals(2, message.getRepeatedInt32Count());
+ Assert.assertEquals(2, message.getRepeatedInt64Count());
+ Assert.assertEquals(2, message.getRepeatedUint32Count());
+ Assert.assertEquals(2, message.getRepeatedUint64Count());
+ Assert.assertEquals(2, message.getRepeatedSint32Count());
+ Assert.assertEquals(2, message.getRepeatedSint64Count());
+ Assert.assertEquals(2, message.getRepeatedFixed32Count());
+ Assert.assertEquals(2, message.getRepeatedFixed64Count());
Assert.assertEquals(2, message.getRepeatedSfixed32Count());
Assert.assertEquals(2, message.getRepeatedSfixed64Count());
- Assert.assertEquals(2, message.getRepeatedFloatCount ());
- Assert.assertEquals(2, message.getRepeatedDoubleCount ());
- Assert.assertEquals(2, message.getRepeatedBoolCount ());
- Assert.assertEquals(2, message.getRepeatedStringCount ());
- Assert.assertEquals(2, message.getRepeatedBytesCount ());
-
- Assert.assertEquals(2, message.getRepeatedGroupCount ());
- Assert.assertEquals(2, message.getRepeatedNestedMessageCount ());
+ Assert.assertEquals(2, message.getRepeatedFloatCount());
+ Assert.assertEquals(2, message.getRepeatedDoubleCount());
+ Assert.assertEquals(2, message.getRepeatedBoolCount());
+ Assert.assertEquals(2, message.getRepeatedStringCount());
+ Assert.assertEquals(2, message.getRepeatedBytesCount());
+
+ Assert.assertEquals(2, message.getRepeatedGroupCount());
+ Assert.assertEquals(2, message.getRepeatedNestedMessageCount());
Assert.assertEquals(2, message.getRepeatedForeignMessageCount());
- Assert.assertEquals(2, message.getRepeatedImportMessageCount ());
- Assert.assertEquals(2, message.getRepeatedLazyMessageCount ());
- Assert.assertEquals(2, message.getRepeatedNestedEnumCount ());
- Assert.assertEquals(2, message.getRepeatedForeignEnumCount ());
- Assert.assertEquals(2, message.getRepeatedImportEnumCount ());
+ Assert.assertEquals(2, message.getRepeatedImportMessageCount());
+ Assert.assertEquals(2, message.getRepeatedLazyMessageCount());
+ Assert.assertEquals(2, message.getRepeatedNestedEnumCount());
+ Assert.assertEquals(2, message.getRepeatedForeignEnumCount());
+ Assert.assertEquals(2, message.getRepeatedImportEnumCount());
Assert.assertEquals(2, message.getRepeatedStringPieceCount());
Assert.assertEquals(2, message.getRepeatedCordCount());
- Assert.assertEquals(201 , message.getRepeatedInt32 (0));
- Assert.assertEquals(202L , message.getRepeatedInt64 (0));
- Assert.assertEquals(203 , message.getRepeatedUint32 (0));
- Assert.assertEquals(204L , message.getRepeatedUint64 (0));
- Assert.assertEquals(205 , message.getRepeatedSint32 (0));
- Assert.assertEquals(206L , message.getRepeatedSint64 (0));
- Assert.assertEquals(207 , message.getRepeatedFixed32 (0));
- Assert.assertEquals(208L , message.getRepeatedFixed64 (0));
- Assert.assertEquals(209 , message.getRepeatedSfixed32(0));
- Assert.assertEquals(210L , message.getRepeatedSfixed64(0));
- Assert.assertEquals(211F , message.getRepeatedFloat (0));
- Assert.assertEquals(212D , message.getRepeatedDouble (0));
- Assert.assertEquals(true , message.getRepeatedBool (0));
- Assert.assertEquals("215", message.getRepeatedString (0));
+ Assert.assertEquals(201, message.getRepeatedInt32(0));
+ Assert.assertEquals(202L, message.getRepeatedInt64(0));
+ Assert.assertEquals(203, message.getRepeatedUint32(0));
+ Assert.assertEquals(204L, message.getRepeatedUint64(0));
+ Assert.assertEquals(205, message.getRepeatedSint32(0));
+ Assert.assertEquals(206L, message.getRepeatedSint64(0));
+ Assert.assertEquals(207, message.getRepeatedFixed32(0));
+ Assert.assertEquals(208L, message.getRepeatedFixed64(0));
+ Assert.assertEquals(209, message.getRepeatedSfixed32(0));
+ Assert.assertEquals(210L, message.getRepeatedSfixed64(0));
+ Assert.assertEquals(211F, message.getRepeatedFloat(0));
+ Assert.assertEquals(212D, message.getRepeatedDouble(0));
+ Assert.assertEquals(true, message.getRepeatedBool(0));
+ Assert.assertEquals("215", message.getRepeatedString(0));
Assert.assertEquals(toBytes("216"), message.getRepeatedBytes(0));
- Assert.assertEquals(217, message.getRepeatedGroup (0).getA());
- Assert.assertEquals(218, message.getRepeatedNestedMessage (0).getBb());
+ Assert.assertEquals(217, message.getRepeatedGroup(0).getA());
+ Assert.assertEquals(218, message.getRepeatedNestedMessage(0).getBb());
Assert.assertEquals(219, message.getRepeatedForeignMessage(0).getC());
- Assert.assertEquals(220, message.getRepeatedImportMessage (0).getD());
- Assert.assertEquals(227, message.getRepeatedLazyMessage (0).getBb());
+ Assert.assertEquals(220, message.getRepeatedImportMessage(0).getD());
+ Assert.assertEquals(227, message.getRepeatedLazyMessage(0).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum (0));
+ Assert.assertEquals(TestAllTypes.NestedEnum.BAR, message.getRepeatedNestedEnum(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getRepeatedForeignEnum(0));
Assert.assertEquals(ImportEnum.IMPORT_BAR, message.getRepeatedImportEnum(0));
@@ -948,29 +916,29 @@ public final class TestUtil {
Assert.assertEquals("225", message.getRepeatedCord(0));
// Actually verify the second (modified) elements now.
- Assert.assertEquals(501 , message.getRepeatedInt32 (1));
- Assert.assertEquals(502L , message.getRepeatedInt64 (1));
- Assert.assertEquals(503 , message.getRepeatedUint32 (1));
- Assert.assertEquals(504L , message.getRepeatedUint64 (1));
- Assert.assertEquals(505 , message.getRepeatedSint32 (1));
- Assert.assertEquals(506L , message.getRepeatedSint64 (1));
- Assert.assertEquals(507 , message.getRepeatedFixed32 (1));
- Assert.assertEquals(508L , message.getRepeatedFixed64 (1));
- Assert.assertEquals(509 , message.getRepeatedSfixed32(1));
- Assert.assertEquals(510L , message.getRepeatedSfixed64(1));
- Assert.assertEquals(511F , message.getRepeatedFloat (1));
- Assert.assertEquals(512D , message.getRepeatedDouble (1));
- Assert.assertEquals(true , message.getRepeatedBool (1));
- Assert.assertEquals("515", message.getRepeatedString (1));
+ Assert.assertEquals(501, message.getRepeatedInt32(1));
+ Assert.assertEquals(502L, message.getRepeatedInt64(1));
+ Assert.assertEquals(503, message.getRepeatedUint32(1));
+ Assert.assertEquals(504L, message.getRepeatedUint64(1));
+ Assert.assertEquals(505, message.getRepeatedSint32(1));
+ Assert.assertEquals(506L, message.getRepeatedSint64(1));
+ Assert.assertEquals(507, message.getRepeatedFixed32(1));
+ Assert.assertEquals(508L, message.getRepeatedFixed64(1));
+ Assert.assertEquals(509, message.getRepeatedSfixed32(1));
+ Assert.assertEquals(510L, message.getRepeatedSfixed64(1));
+ Assert.assertEquals(511F, message.getRepeatedFloat(1));
+ Assert.assertEquals(512D, message.getRepeatedDouble(1));
+ Assert.assertEquals(true, message.getRepeatedBool(1));
+ Assert.assertEquals("515", message.getRepeatedString(1));
Assert.assertEquals(toBytes("516"), message.getRepeatedBytes(1));
- Assert.assertEquals(517, message.getRepeatedGroup (1).getA());
- Assert.assertEquals(518, message.getRepeatedNestedMessage (1).getBb());
+ Assert.assertEquals(517, message.getRepeatedGroup(1).getA());
+ Assert.assertEquals(518, message.getRepeatedNestedMessage(1).getBb());
Assert.assertEquals(519, message.getRepeatedForeignMessage(1).getC());
- Assert.assertEquals(520, message.getRepeatedImportMessage (1).getD());
- Assert.assertEquals(527, message.getRepeatedLazyMessage (1).getBb());
+ Assert.assertEquals(520, message.getRepeatedImportMessage(1).getD());
+ Assert.assertEquals(527, message.getRepeatedLazyMessage(1).getBb());
- Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum (1));
+ Assert.assertEquals(TestAllTypes.NestedEnum.FOO, message.getRepeatedNestedEnum(1));
Assert.assertEquals(ForeignEnum.FOREIGN_FOO, message.getRepeatedForeignEnum(1));
Assert.assertEquals(ImportEnum.IMPORT_FOO, message.getRepeatedImportEnum(1));
@@ -978,172 +946,170 @@ public final class TestUtil {
Assert.assertEquals("525", message.getRepeatedCord(1));
}
- /**
- * Set every field of {@code message} to a unique value.
- */
+ /** Set every field of {@code message} to a unique value. */
public static void setPackedFields(TestPackedTypes.Builder message) {
- message.addPackedInt32 (601);
- message.addPackedInt64 (602);
- message.addPackedUint32 (603);
- message.addPackedUint64 (604);
- message.addPackedSint32 (605);
- message.addPackedSint64 (606);
- message.addPackedFixed32 (607);
- message.addPackedFixed64 (608);
+ message.addPackedInt32(601);
+ message.addPackedInt64(602);
+ message.addPackedUint32(603);
+ message.addPackedUint64(604);
+ message.addPackedSint32(605);
+ message.addPackedSint64(606);
+ message.addPackedFixed32(607);
+ message.addPackedFixed64(608);
message.addPackedSfixed32(609);
message.addPackedSfixed64(610);
- message.addPackedFloat (611);
- message.addPackedDouble (612);
- message.addPackedBool (true);
- message.addPackedEnum (ForeignEnum.FOREIGN_BAR);
+ message.addPackedFloat(611);
+ message.addPackedDouble(612);
+ message.addPackedBool(true);
+ message.addPackedEnum(ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addPackedInt32 (701);
- message.addPackedInt64 (702);
- message.addPackedUint32 (703);
- message.addPackedUint64 (704);
- message.addPackedSint32 (705);
- message.addPackedSint64 (706);
- message.addPackedFixed32 (707);
- message.addPackedFixed64 (708);
+ message.addPackedInt32(701);
+ message.addPackedInt64(702);
+ message.addPackedUint32(703);
+ message.addPackedUint64(704);
+ message.addPackedSint32(705);
+ message.addPackedSint64(706);
+ message.addPackedFixed32(707);
+ message.addPackedFixed64(708);
message.addPackedSfixed32(709);
message.addPackedSfixed64(710);
- message.addPackedFloat (711);
- message.addPackedDouble (712);
- message.addPackedBool (false);
- message.addPackedEnum (ForeignEnum.FOREIGN_BAZ);
+ message.addPackedFloat(711);
+ message.addPackedDouble(712);
+ message.addPackedBool(false);
+ message.addPackedEnum(ForeignEnum.FOREIGN_BAZ);
}
/**
- * Set every field of {@code message} to a unique value. Must correspond with
- * the values applied by {@code setPackedFields}.
+ * Set every field of {@code message} to a unique value. Must correspond with the values applied
+ * by {@code setPackedFields}.
*/
public static void setUnpackedFields(TestUnpackedTypes.Builder message) {
- message.addUnpackedInt32 (601);
- message.addUnpackedInt64 (602);
- message.addUnpackedUint32 (603);
- message.addUnpackedUint64 (604);
- message.addUnpackedSint32 (605);
- message.addUnpackedSint64 (606);
- message.addUnpackedFixed32 (607);
- message.addUnpackedFixed64 (608);
+ message.addUnpackedInt32(601);
+ message.addUnpackedInt64(602);
+ message.addUnpackedUint32(603);
+ message.addUnpackedUint64(604);
+ message.addUnpackedSint32(605);
+ message.addUnpackedSint64(606);
+ message.addUnpackedFixed32(607);
+ message.addUnpackedFixed64(608);
message.addUnpackedSfixed32(609);
message.addUnpackedSfixed64(610);
- message.addUnpackedFloat (611);
- message.addUnpackedDouble (612);
- message.addUnpackedBool (true);
- message.addUnpackedEnum (ForeignEnum.FOREIGN_BAR);
+ message.addUnpackedFloat(611);
+ message.addUnpackedDouble(612);
+ message.addUnpackedBool(true);
+ message.addUnpackedEnum(ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addUnpackedInt32 (701);
- message.addUnpackedInt64 (702);
- message.addUnpackedUint32 (703);
- message.addUnpackedUint64 (704);
- message.addUnpackedSint32 (705);
- message.addUnpackedSint64 (706);
- message.addUnpackedFixed32 (707);
- message.addUnpackedFixed64 (708);
+ message.addUnpackedInt32(701);
+ message.addUnpackedInt64(702);
+ message.addUnpackedUint32(703);
+ message.addUnpackedUint64(704);
+ message.addUnpackedSint32(705);
+ message.addUnpackedSint64(706);
+ message.addUnpackedFixed32(707);
+ message.addUnpackedFixed64(708);
message.addUnpackedSfixed32(709);
message.addUnpackedSfixed64(710);
- message.addUnpackedFloat (711);
- message.addUnpackedDouble (712);
- message.addUnpackedBool (false);
- message.addUnpackedEnum (ForeignEnum.FOREIGN_BAZ);
+ message.addUnpackedFloat(711);
+ message.addUnpackedDouble(712);
+ message.addUnpackedBool(false);
+ message.addUnpackedEnum(ForeignEnum.FOREIGN_BAZ);
}
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setPackedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setPackedFields}.
*/
public static void assertPackedFieldsSet(TestPackedTypes message) {
- Assert.assertEquals(2, message.getPackedInt32Count ());
- Assert.assertEquals(2, message.getPackedInt64Count ());
- Assert.assertEquals(2, message.getPackedUint32Count ());
- Assert.assertEquals(2, message.getPackedUint64Count ());
- Assert.assertEquals(2, message.getPackedSint32Count ());
- Assert.assertEquals(2, message.getPackedSint64Count ());
- Assert.assertEquals(2, message.getPackedFixed32Count ());
- Assert.assertEquals(2, message.getPackedFixed64Count ());
+ Assert.assertEquals(2, message.getPackedInt32Count());
+ Assert.assertEquals(2, message.getPackedInt64Count());
+ Assert.assertEquals(2, message.getPackedUint32Count());
+ Assert.assertEquals(2, message.getPackedUint64Count());
+ Assert.assertEquals(2, message.getPackedSint32Count());
+ Assert.assertEquals(2, message.getPackedSint64Count());
+ Assert.assertEquals(2, message.getPackedFixed32Count());
+ Assert.assertEquals(2, message.getPackedFixed64Count());
Assert.assertEquals(2, message.getPackedSfixed32Count());
Assert.assertEquals(2, message.getPackedSfixed64Count());
- Assert.assertEquals(2, message.getPackedFloatCount ());
- Assert.assertEquals(2, message.getPackedDoubleCount ());
- Assert.assertEquals(2, message.getPackedBoolCount ());
- Assert.assertEquals(2, message.getPackedEnumCount ());
- Assert.assertEquals(601 , message.getPackedInt32 (0));
- Assert.assertEquals(602 , message.getPackedInt64 (0));
- Assert.assertEquals(603 , message.getPackedUint32 (0));
- Assert.assertEquals(604 , message.getPackedUint64 (0));
- Assert.assertEquals(605 , message.getPackedSint32 (0));
- Assert.assertEquals(606 , message.getPackedSint64 (0));
- Assert.assertEquals(607 , message.getPackedFixed32 (0));
- Assert.assertEquals(608 , message.getPackedFixed64 (0));
- Assert.assertEquals(609 , message.getPackedSfixed32(0));
- Assert.assertEquals(610 , message.getPackedSfixed64(0));
- Assert.assertEquals(611 , message.getPackedFloat (0), 0.0);
- Assert.assertEquals(612 , message.getPackedDouble (0), 0.0);
- Assert.assertEquals(true , message.getPackedBool (0));
+ Assert.assertEquals(2, message.getPackedFloatCount());
+ Assert.assertEquals(2, message.getPackedDoubleCount());
+ Assert.assertEquals(2, message.getPackedBoolCount());
+ Assert.assertEquals(2, message.getPackedEnumCount());
+ Assert.assertEquals(601, message.getPackedInt32(0));
+ Assert.assertEquals(602, message.getPackedInt64(0));
+ Assert.assertEquals(603, message.getPackedUint32(0));
+ Assert.assertEquals(604, message.getPackedUint64(0));
+ Assert.assertEquals(605, message.getPackedSint32(0));
+ Assert.assertEquals(606, message.getPackedSint64(0));
+ Assert.assertEquals(607, message.getPackedFixed32(0));
+ Assert.assertEquals(608, message.getPackedFixed64(0));
+ Assert.assertEquals(609, message.getPackedSfixed32(0));
+ Assert.assertEquals(610, message.getPackedSfixed64(0));
+ Assert.assertEquals(611, message.getPackedFloat(0), 0.0);
+ Assert.assertEquals(612, message.getPackedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getPackedBool(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getPackedEnum(0));
- Assert.assertEquals(701 , message.getPackedInt32 (1));
- Assert.assertEquals(702 , message.getPackedInt64 (1));
- Assert.assertEquals(703 , message.getPackedUint32 (1));
- Assert.assertEquals(704 , message.getPackedUint64 (1));
- Assert.assertEquals(705 , message.getPackedSint32 (1));
- Assert.assertEquals(706 , message.getPackedSint64 (1));
- Assert.assertEquals(707 , message.getPackedFixed32 (1));
- Assert.assertEquals(708 , message.getPackedFixed64 (1));
- Assert.assertEquals(709 , message.getPackedSfixed32(1));
- Assert.assertEquals(710 , message.getPackedSfixed64(1));
- Assert.assertEquals(711 , message.getPackedFloat (1), 0.0);
- Assert.assertEquals(712 , message.getPackedDouble (1), 0.0);
- Assert.assertEquals(false, message.getPackedBool (1));
+ Assert.assertEquals(701, message.getPackedInt32(1));
+ Assert.assertEquals(702, message.getPackedInt64(1));
+ Assert.assertEquals(703, message.getPackedUint32(1));
+ Assert.assertEquals(704, message.getPackedUint64(1));
+ Assert.assertEquals(705, message.getPackedSint32(1));
+ Assert.assertEquals(706, message.getPackedSint64(1));
+ Assert.assertEquals(707, message.getPackedFixed32(1));
+ Assert.assertEquals(708, message.getPackedFixed64(1));
+ Assert.assertEquals(709, message.getPackedSfixed32(1));
+ Assert.assertEquals(710, message.getPackedSfixed64(1));
+ Assert.assertEquals(711, message.getPackedFloat(1), 0.0);
+ Assert.assertEquals(712, message.getPackedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getPackedBool(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getPackedEnum(1));
}
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setUnpackedFields}.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to the
+ * values assigned by {@code setUnpackedFields}.
*/
public static void assertUnpackedFieldsSet(TestUnpackedTypes message) {
- Assert.assertEquals(2, message.getUnpackedInt32Count ());
- Assert.assertEquals(2, message.getUnpackedInt64Count ());
- Assert.assertEquals(2, message.getUnpackedUint32Count ());
- Assert.assertEquals(2, message.getUnpackedUint64Count ());
- Assert.assertEquals(2, message.getUnpackedSint32Count ());
- Assert.assertEquals(2, message.getUnpackedSint64Count ());
- Assert.assertEquals(2, message.getUnpackedFixed32Count ());
- Assert.assertEquals(2, message.getUnpackedFixed64Count ());
+ Assert.assertEquals(2, message.getUnpackedInt32Count());
+ Assert.assertEquals(2, message.getUnpackedInt64Count());
+ Assert.assertEquals(2, message.getUnpackedUint32Count());
+ Assert.assertEquals(2, message.getUnpackedUint64Count());
+ Assert.assertEquals(2, message.getUnpackedSint32Count());
+ Assert.assertEquals(2, message.getUnpackedSint64Count());
+ Assert.assertEquals(2, message.getUnpackedFixed32Count());
+ Assert.assertEquals(2, message.getUnpackedFixed64Count());
Assert.assertEquals(2, message.getUnpackedSfixed32Count());
Assert.assertEquals(2, message.getUnpackedSfixed64Count());
- Assert.assertEquals(2, message.getUnpackedFloatCount ());
- Assert.assertEquals(2, message.getUnpackedDoubleCount ());
- Assert.assertEquals(2, message.getUnpackedBoolCount ());
- Assert.assertEquals(2, message.getUnpackedEnumCount ());
- Assert.assertEquals(601 , message.getUnpackedInt32 (0));
- Assert.assertEquals(602 , message.getUnpackedInt64 (0));
- Assert.assertEquals(603 , message.getUnpackedUint32 (0));
- Assert.assertEquals(604 , message.getUnpackedUint64 (0));
- Assert.assertEquals(605 , message.getUnpackedSint32 (0));
- Assert.assertEquals(606 , message.getUnpackedSint64 (0));
- Assert.assertEquals(607 , message.getUnpackedFixed32 (0));
- Assert.assertEquals(608 , message.getUnpackedFixed64 (0));
- Assert.assertEquals(609 , message.getUnpackedSfixed32(0));
- Assert.assertEquals(610 , message.getUnpackedSfixed64(0));
- Assert.assertEquals(611 , message.getUnpackedFloat (0), 0.0);
- Assert.assertEquals(612 , message.getUnpackedDouble (0), 0.0);
- Assert.assertEquals(true , message.getUnpackedBool (0));
+ Assert.assertEquals(2, message.getUnpackedFloatCount());
+ Assert.assertEquals(2, message.getUnpackedDoubleCount());
+ Assert.assertEquals(2, message.getUnpackedBoolCount());
+ Assert.assertEquals(2, message.getUnpackedEnumCount());
+ Assert.assertEquals(601, message.getUnpackedInt32(0));
+ Assert.assertEquals(602, message.getUnpackedInt64(0));
+ Assert.assertEquals(603, message.getUnpackedUint32(0));
+ Assert.assertEquals(604, message.getUnpackedUint64(0));
+ Assert.assertEquals(605, message.getUnpackedSint32(0));
+ Assert.assertEquals(606, message.getUnpackedSint64(0));
+ Assert.assertEquals(607, message.getUnpackedFixed32(0));
+ Assert.assertEquals(608, message.getUnpackedFixed64(0));
+ Assert.assertEquals(609, message.getUnpackedSfixed32(0));
+ Assert.assertEquals(610, message.getUnpackedSfixed64(0));
+ Assert.assertEquals(611, message.getUnpackedFloat(0), 0.0);
+ Assert.assertEquals(612, message.getUnpackedDouble(0), 0.0);
+ Assert.assertEquals(true, message.getUnpackedBool(0));
Assert.assertEquals(ForeignEnum.FOREIGN_BAR, message.getUnpackedEnum(0));
- Assert.assertEquals(701 , message.getUnpackedInt32 (1));
- Assert.assertEquals(702 , message.getUnpackedInt64 (1));
- Assert.assertEquals(703 , message.getUnpackedUint32 (1));
- Assert.assertEquals(704 , message.getUnpackedUint64 (1));
- Assert.assertEquals(705 , message.getUnpackedSint32 (1));
- Assert.assertEquals(706 , message.getUnpackedSint64 (1));
- Assert.assertEquals(707 , message.getUnpackedFixed32 (1));
- Assert.assertEquals(708 , message.getUnpackedFixed64 (1));
- Assert.assertEquals(709 , message.getUnpackedSfixed32(1));
- Assert.assertEquals(710 , message.getUnpackedSfixed64(1));
- Assert.assertEquals(711 , message.getUnpackedFloat (1), 0.0);
- Assert.assertEquals(712 , message.getUnpackedDouble (1), 0.0);
- Assert.assertEquals(false, message.getUnpackedBool (1));
+ Assert.assertEquals(701, message.getUnpackedInt32(1));
+ Assert.assertEquals(702, message.getUnpackedInt64(1));
+ Assert.assertEquals(703, message.getUnpackedUint32(1));
+ Assert.assertEquals(704, message.getUnpackedUint64(1));
+ Assert.assertEquals(705, message.getUnpackedSint32(1));
+ Assert.assertEquals(706, message.getUnpackedSint64(1));
+ Assert.assertEquals(707, message.getUnpackedFixed32(1));
+ Assert.assertEquals(708, message.getUnpackedFixed64(1));
+ Assert.assertEquals(709, message.getUnpackedSfixed32(1));
+ Assert.assertEquals(710, message.getUnpackedSfixed64(1));
+ Assert.assertEquals(711, message.getUnpackedFloat(1), 0.0);
+ Assert.assertEquals(712, message.getUnpackedDouble(1), 0.0);
+ Assert.assertEquals(false, message.getUnpackedBool(1));
Assert.assertEquals(ForeignEnum.FOREIGN_BAZ, message.getUnpackedEnum(1));
}
@@ -1156,99 +1122,119 @@ public final class TestUtil {
private static void assertEqualsExactType(int a, int b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(long a, long b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(float a, float b) {
Assert.assertEquals(a, b, 0.0);
}
+
private static void assertEqualsExactType(double a, double b) {
Assert.assertEquals(a, b, 0.0);
}
+
private static void assertEqualsExactType(boolean a, boolean b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(String a, String b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ByteString a, ByteString b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(TestAllTypes.NestedEnum a,
- TestAllTypes.NestedEnum b) {
+
+ private static void assertEqualsExactType(TestAllTypes.NestedEnum a, TestAllTypes.NestedEnum b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ForeignEnum a, ForeignEnum b) {
Assert.assertEquals(a, b);
}
+
private static void assertEqualsExactType(ImportEnum a, ImportEnum b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(TestAllTypesLite.NestedEnum a,
- TestAllTypesLite.NestedEnum b) {
+
+ private static void assertEqualsExactType(
+ TestAllTypesLite.NestedEnum a, TestAllTypesLite.NestedEnum b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(ForeignEnumLite a,
- ForeignEnumLite b) {
+
+ private static void assertEqualsExactType(ForeignEnumLite a, ForeignEnumLite b) {
Assert.assertEquals(a, b);
}
- private static void assertEqualsExactType(ImportEnumLite a,
- ImportEnumLite b) {
+
+ private static void assertEqualsExactType(ImportEnumLite a, ImportEnumLite b) {
Assert.assertEquals(a, b);
}
/**
- * Get an unmodifiable {@link ExtensionRegistry} containing all the
- * extensions of {@code TestAllExtensions}.
+ * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code
+ * TestAllExtensions}.
+ */
+ public static ExtensionRegistryLite getExtensionRegistry() {
+ ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
+ registerAllExtensions(registry);
+ return registry.getUnmodifiable();
+ }
+
+ // BEGIN FULL-RUNTIME
+ /**
+ * Get an unmodifiable {@link ExtensionRegistry} containing all the extensions of {@code
+ * TestAllExtensions}.
*/
- public static ExtensionRegistry getExtensionRegistry() {
+ public static ExtensionRegistry getFullExtensionRegistry() {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
registerAllExtensions(registry);
return registry.getUnmodifiable();
}
+ // END FULL-RUNTIME
/**
- * Register all of {@code TestAllExtensions}'s extensions with the
- * given {@link ExtensionRegistry}.
+ * Register all of {@code TestAllExtensions}'s extensions with the given {@link
+ * ExtensionRegistry}.
*/
- public static void registerAllExtensions(ExtensionRegistry registry) {
+ public static void registerAllExtensions(ExtensionRegistryLite registry) {
UnittestProto.registerAllExtensions(registry);
TestUtilLite.registerAllExtensionsLite(registry);
}
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllExtensionsSet()}.
+ * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
*/
public static void setAllExtensions(TestAllExtensions.Builder message) {
- message.setExtension(optionalInt32Extension , 101);
- message.setExtension(optionalInt64Extension , 102L);
- message.setExtension(optionalUint32Extension , 103);
- message.setExtension(optionalUint64Extension , 104L);
- message.setExtension(optionalSint32Extension , 105);
- message.setExtension(optionalSint64Extension , 106L);
- message.setExtension(optionalFixed32Extension , 107);
- message.setExtension(optionalFixed64Extension , 108L);
+ message.setExtension(optionalInt32Extension, 101);
+ message.setExtension(optionalInt64Extension, 102L);
+ message.setExtension(optionalUint32Extension, 103);
+ message.setExtension(optionalUint64Extension, 104L);
+ message.setExtension(optionalSint32Extension, 105);
+ message.setExtension(optionalSint64Extension, 106L);
+ message.setExtension(optionalFixed32Extension, 107);
+ message.setExtension(optionalFixed64Extension, 108L);
message.setExtension(optionalSfixed32Extension, 109);
message.setExtension(optionalSfixed64Extension, 110L);
- message.setExtension(optionalFloatExtension , 111F);
- message.setExtension(optionalDoubleExtension , 112D);
- message.setExtension(optionalBoolExtension , true);
- message.setExtension(optionalStringExtension , "115");
- message.setExtension(optionalBytesExtension , toBytes("116"));
-
- message.setExtension(optionalGroupExtension,
- OptionalGroup_extension.newBuilder().setA(117).build());
- message.setExtension(optionalNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
- message.setExtension(optionalForeignMessageExtension,
- ForeignMessage.newBuilder().setC(119).build());
- message.setExtension(optionalImportMessageExtension,
- ImportMessage.newBuilder().setD(120).build());
- message.setExtension(optionalPublicImportMessageExtension,
- PublicImportMessage.newBuilder().setE(126).build());
- message.setExtension(optionalLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
+ message.setExtension(optionalFloatExtension, 111F);
+ message.setExtension(optionalDoubleExtension, 112D);
+ message.setExtension(optionalBoolExtension, true);
+ message.setExtension(optionalStringExtension, "115");
+ message.setExtension(optionalBytesExtension, toBytes("116"));
+
+ message.setExtension(
+ optionalGroupExtension, OptionalGroup_extension.newBuilder().setA(117).build());
+ message.setExtension(
+ optionalNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(118).build());
+ message.setExtension(
+ optionalForeignMessageExtension, ForeignMessage.newBuilder().setC(119).build());
+ message.setExtension(
+ optionalImportMessageExtension, ImportMessage.newBuilder().setD(120).build());
+ message.setExtension(
+ optionalPublicImportMessageExtension, PublicImportMessage.newBuilder().setE(126).build());
+ message.setExtension(
+ optionalLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(127).build());
message.setExtension(optionalNestedEnumExtension, TestAllTypes.NestedEnum.BAZ);
message.setExtension(optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
@@ -1259,32 +1245,32 @@ public final class TestUtil {
// -----------------------------------------------------------------
- message.addExtension(repeatedInt32Extension , 201);
- message.addExtension(repeatedInt64Extension , 202L);
- message.addExtension(repeatedUint32Extension , 203);
- message.addExtension(repeatedUint64Extension , 204L);
- message.addExtension(repeatedSint32Extension , 205);
- message.addExtension(repeatedSint64Extension , 206L);
- message.addExtension(repeatedFixed32Extension , 207);
- message.addExtension(repeatedFixed64Extension , 208L);
+ message.addExtension(repeatedInt32Extension, 201);
+ message.addExtension(repeatedInt64Extension, 202L);
+ message.addExtension(repeatedUint32Extension, 203);
+ message.addExtension(repeatedUint64Extension, 204L);
+ message.addExtension(repeatedSint32Extension, 205);
+ message.addExtension(repeatedSint64Extension, 206L);
+ message.addExtension(repeatedFixed32Extension, 207);
+ message.addExtension(repeatedFixed64Extension, 208L);
message.addExtension(repeatedSfixed32Extension, 209);
message.addExtension(repeatedSfixed64Extension, 210L);
- message.addExtension(repeatedFloatExtension , 211F);
- message.addExtension(repeatedDoubleExtension , 212D);
- message.addExtension(repeatedBoolExtension , true);
- message.addExtension(repeatedStringExtension , "215");
- message.addExtension(repeatedBytesExtension , toBytes("216"));
-
- message.addExtension(repeatedGroupExtension,
- RepeatedGroup_extension.newBuilder().setA(217).build());
- message.addExtension(repeatedNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
- message.addExtension(repeatedForeignMessageExtension,
- ForeignMessage.newBuilder().setC(219).build());
- message.addExtension(repeatedImportMessageExtension,
- ImportMessage.newBuilder().setD(220).build());
- message.addExtension(repeatedLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
+ message.addExtension(repeatedFloatExtension, 211F);
+ message.addExtension(repeatedDoubleExtension, 212D);
+ message.addExtension(repeatedBoolExtension, true);
+ message.addExtension(repeatedStringExtension, "215");
+ message.addExtension(repeatedBytesExtension, toBytes("216"));
+
+ message.addExtension(
+ repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(217).build());
+ message.addExtension(
+ repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ message.addExtension(
+ repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(219).build());
+ message.addExtension(
+ repeatedImportMessageExtension, ImportMessage.newBuilder().setD(220).build());
+ message.addExtension(
+ repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(227).build());
message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAR);
message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAR);
@@ -1294,32 +1280,32 @@ public final class TestUtil {
message.addExtension(repeatedCordExtension, "225");
// Add a second one of each field.
- message.addExtension(repeatedInt32Extension , 301);
- message.addExtension(repeatedInt64Extension , 302L);
- message.addExtension(repeatedUint32Extension , 303);
- message.addExtension(repeatedUint64Extension , 304L);
- message.addExtension(repeatedSint32Extension , 305);
- message.addExtension(repeatedSint64Extension , 306L);
- message.addExtension(repeatedFixed32Extension , 307);
- message.addExtension(repeatedFixed64Extension , 308L);
+ message.addExtension(repeatedInt32Extension, 301);
+ message.addExtension(repeatedInt64Extension, 302L);
+ message.addExtension(repeatedUint32Extension, 303);
+ message.addExtension(repeatedUint64Extension, 304L);
+ message.addExtension(repeatedSint32Extension, 305);
+ message.addExtension(repeatedSint64Extension, 306L);
+ message.addExtension(repeatedFixed32Extension, 307);
+ message.addExtension(repeatedFixed64Extension, 308L);
message.addExtension(repeatedSfixed32Extension, 309);
message.addExtension(repeatedSfixed64Extension, 310L);
- message.addExtension(repeatedFloatExtension , 311F);
- message.addExtension(repeatedDoubleExtension , 312D);
- message.addExtension(repeatedBoolExtension , false);
- message.addExtension(repeatedStringExtension , "315");
- message.addExtension(repeatedBytesExtension , toBytes("316"));
-
- message.addExtension(repeatedGroupExtension,
- RepeatedGroup_extension.newBuilder().setA(317).build());
- message.addExtension(repeatedNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
- message.addExtension(repeatedForeignMessageExtension,
- ForeignMessage.newBuilder().setC(319).build());
- message.addExtension(repeatedImportMessageExtension,
- ImportMessage.newBuilder().setD(320).build());
- message.addExtension(repeatedLazyMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
+ message.addExtension(repeatedFloatExtension, 311F);
+ message.addExtension(repeatedDoubleExtension, 312D);
+ message.addExtension(repeatedBoolExtension, false);
+ message.addExtension(repeatedStringExtension, "315");
+ message.addExtension(repeatedBytesExtension, toBytes("316"));
+
+ message.addExtension(
+ repeatedGroupExtension, RepeatedGroup_extension.newBuilder().setA(317).build());
+ message.addExtension(
+ repeatedNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(318).build());
+ message.addExtension(
+ repeatedForeignMessageExtension, ForeignMessage.newBuilder().setC(319).build());
+ message.addExtension(
+ repeatedImportMessageExtension, ImportMessage.newBuilder().setD(320).build());
+ message.addExtension(
+ repeatedLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(327).build());
message.addExtension(repeatedNestedEnumExtension, TestAllTypes.NestedEnum.BAZ);
message.addExtension(repeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ);
@@ -1330,21 +1316,21 @@ public final class TestUtil {
// -----------------------------------------------------------------
- message.setExtension(defaultInt32Extension , 401);
- message.setExtension(defaultInt64Extension , 402L);
- message.setExtension(defaultUint32Extension , 403);
- message.setExtension(defaultUint64Extension , 404L);
- message.setExtension(defaultSint32Extension , 405);
- message.setExtension(defaultSint64Extension , 406L);
- message.setExtension(defaultFixed32Extension , 407);
- message.setExtension(defaultFixed64Extension , 408L);
+ message.setExtension(defaultInt32Extension, 401);
+ message.setExtension(defaultInt64Extension, 402L);
+ message.setExtension(defaultUint32Extension, 403);
+ message.setExtension(defaultUint64Extension, 404L);
+ message.setExtension(defaultSint32Extension, 405);
+ message.setExtension(defaultSint64Extension, 406L);
+ message.setExtension(defaultFixed32Extension, 407);
+ message.setExtension(defaultFixed64Extension, 408L);
message.setExtension(defaultSfixed32Extension, 409);
message.setExtension(defaultSfixed64Extension, 410L);
- message.setExtension(defaultFloatExtension , 411F);
- message.setExtension(defaultDoubleExtension , 412D);
- message.setExtension(defaultBoolExtension , false);
- message.setExtension(defaultStringExtension , "415");
- message.setExtension(defaultBytesExtension , toBytes("416"));
+ message.setExtension(defaultFloatExtension, 411F);
+ message.setExtension(defaultDoubleExtension, 412D);
+ message.setExtension(defaultBoolExtension, false);
+ message.setExtension(defaultStringExtension, "415");
+ message.setExtension(defaultBytesExtension, toBytes("416"));
message.setExtension(defaultNestedEnumExtension, TestAllTypes.NestedEnum.FOO);
message.setExtension(defaultForeignEnumExtension, ForeignEnum.FOREIGN_FOO);
@@ -1354,8 +1340,8 @@ public final class TestUtil {
message.setExtension(defaultCordExtension, "425");
message.setExtension(oneofUint32Extension, 601);
- message.setExtension(oneofNestedMessageExtension,
- TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
+ message.setExtension(
+ oneofNestedMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(602).build());
message.setExtension(oneofStringExtension, "603");
message.setExtension(oneofBytesExtension, toBytes("604"));
}
@@ -1363,41 +1349,44 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Modify the repeated extensions of {@code message} to contain the values
- * expected by {@code assertRepeatedExtensionsModified()}.
+ * Modify the repeated extensions of {@code message} to contain the values expected by {@code
+ * assertRepeatedExtensionsModified()}.
*/
- public static void modifyRepeatedExtensions(
- TestAllExtensions.Builder message) {
- message.setExtension(repeatedInt32Extension , 1, 501);
- message.setExtension(repeatedInt64Extension , 1, 502L);
- message.setExtension(repeatedUint32Extension , 1, 503);
- message.setExtension(repeatedUint64Extension , 1, 504L);
- message.setExtension(repeatedSint32Extension , 1, 505);
- message.setExtension(repeatedSint64Extension , 1, 506L);
- message.setExtension(repeatedFixed32Extension , 1, 507);
- message.setExtension(repeatedFixed64Extension , 1, 508L);
+ public static void modifyRepeatedExtensions(TestAllExtensions.Builder message) {
+ message.setExtension(repeatedInt32Extension, 1, 501);
+ message.setExtension(repeatedInt64Extension, 1, 502L);
+ message.setExtension(repeatedUint32Extension, 1, 503);
+ message.setExtension(repeatedUint64Extension, 1, 504L);
+ message.setExtension(repeatedSint32Extension, 1, 505);
+ message.setExtension(repeatedSint64Extension, 1, 506L);
+ message.setExtension(repeatedFixed32Extension, 1, 507);
+ message.setExtension(repeatedFixed64Extension, 1, 508L);
message.setExtension(repeatedSfixed32Extension, 1, 509);
message.setExtension(repeatedSfixed64Extension, 1, 510L);
- message.setExtension(repeatedFloatExtension , 1, 511F);
- message.setExtension(repeatedDoubleExtension , 1, 512D);
- message.setExtension(repeatedBoolExtension , 1, true);
- message.setExtension(repeatedStringExtension , 1, "515");
- message.setExtension(repeatedBytesExtension , 1, toBytes("516"));
-
- message.setExtension(repeatedGroupExtension, 1,
- RepeatedGroup_extension.newBuilder().setA(517).build());
- message.setExtension(repeatedNestedMessageExtension, 1,
- TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
- message.setExtension(repeatedForeignMessageExtension, 1,
- ForeignMessage.newBuilder().setC(519).build());
- message.setExtension(repeatedImportMessageExtension, 1,
- ImportMessage.newBuilder().setD(520).build());
- message.setExtension(repeatedLazyMessageExtension, 1,
- TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
-
- message.setExtension(repeatedNestedEnumExtension , 1, TestAllTypes.NestedEnum.FOO);
+ message.setExtension(repeatedFloatExtension, 1, 511F);
+ message.setExtension(repeatedDoubleExtension, 1, 512D);
+ message.setExtension(repeatedBoolExtension, 1, true);
+ message.setExtension(repeatedStringExtension, 1, "515");
+ message.setExtension(repeatedBytesExtension, 1, toBytes("516"));
+
+ message.setExtension(
+ repeatedGroupExtension, 1, RepeatedGroup_extension.newBuilder().setA(517).build());
+ message.setExtension(
+ repeatedNestedMessageExtension,
+ 1,
+ TestAllTypes.NestedMessage.newBuilder().setBb(518).build());
+ message.setExtension(
+ repeatedForeignMessageExtension, 1, ForeignMessage.newBuilder().setC(519).build());
+ message.setExtension(
+ repeatedImportMessageExtension, 1, ImportMessage.newBuilder().setD(520).build());
+ message.setExtension(
+ repeatedLazyMessageExtension,
+ 1,
+ TestAllTypes.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setExtension(repeatedNestedEnumExtension, 1, TestAllTypes.NestedEnum.FOO);
message.setExtension(repeatedForeignEnumExtension, 1, ForeignEnum.FOREIGN_FOO);
- message.setExtension(repeatedImportEnumExtension , 1, ImportEnum.IMPORT_FOO);
+ message.setExtension(repeatedImportEnumExtension, 1, ImportEnum.IMPORT_FOO);
message.setExtension(repeatedStringPieceExtension, 1, "524");
message.setExtension(repeatedCordExtension, 1, "525");
@@ -1406,218 +1395,215 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions}.
*/
- public static void assertAllExtensionsSet(
- TestAllExtensionsOrBuilder message) {
- Assert.assertTrue(message.hasExtension(optionalInt32Extension ));
- Assert.assertTrue(message.hasExtension(optionalInt64Extension ));
- Assert.assertTrue(message.hasExtension(optionalUint32Extension ));
- Assert.assertTrue(message.hasExtension(optionalUint64Extension ));
- Assert.assertTrue(message.hasExtension(optionalSint32Extension ));
- Assert.assertTrue(message.hasExtension(optionalSint64Extension ));
- Assert.assertTrue(message.hasExtension(optionalFixed32Extension ));
- Assert.assertTrue(message.hasExtension(optionalFixed64Extension ));
+ public static void assertAllExtensionsSet(TestAllExtensionsOrBuilder message) {
+ Assert.assertTrue(message.hasExtension(optionalInt32Extension));
+ Assert.assertTrue(message.hasExtension(optionalInt64Extension));
+ Assert.assertTrue(message.hasExtension(optionalUint32Extension));
+ Assert.assertTrue(message.hasExtension(optionalUint64Extension));
+ Assert.assertTrue(message.hasExtension(optionalSint32Extension));
+ Assert.assertTrue(message.hasExtension(optionalSint64Extension));
+ Assert.assertTrue(message.hasExtension(optionalFixed32Extension));
+ Assert.assertTrue(message.hasExtension(optionalFixed64Extension));
Assert.assertTrue(message.hasExtension(optionalSfixed32Extension));
Assert.assertTrue(message.hasExtension(optionalSfixed64Extension));
- Assert.assertTrue(message.hasExtension(optionalFloatExtension ));
- Assert.assertTrue(message.hasExtension(optionalDoubleExtension ));
- Assert.assertTrue(message.hasExtension(optionalBoolExtension ));
- Assert.assertTrue(message.hasExtension(optionalStringExtension ));
- Assert.assertTrue(message.hasExtension(optionalBytesExtension ));
-
- Assert.assertTrue(message.hasExtension(optionalGroupExtension ));
- Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension ));
+ Assert.assertTrue(message.hasExtension(optionalFloatExtension));
+ Assert.assertTrue(message.hasExtension(optionalDoubleExtension));
+ Assert.assertTrue(message.hasExtension(optionalBoolExtension));
+ Assert.assertTrue(message.hasExtension(optionalStringExtension));
+ Assert.assertTrue(message.hasExtension(optionalBytesExtension));
+
+ Assert.assertTrue(message.hasExtension(optionalGroupExtension));
+ Assert.assertTrue(message.hasExtension(optionalNestedMessageExtension));
Assert.assertTrue(message.hasExtension(optionalForeignMessageExtension));
- Assert.assertTrue(message.hasExtension(optionalImportMessageExtension ));
+ Assert.assertTrue(message.hasExtension(optionalImportMessageExtension));
- Assert.assertTrue(message.getExtension(optionalGroupExtension ).hasA());
- Assert.assertTrue(message.getExtension(optionalNestedMessageExtension ).hasBb());
+ Assert.assertTrue(message.getExtension(optionalGroupExtension).hasA());
+ Assert.assertTrue(message.getExtension(optionalNestedMessageExtension).hasBb());
Assert.assertTrue(message.getExtension(optionalForeignMessageExtension).hasC());
- Assert.assertTrue(message.getExtension(optionalImportMessageExtension ).hasD());
+ Assert.assertTrue(message.getExtension(optionalImportMessageExtension).hasD());
- Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension ));
+ Assert.assertTrue(message.hasExtension(optionalNestedEnumExtension));
Assert.assertTrue(message.hasExtension(optionalForeignEnumExtension));
- Assert.assertTrue(message.hasExtension(optionalImportEnumExtension ));
+ Assert.assertTrue(message.hasExtension(optionalImportEnumExtension));
Assert.assertTrue(message.hasExtension(optionalStringPieceExtension));
Assert.assertTrue(message.hasExtension(optionalCordExtension));
- assertEqualsExactType(101 , message.getExtension(optionalInt32Extension ));
- assertEqualsExactType(102L , message.getExtension(optionalInt64Extension ));
- assertEqualsExactType(103 , message.getExtension(optionalUint32Extension ));
- assertEqualsExactType(104L , message.getExtension(optionalUint64Extension ));
- assertEqualsExactType(105 , message.getExtension(optionalSint32Extension ));
- assertEqualsExactType(106L , message.getExtension(optionalSint64Extension ));
- assertEqualsExactType(107 , message.getExtension(optionalFixed32Extension ));
- assertEqualsExactType(108L , message.getExtension(optionalFixed64Extension ));
- assertEqualsExactType(109 , message.getExtension(optionalSfixed32Extension));
- assertEqualsExactType(110L , message.getExtension(optionalSfixed64Extension));
- assertEqualsExactType(111F , message.getExtension(optionalFloatExtension ));
- assertEqualsExactType(112D , message.getExtension(optionalDoubleExtension ));
- assertEqualsExactType(true , message.getExtension(optionalBoolExtension ));
- assertEqualsExactType("115", message.getExtension(optionalStringExtension ));
+ assertEqualsExactType(101, message.getExtension(optionalInt32Extension));
+ assertEqualsExactType(102L, message.getExtension(optionalInt64Extension));
+ assertEqualsExactType(103, message.getExtension(optionalUint32Extension));
+ assertEqualsExactType(104L, message.getExtension(optionalUint64Extension));
+ assertEqualsExactType(105, message.getExtension(optionalSint32Extension));
+ assertEqualsExactType(106L, message.getExtension(optionalSint64Extension));
+ assertEqualsExactType(107, message.getExtension(optionalFixed32Extension));
+ assertEqualsExactType(108L, message.getExtension(optionalFixed64Extension));
+ assertEqualsExactType(109, message.getExtension(optionalSfixed32Extension));
+ assertEqualsExactType(110L, message.getExtension(optionalSfixed64Extension));
+ assertEqualsExactType(111F, message.getExtension(optionalFloatExtension));
+ assertEqualsExactType(112D, message.getExtension(optionalDoubleExtension));
+ assertEqualsExactType(true, message.getExtension(optionalBoolExtension));
+ assertEqualsExactType("115", message.getExtension(optionalStringExtension));
assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtension));
- assertEqualsExactType(117, message.getExtension(optionalGroupExtension ).getA());
- assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension ).getBb());
- assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension ).getC());
- assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension ).getD());
+ assertEqualsExactType(117, message.getExtension(optionalGroupExtension).getA());
+ assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtension).getBb());
+ assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtension).getC());
+ assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension).getD());
assertEqualsExactType(126, message.getExtension(optionalPublicImportMessageExtension).getE());
- assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension ).getBb());
+ assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAZ,
- message.getExtension(optionalNestedEnumExtension));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(optionalForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_BAZ,
- message.getExtension(optionalImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAZ, message.getExtension(optionalForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_BAZ, message.getExtension(optionalImportEnumExtension));
assertEqualsExactType("124", message.getExtension(optionalStringPieceExtension));
assertEqualsExactType("125", message.getExtension(optionalCordExtension));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb());
assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtension, 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(repeatedForeignEnumExtension, 0));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(repeatedImportEnumExtension, 0));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0));
- assertEqualsExactType(301 , message.getExtension(repeatedInt32Extension , 1));
- assertEqualsExactType(302L , message.getExtension(repeatedInt64Extension , 1));
- assertEqualsExactType(303 , message.getExtension(repeatedUint32Extension , 1));
- assertEqualsExactType(304L , message.getExtension(repeatedUint64Extension , 1));
- assertEqualsExactType(305 , message.getExtension(repeatedSint32Extension , 1));
- assertEqualsExactType(306L , message.getExtension(repeatedSint64Extension , 1));
- assertEqualsExactType(307 , message.getExtension(repeatedFixed32Extension , 1));
- assertEqualsExactType(308L , message.getExtension(repeatedFixed64Extension , 1));
- assertEqualsExactType(309 , message.getExtension(repeatedSfixed32Extension, 1));
- assertEqualsExactType(310L , message.getExtension(repeatedSfixed64Extension, 1));
- assertEqualsExactType(311F , message.getExtension(repeatedFloatExtension , 1));
- assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtension , 1));
- assertEqualsExactType(false, message.getExtension(repeatedBoolExtension , 1));
- assertEqualsExactType("315", message.getExtension(repeatedStringExtension , 1));
+ assertEqualsExactType(301, message.getExtension(repeatedInt32Extension, 1));
+ assertEqualsExactType(302L, message.getExtension(repeatedInt64Extension, 1));
+ assertEqualsExactType(303, message.getExtension(repeatedUint32Extension, 1));
+ assertEqualsExactType(304L, message.getExtension(repeatedUint64Extension, 1));
+ assertEqualsExactType(305, message.getExtension(repeatedSint32Extension, 1));
+ assertEqualsExactType(306L, message.getExtension(repeatedSint64Extension, 1));
+ assertEqualsExactType(307, message.getExtension(repeatedFixed32Extension, 1));
+ assertEqualsExactType(308L, message.getExtension(repeatedFixed64Extension, 1));
+ assertEqualsExactType(309, message.getExtension(repeatedSfixed32Extension, 1));
+ assertEqualsExactType(310L, message.getExtension(repeatedSfixed64Extension, 1));
+ assertEqualsExactType(311F, message.getExtension(repeatedFloatExtension, 1));
+ assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtension, 1));
+ assertEqualsExactType(false, message.getExtension(repeatedBoolExtension, 1));
+ assertEqualsExactType("315", message.getExtension(repeatedStringExtension, 1));
assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtension, 1));
- assertEqualsExactType(317, message.getExtension(repeatedGroupExtension , 1).getA());
- assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension , 1).getBb());
+ assertEqualsExactType(317, message.getExtension(repeatedGroupExtension, 1).getA());
+ assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtension, 1).getBb());
assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtension, 1).getC());
- assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension , 1).getD());
- assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension , 1).getBb());
+ assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtension, 1).getD());
+ assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtension, 1).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAZ,
- message.getExtension(repeatedNestedEnumExtension, 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(repeatedForeignEnumExtension, 1));
- assertEqualsExactType(ImportEnum.IMPORT_BAZ,
- message.getExtension(repeatedImportEnumExtension, 1));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtension, 1));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAZ, message.getExtension(repeatedForeignEnumExtension, 1));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAZ, message.getExtension(repeatedImportEnumExtension, 1));
assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtension, 1));
assertEqualsExactType("325", message.getExtension(repeatedCordExtension, 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasExtension(defaultInt32Extension ));
- Assert.assertTrue(message.hasExtension(defaultInt64Extension ));
- Assert.assertTrue(message.hasExtension(defaultUint32Extension ));
- Assert.assertTrue(message.hasExtension(defaultUint64Extension ));
- Assert.assertTrue(message.hasExtension(defaultSint32Extension ));
- Assert.assertTrue(message.hasExtension(defaultSint64Extension ));
- Assert.assertTrue(message.hasExtension(defaultFixed32Extension ));
- Assert.assertTrue(message.hasExtension(defaultFixed64Extension ));
+ Assert.assertTrue(message.hasExtension(defaultInt32Extension));
+ Assert.assertTrue(message.hasExtension(defaultInt64Extension));
+ Assert.assertTrue(message.hasExtension(defaultUint32Extension));
+ Assert.assertTrue(message.hasExtension(defaultUint64Extension));
+ Assert.assertTrue(message.hasExtension(defaultSint32Extension));
+ Assert.assertTrue(message.hasExtension(defaultSint64Extension));
+ Assert.assertTrue(message.hasExtension(defaultFixed32Extension));
+ Assert.assertTrue(message.hasExtension(defaultFixed64Extension));
Assert.assertTrue(message.hasExtension(defaultSfixed32Extension));
Assert.assertTrue(message.hasExtension(defaultSfixed64Extension));
- Assert.assertTrue(message.hasExtension(defaultFloatExtension ));
- Assert.assertTrue(message.hasExtension(defaultDoubleExtension ));
- Assert.assertTrue(message.hasExtension(defaultBoolExtension ));
- Assert.assertTrue(message.hasExtension(defaultStringExtension ));
- Assert.assertTrue(message.hasExtension(defaultBytesExtension ));
+ Assert.assertTrue(message.hasExtension(defaultFloatExtension));
+ Assert.assertTrue(message.hasExtension(defaultDoubleExtension));
+ Assert.assertTrue(message.hasExtension(defaultBoolExtension));
+ Assert.assertTrue(message.hasExtension(defaultStringExtension));
+ Assert.assertTrue(message.hasExtension(defaultBytesExtension));
- Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension ));
+ Assert.assertTrue(message.hasExtension(defaultNestedEnumExtension));
Assert.assertTrue(message.hasExtension(defaultForeignEnumExtension));
- Assert.assertTrue(message.hasExtension(defaultImportEnumExtension ));
+ Assert.assertTrue(message.hasExtension(defaultImportEnumExtension));
Assert.assertTrue(message.hasExtension(defaultStringPieceExtension));
Assert.assertTrue(message.hasExtension(defaultCordExtension));
- assertEqualsExactType(401 , message.getExtension(defaultInt32Extension ));
- assertEqualsExactType(402L , message.getExtension(defaultInt64Extension ));
- assertEqualsExactType(403 , message.getExtension(defaultUint32Extension ));
- assertEqualsExactType(404L , message.getExtension(defaultUint64Extension ));
- assertEqualsExactType(405 , message.getExtension(defaultSint32Extension ));
- assertEqualsExactType(406L , message.getExtension(defaultSint64Extension ));
- assertEqualsExactType(407 , message.getExtension(defaultFixed32Extension ));
- assertEqualsExactType(408L , message.getExtension(defaultFixed64Extension ));
- assertEqualsExactType(409 , message.getExtension(defaultSfixed32Extension));
- assertEqualsExactType(410L , message.getExtension(defaultSfixed64Extension));
- assertEqualsExactType(411F , message.getExtension(defaultFloatExtension ));
- assertEqualsExactType(412D , message.getExtension(defaultDoubleExtension ));
- assertEqualsExactType(false, message.getExtension(defaultBoolExtension ));
- assertEqualsExactType("415", message.getExtension(defaultStringExtension ));
+ assertEqualsExactType(401, message.getExtension(defaultInt32Extension));
+ assertEqualsExactType(402L, message.getExtension(defaultInt64Extension));
+ assertEqualsExactType(403, message.getExtension(defaultUint32Extension));
+ assertEqualsExactType(404L, message.getExtension(defaultUint64Extension));
+ assertEqualsExactType(405, message.getExtension(defaultSint32Extension));
+ assertEqualsExactType(406L, message.getExtension(defaultSint64Extension));
+ assertEqualsExactType(407, message.getExtension(defaultFixed32Extension));
+ assertEqualsExactType(408L, message.getExtension(defaultFixed64Extension));
+ assertEqualsExactType(409, message.getExtension(defaultSfixed32Extension));
+ assertEqualsExactType(410L, message.getExtension(defaultSfixed64Extension));
+ assertEqualsExactType(411F, message.getExtension(defaultFloatExtension));
+ assertEqualsExactType(412D, message.getExtension(defaultDoubleExtension));
+ assertEqualsExactType(false, message.getExtension(defaultBoolExtension));
+ assertEqualsExactType("415", message.getExtension(defaultStringExtension));
assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtension));
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(defaultNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(defaultForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(defaultImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(defaultForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(defaultImportEnumExtension));
assertEqualsExactType("424", message.getExtension(defaultStringPieceExtension));
assertEqualsExactType("425", message.getExtension(defaultCordExtension));
@@ -1630,184 +1616,181 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are cleared, and that getting the extensions returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are
+ * cleared, and that getting the extensions returns their default values.
*/
public static void assertExtensionsClear(TestAllExtensionsOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasExtension(optionalInt32Extension ));
- Assert.assertFalse(message.hasExtension(optionalInt64Extension ));
- Assert.assertFalse(message.hasExtension(optionalUint32Extension ));
- Assert.assertFalse(message.hasExtension(optionalUint64Extension ));
- Assert.assertFalse(message.hasExtension(optionalSint32Extension ));
- Assert.assertFalse(message.hasExtension(optionalSint64Extension ));
- Assert.assertFalse(message.hasExtension(optionalFixed32Extension ));
- Assert.assertFalse(message.hasExtension(optionalFixed64Extension ));
+ Assert.assertFalse(message.hasExtension(optionalInt32Extension));
+ Assert.assertFalse(message.hasExtension(optionalInt64Extension));
+ Assert.assertFalse(message.hasExtension(optionalUint32Extension));
+ Assert.assertFalse(message.hasExtension(optionalUint64Extension));
+ Assert.assertFalse(message.hasExtension(optionalSint32Extension));
+ Assert.assertFalse(message.hasExtension(optionalSint64Extension));
+ Assert.assertFalse(message.hasExtension(optionalFixed32Extension));
+ Assert.assertFalse(message.hasExtension(optionalFixed64Extension));
Assert.assertFalse(message.hasExtension(optionalSfixed32Extension));
Assert.assertFalse(message.hasExtension(optionalSfixed64Extension));
- Assert.assertFalse(message.hasExtension(optionalFloatExtension ));
- Assert.assertFalse(message.hasExtension(optionalDoubleExtension ));
- Assert.assertFalse(message.hasExtension(optionalBoolExtension ));
- Assert.assertFalse(message.hasExtension(optionalStringExtension ));
- Assert.assertFalse(message.hasExtension(optionalBytesExtension ));
-
- Assert.assertFalse(message.hasExtension(optionalGroupExtension ));
- Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension ));
+ Assert.assertFalse(message.hasExtension(optionalFloatExtension));
+ Assert.assertFalse(message.hasExtension(optionalDoubleExtension));
+ Assert.assertFalse(message.hasExtension(optionalBoolExtension));
+ Assert.assertFalse(message.hasExtension(optionalStringExtension));
+ Assert.assertFalse(message.hasExtension(optionalBytesExtension));
+
+ Assert.assertFalse(message.hasExtension(optionalGroupExtension));
+ Assert.assertFalse(message.hasExtension(optionalNestedMessageExtension));
Assert.assertFalse(message.hasExtension(optionalForeignMessageExtension));
- Assert.assertFalse(message.hasExtension(optionalImportMessageExtension ));
+ Assert.assertFalse(message.hasExtension(optionalImportMessageExtension));
- Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension ));
+ Assert.assertFalse(message.hasExtension(optionalNestedEnumExtension));
Assert.assertFalse(message.hasExtension(optionalForeignEnumExtension));
- Assert.assertFalse(message.hasExtension(optionalImportEnumExtension ));
+ Assert.assertFalse(message.hasExtension(optionalImportEnumExtension));
Assert.assertFalse(message.hasExtension(optionalStringPieceExtension));
Assert.assertFalse(message.hasExtension(optionalCordExtension));
// Optional fields without defaults are set to zero or something like it.
- assertEqualsExactType(0 , message.getExtension(optionalInt32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalInt64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalUint32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalUint64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalSint32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalSint64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalFixed32Extension ));
- assertEqualsExactType(0L , message.getExtension(optionalFixed64Extension ));
- assertEqualsExactType(0 , message.getExtension(optionalSfixed32Extension));
- assertEqualsExactType(0L , message.getExtension(optionalSfixed64Extension));
- assertEqualsExactType(0F , message.getExtension(optionalFloatExtension ));
- assertEqualsExactType(0D , message.getExtension(optionalDoubleExtension ));
- assertEqualsExactType(false, message.getExtension(optionalBoolExtension ));
- assertEqualsExactType("" , message.getExtension(optionalStringExtension ));
+ assertEqualsExactType(0, message.getExtension(optionalInt32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalInt64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalUint32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalUint64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalSint32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalSint64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalFixed32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalFixed64Extension));
+ assertEqualsExactType(0, message.getExtension(optionalSfixed32Extension));
+ assertEqualsExactType(0L, message.getExtension(optionalSfixed64Extension));
+ assertEqualsExactType(0F, message.getExtension(optionalFloatExtension));
+ assertEqualsExactType(0D, message.getExtension(optionalDoubleExtension));
+ assertEqualsExactType(false, message.getExtension(optionalBoolExtension));
+ assertEqualsExactType("", message.getExtension(optionalStringExtension));
assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtension));
// Embedded messages should also be clear.
- Assert.assertFalse(message.getExtension(optionalGroupExtension ).hasA());
- Assert.assertFalse(message.getExtension(optionalNestedMessageExtension ).hasBb());
+ Assert.assertFalse(message.getExtension(optionalGroupExtension).hasA());
+ Assert.assertFalse(message.getExtension(optionalNestedMessageExtension).hasBb());
Assert.assertFalse(message.getExtension(optionalForeignMessageExtension).hasC());
- Assert.assertFalse(message.getExtension(optionalImportMessageExtension ).hasD());
+ Assert.assertFalse(message.getExtension(optionalImportMessageExtension).hasD());
- assertEqualsExactType(0, message.getExtension(optionalGroupExtension ).getA());
- assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalGroupExtension).getA());
+ assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtension).getBb());
assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtension).getC());
- assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension ).getD());
+ assertEqualsExactType(0, message.getExtension(optionalImportMessageExtension).getD());
// Enums without defaults are set to the first value in the enum.
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(optionalNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(optionalForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(optionalImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(optionalForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_FOO, message.getExtension(optionalImportEnumExtension));
assertEqualsExactType("", message.getExtension(optionalStringPieceExtension));
assertEqualsExactType("", message.getExtension(optionalCordExtension));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtension));
// Repeated fields are empty via getExtension().size().
- Assert.assertEquals(0, message.getExtension(repeatedInt32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedInt64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedUint32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedUint64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedSint32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedSint64Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedInt32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedInt64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedUint32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedUint64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedSint32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedSint64Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFixed32Extension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFixed64Extension).size());
Assert.assertEquals(0, message.getExtension(repeatedSfixed32Extension).size());
Assert.assertEquals(0, message.getExtension(repeatedSfixed64Extension).size());
- Assert.assertEquals(0, message.getExtension(repeatedFloatExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedBoolExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedStringExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedBytesExtension ).size());
-
- Assert.assertEquals(0, message.getExtension(repeatedGroupExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedFloatExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedDoubleExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedBoolExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedStringExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedBytesExtension).size());
+
+ Assert.assertEquals(0, message.getExtension(repeatedGroupExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedNestedMessageExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedForeignMessageExtension).size());
- Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension ).size());
- Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension ).size());
+ Assert.assertEquals(0, message.getExtension(repeatedImportMessageExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedLazyMessageExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedNestedEnumExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedForeignEnumExtension).size());
+ Assert.assertEquals(0, message.getExtension(repeatedImportEnumExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedStringPieceExtension).size());
Assert.assertEquals(0, message.getExtension(repeatedCordExtension).size());
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasExtension(defaultInt32Extension ));
- Assert.assertFalse(message.hasExtension(defaultInt64Extension ));
- Assert.assertFalse(message.hasExtension(defaultUint32Extension ));
- Assert.assertFalse(message.hasExtension(defaultUint64Extension ));
- Assert.assertFalse(message.hasExtension(defaultSint32Extension ));
- Assert.assertFalse(message.hasExtension(defaultSint64Extension ));
- Assert.assertFalse(message.hasExtension(defaultFixed32Extension ));
- Assert.assertFalse(message.hasExtension(defaultFixed64Extension ));
+ Assert.assertFalse(message.hasExtension(defaultInt32Extension));
+ Assert.assertFalse(message.hasExtension(defaultInt64Extension));
+ Assert.assertFalse(message.hasExtension(defaultUint32Extension));
+ Assert.assertFalse(message.hasExtension(defaultUint64Extension));
+ Assert.assertFalse(message.hasExtension(defaultSint32Extension));
+ Assert.assertFalse(message.hasExtension(defaultSint64Extension));
+ Assert.assertFalse(message.hasExtension(defaultFixed32Extension));
+ Assert.assertFalse(message.hasExtension(defaultFixed64Extension));
Assert.assertFalse(message.hasExtension(defaultSfixed32Extension));
Assert.assertFalse(message.hasExtension(defaultSfixed64Extension));
- Assert.assertFalse(message.hasExtension(defaultFloatExtension ));
- Assert.assertFalse(message.hasExtension(defaultDoubleExtension ));
- Assert.assertFalse(message.hasExtension(defaultBoolExtension ));
- Assert.assertFalse(message.hasExtension(defaultStringExtension ));
- Assert.assertFalse(message.hasExtension(defaultBytesExtension ));
+ Assert.assertFalse(message.hasExtension(defaultFloatExtension));
+ Assert.assertFalse(message.hasExtension(defaultDoubleExtension));
+ Assert.assertFalse(message.hasExtension(defaultBoolExtension));
+ Assert.assertFalse(message.hasExtension(defaultStringExtension));
+ Assert.assertFalse(message.hasExtension(defaultBytesExtension));
- Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension ));
+ Assert.assertFalse(message.hasExtension(defaultNestedEnumExtension));
Assert.assertFalse(message.hasExtension(defaultForeignEnumExtension));
- Assert.assertFalse(message.hasExtension(defaultImportEnumExtension ));
+ Assert.assertFalse(message.hasExtension(defaultImportEnumExtension));
Assert.assertFalse(message.hasExtension(defaultStringPieceExtension));
Assert.assertFalse(message.hasExtension(defaultCordExtension));
// Fields with defaults have their default values (duh).
- assertEqualsExactType( 41 , message.getExtension(defaultInt32Extension ));
- assertEqualsExactType( 42L , message.getExtension(defaultInt64Extension ));
- assertEqualsExactType( 43 , message.getExtension(defaultUint32Extension ));
- assertEqualsExactType( 44L , message.getExtension(defaultUint64Extension ));
- assertEqualsExactType(-45 , message.getExtension(defaultSint32Extension ));
- assertEqualsExactType( 46L , message.getExtension(defaultSint64Extension ));
- assertEqualsExactType( 47 , message.getExtension(defaultFixed32Extension ));
- assertEqualsExactType( 48L , message.getExtension(defaultFixed64Extension ));
- assertEqualsExactType( 49 , message.getExtension(defaultSfixed32Extension));
- assertEqualsExactType(-50L , message.getExtension(defaultSfixed64Extension));
- assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtension ));
- assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtension ));
- assertEqualsExactType(true , message.getExtension(defaultBoolExtension ));
- assertEqualsExactType("hello", message.getExtension(defaultStringExtension ));
+ assertEqualsExactType(41, message.getExtension(defaultInt32Extension));
+ assertEqualsExactType(42L, message.getExtension(defaultInt64Extension));
+ assertEqualsExactType(43, message.getExtension(defaultUint32Extension));
+ assertEqualsExactType(44L, message.getExtension(defaultUint64Extension));
+ assertEqualsExactType(-45, message.getExtension(defaultSint32Extension));
+ assertEqualsExactType(46L, message.getExtension(defaultSint64Extension));
+ assertEqualsExactType(47, message.getExtension(defaultFixed32Extension));
+ assertEqualsExactType(48L, message.getExtension(defaultFixed64Extension));
+ assertEqualsExactType(49, message.getExtension(defaultSfixed32Extension));
+ assertEqualsExactType(-50L, message.getExtension(defaultSfixed64Extension));
+ assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtension));
+ assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtension));
+ assertEqualsExactType(true, message.getExtension(defaultBoolExtension));
+ assertEqualsExactType("hello", message.getExtension(defaultStringExtension));
assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtension));
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(defaultNestedEnumExtension ));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(defaultForeignEnumExtension));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(defaultImportEnumExtension));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtension));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(defaultForeignEnumExtension));
+ assertEqualsExactType(ImportEnum.IMPORT_BAR, message.getExtension(defaultImportEnumExtension));
assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtension));
assertEqualsExactType("123", message.getExtension(defaultCordExtension));
@@ -1821,405 +1804,402 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}
- * followed by {@code modifyRepeatedExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}.
*/
- public static void assertRepeatedExtensionsModified(
- TestAllExtensionsOrBuilder message) {
+ public static void assertRepeatedExtensionsModified(TestAllExtensionsOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtension));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtension));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtension));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtension));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtension));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32Extension , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64Extension , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32Extension , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64Extension , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32Extension , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64Extension , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32Extension , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64Extension , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32Extension, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64Extension, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtension , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtension , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32Extension, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64Extension, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32Extension, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64Extension, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32Extension, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64Extension, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32Extension, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64Extension, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32Extension, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64Extension, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtension, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtension, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtension, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtension , 0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension , 0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtension, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtension, 0).getBb());
assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtension, 0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension , 0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension , 0).getBb());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtension, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtension, 0).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtension, 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(repeatedForeignEnumExtension, 0));
- assertEqualsExactType(ImportEnum.IMPORT_BAR,
- message.getExtension(repeatedImportEnumExtension, 0));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtension, 0));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_BAR, message.getExtension(repeatedForeignEnumExtension, 0));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_BAR, message.getExtension(repeatedImportEnumExtension, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtension, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtension, 0));
// Actually verify the second (modified) elements now.
- assertEqualsExactType(501 , message.getExtension(repeatedInt32Extension , 1));
- assertEqualsExactType(502L , message.getExtension(repeatedInt64Extension , 1));
- assertEqualsExactType(503 , message.getExtension(repeatedUint32Extension , 1));
- assertEqualsExactType(504L , message.getExtension(repeatedUint64Extension , 1));
- assertEqualsExactType(505 , message.getExtension(repeatedSint32Extension , 1));
- assertEqualsExactType(506L , message.getExtension(repeatedSint64Extension , 1));
- assertEqualsExactType(507 , message.getExtension(repeatedFixed32Extension , 1));
- assertEqualsExactType(508L , message.getExtension(repeatedFixed64Extension , 1));
- assertEqualsExactType(509 , message.getExtension(repeatedSfixed32Extension, 1));
- assertEqualsExactType(510L , message.getExtension(repeatedSfixed64Extension, 1));
- assertEqualsExactType(511F , message.getExtension(repeatedFloatExtension , 1));
- assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtension , 1));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtension , 1));
- assertEqualsExactType("515", message.getExtension(repeatedStringExtension , 1));
+ assertEqualsExactType(501, message.getExtension(repeatedInt32Extension, 1));
+ assertEqualsExactType(502L, message.getExtension(repeatedInt64Extension, 1));
+ assertEqualsExactType(503, message.getExtension(repeatedUint32Extension, 1));
+ assertEqualsExactType(504L, message.getExtension(repeatedUint64Extension, 1));
+ assertEqualsExactType(505, message.getExtension(repeatedSint32Extension, 1));
+ assertEqualsExactType(506L, message.getExtension(repeatedSint64Extension, 1));
+ assertEqualsExactType(507, message.getExtension(repeatedFixed32Extension, 1));
+ assertEqualsExactType(508L, message.getExtension(repeatedFixed64Extension, 1));
+ assertEqualsExactType(509, message.getExtension(repeatedSfixed32Extension, 1));
+ assertEqualsExactType(510L, message.getExtension(repeatedSfixed64Extension, 1));
+ assertEqualsExactType(511F, message.getExtension(repeatedFloatExtension, 1));
+ assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtension, 1));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtension, 1));
+ assertEqualsExactType("515", message.getExtension(repeatedStringExtension, 1));
assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtension, 1));
- assertEqualsExactType(517, message.getExtension(repeatedGroupExtension , 1).getA());
- assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension , 1).getBb());
+ assertEqualsExactType(517, message.getExtension(repeatedGroupExtension, 1).getA());
+ assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtension, 1).getBb());
assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtension, 1).getC());
- assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension , 1).getD());
- assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension , 1).getBb());
+ assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtension, 1).getD());
+ assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtension, 1).getBb());
- assertEqualsExactType(TestAllTypes.NestedEnum.FOO,
- message.getExtension(repeatedNestedEnumExtension, 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_FOO,
- message.getExtension(repeatedForeignEnumExtension, 1));
- assertEqualsExactType(ImportEnum.IMPORT_FOO,
- message.getExtension(repeatedImportEnumExtension, 1));
+ assertEqualsExactType(
+ TestAllTypes.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtension, 1));
+ assertEqualsExactType(
+ ForeignEnum.FOREIGN_FOO, message.getExtension(repeatedForeignEnumExtension, 1));
+ assertEqualsExactType(
+ ImportEnum.IMPORT_FOO, message.getExtension(repeatedImportEnumExtension, 1));
assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtension, 1));
assertEqualsExactType("525", message.getExtension(repeatedCordExtension, 1));
}
public static void setPackedExtensions(TestPackedExtensions.Builder message) {
- message.addExtension(packedInt32Extension , 601);
- message.addExtension(packedInt64Extension , 602L);
- message.addExtension(packedUint32Extension , 603);
- message.addExtension(packedUint64Extension , 604L);
- message.addExtension(packedSint32Extension , 605);
- message.addExtension(packedSint64Extension , 606L);
- message.addExtension(packedFixed32Extension , 607);
- message.addExtension(packedFixed64Extension , 608L);
+ message.addExtension(packedInt32Extension, 601);
+ message.addExtension(packedInt64Extension, 602L);
+ message.addExtension(packedUint32Extension, 603);
+ message.addExtension(packedUint64Extension, 604L);
+ message.addExtension(packedSint32Extension, 605);
+ message.addExtension(packedSint64Extension, 606L);
+ message.addExtension(packedFixed32Extension, 607);
+ message.addExtension(packedFixed64Extension, 608L);
message.addExtension(packedSfixed32Extension, 609);
message.addExtension(packedSfixed64Extension, 610L);
- message.addExtension(packedFloatExtension , 611F);
- message.addExtension(packedDoubleExtension , 612D);
- message.addExtension(packedBoolExtension , true);
+ message.addExtension(packedFloatExtension, 611F);
+ message.addExtension(packedDoubleExtension, 612D);
+ message.addExtension(packedBoolExtension, true);
message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAR);
// Add a second one of each field.
- message.addExtension(packedInt32Extension , 701);
- message.addExtension(packedInt64Extension , 702L);
- message.addExtension(packedUint32Extension , 703);
- message.addExtension(packedUint64Extension , 704L);
- message.addExtension(packedSint32Extension , 705);
- message.addExtension(packedSint64Extension , 706L);
- message.addExtension(packedFixed32Extension , 707);
- message.addExtension(packedFixed64Extension , 708L);
+ message.addExtension(packedInt32Extension, 701);
+ message.addExtension(packedInt64Extension, 702L);
+ message.addExtension(packedUint32Extension, 703);
+ message.addExtension(packedUint64Extension, 704L);
+ message.addExtension(packedSint32Extension, 705);
+ message.addExtension(packedSint64Extension, 706L);
+ message.addExtension(packedFixed32Extension, 707);
+ message.addExtension(packedFixed64Extension, 708L);
message.addExtension(packedSfixed32Extension, 709);
message.addExtension(packedSfixed64Extension, 710L);
- message.addExtension(packedFloatExtension , 711F);
- message.addExtension(packedDoubleExtension , 712D);
- message.addExtension(packedBoolExtension , false);
+ message.addExtension(packedFloatExtension, 711F);
+ message.addExtension(packedDoubleExtension, 712D);
+ message.addExtension(packedBoolExtension, false);
message.addExtension(packedEnumExtension, ForeignEnum.FOREIGN_BAZ);
}
public static void assertPackedExtensionsSet(TestPackedExtensions message) {
- Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension ));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint64Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed32Extension));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed64Extension));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed32Extension));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed64Extension));
- Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension ));
- Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension ));
- Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension ));
+ Assert.assertEquals(2, message.getExtensionCount(packedFloatExtension));
+ Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtension));
+ Assert.assertEquals(2, message.getExtensionCount(packedBoolExtension));
Assert.assertEquals(2, message.getExtensionCount(packedEnumExtension));
- assertEqualsExactType(601 , message.getExtension(packedInt32Extension , 0));
- assertEqualsExactType(602L , message.getExtension(packedInt64Extension , 0));
- assertEqualsExactType(603 , message.getExtension(packedUint32Extension , 0));
- assertEqualsExactType(604L , message.getExtension(packedUint64Extension , 0));
- assertEqualsExactType(605 , message.getExtension(packedSint32Extension , 0));
- assertEqualsExactType(606L , message.getExtension(packedSint64Extension , 0));
- assertEqualsExactType(607 , message.getExtension(packedFixed32Extension , 0));
- assertEqualsExactType(608L , message.getExtension(packedFixed64Extension , 0));
- assertEqualsExactType(609 , message.getExtension(packedSfixed32Extension, 0));
- assertEqualsExactType(610L , message.getExtension(packedSfixed64Extension, 0));
- assertEqualsExactType(611F , message.getExtension(packedFloatExtension , 0));
- assertEqualsExactType(612D , message.getExtension(packedDoubleExtension , 0));
- assertEqualsExactType(true , message.getExtension(packedBoolExtension , 0));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAR,
- message.getExtension(packedEnumExtension, 0));
- assertEqualsExactType(701 , message.getExtension(packedInt32Extension , 1));
- assertEqualsExactType(702L , message.getExtension(packedInt64Extension , 1));
- assertEqualsExactType(703 , message.getExtension(packedUint32Extension , 1));
- assertEqualsExactType(704L , message.getExtension(packedUint64Extension , 1));
- assertEqualsExactType(705 , message.getExtension(packedSint32Extension , 1));
- assertEqualsExactType(706L , message.getExtension(packedSint64Extension , 1));
- assertEqualsExactType(707 , message.getExtension(packedFixed32Extension , 1));
- assertEqualsExactType(708L , message.getExtension(packedFixed64Extension , 1));
- assertEqualsExactType(709 , message.getExtension(packedSfixed32Extension, 1));
- assertEqualsExactType(710L , message.getExtension(packedSfixed64Extension, 1));
- assertEqualsExactType(711F , message.getExtension(packedFloatExtension , 1));
- assertEqualsExactType(712D , message.getExtension(packedDoubleExtension , 1));
- assertEqualsExactType(false, message.getExtension(packedBoolExtension , 1));
- assertEqualsExactType(ForeignEnum.FOREIGN_BAZ,
- message.getExtension(packedEnumExtension, 1));
+ assertEqualsExactType(601, message.getExtension(packedInt32Extension, 0));
+ assertEqualsExactType(602L, message.getExtension(packedInt64Extension, 0));
+ assertEqualsExactType(603, message.getExtension(packedUint32Extension, 0));
+ assertEqualsExactType(604L, message.getExtension(packedUint64Extension, 0));
+ assertEqualsExactType(605, message.getExtension(packedSint32Extension, 0));
+ assertEqualsExactType(606L, message.getExtension(packedSint64Extension, 0));
+ assertEqualsExactType(607, message.getExtension(packedFixed32Extension, 0));
+ assertEqualsExactType(608L, message.getExtension(packedFixed64Extension, 0));
+ assertEqualsExactType(609, message.getExtension(packedSfixed32Extension, 0));
+ assertEqualsExactType(610L, message.getExtension(packedSfixed64Extension, 0));
+ assertEqualsExactType(611F, message.getExtension(packedFloatExtension, 0));
+ assertEqualsExactType(612D, message.getExtension(packedDoubleExtension, 0));
+ assertEqualsExactType(true, message.getExtension(packedBoolExtension, 0));
+ assertEqualsExactType(ForeignEnum.FOREIGN_BAR, message.getExtension(packedEnumExtension, 0));
+ assertEqualsExactType(701, message.getExtension(packedInt32Extension, 1));
+ assertEqualsExactType(702L, message.getExtension(packedInt64Extension, 1));
+ assertEqualsExactType(703, message.getExtension(packedUint32Extension, 1));
+ assertEqualsExactType(704L, message.getExtension(packedUint64Extension, 1));
+ assertEqualsExactType(705, message.getExtension(packedSint32Extension, 1));
+ assertEqualsExactType(706L, message.getExtension(packedSint64Extension, 1));
+ assertEqualsExactType(707, message.getExtension(packedFixed32Extension, 1));
+ assertEqualsExactType(708L, message.getExtension(packedFixed64Extension, 1));
+ assertEqualsExactType(709, message.getExtension(packedSfixed32Extension, 1));
+ assertEqualsExactType(710L, message.getExtension(packedSfixed64Extension, 1));
+ assertEqualsExactType(711F, message.getExtension(packedFloatExtension, 1));
+ assertEqualsExactType(712D, message.getExtension(packedDoubleExtension, 1));
+ assertEqualsExactType(false, message.getExtension(packedBoolExtension, 1));
+ assertEqualsExactType(ForeignEnum.FOREIGN_BAZ, message.getExtension(packedEnumExtension, 1));
}
// ===================================================================
// Lite extensions
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions}.
*/
- public static void assertAllExtensionsSet(
- TestAllExtensionsLiteOrBuilder message) {
- Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite ));
+ public static void assertAllExtensionsSet(TestAllExtensionsLiteOrBuilder message) {
+ Assert.assertTrue(message.hasExtension(optionalInt32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalInt64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalUint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalUint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalSint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalSint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalFixed32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalFixed64ExtensionLite));
Assert.assertTrue(message.hasExtension(optionalSfixed32ExtensionLite));
Assert.assertTrue(message.hasExtension(optionalSfixed64ExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalStringExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite ));
-
- Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite ));
- Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalFloatExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalDoubleExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalBoolExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalStringExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalBytesExtensionLite));
+
+ Assert.assertTrue(message.hasExtension(optionalGroupExtensionLite));
+ Assert.assertTrue(message.hasExtension(optionalNestedMessageExtensionLite));
Assert.assertTrue(message.hasExtension(optionalForeignMessageExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalImportMessageExtensionLite));
- Assert.assertTrue(message.getExtension(optionalGroupExtensionLite ).hasA());
- Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite ).hasBb());
+ Assert.assertTrue(message.getExtension(optionalGroupExtensionLite).hasA());
+ Assert.assertTrue(message.getExtension(optionalNestedMessageExtensionLite).hasBb());
Assert.assertTrue(message.getExtension(optionalForeignMessageExtensionLite).hasC());
- Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite ).hasD());
+ Assert.assertTrue(message.getExtension(optionalImportMessageExtensionLite).hasD());
- Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalNestedEnumExtensionLite));
Assert.assertTrue(message.hasExtension(optionalForeignEnumExtensionLite));
- Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(optionalImportEnumExtensionLite));
Assert.assertTrue(message.hasExtension(optionalStringPieceExtensionLite));
Assert.assertTrue(message.hasExtension(optionalCordExtensionLite));
- assertEqualsExactType(101 , message.getExtension(optionalInt32ExtensionLite ));
- assertEqualsExactType(102L , message.getExtension(optionalInt64ExtensionLite ));
- assertEqualsExactType(103 , message.getExtension(optionalUint32ExtensionLite ));
- assertEqualsExactType(104L , message.getExtension(optionalUint64ExtensionLite ));
- assertEqualsExactType(105 , message.getExtension(optionalSint32ExtensionLite ));
- assertEqualsExactType(106L , message.getExtension(optionalSint64ExtensionLite ));
- assertEqualsExactType(107 , message.getExtension(optionalFixed32ExtensionLite ));
- assertEqualsExactType(108L , message.getExtension(optionalFixed64ExtensionLite ));
- assertEqualsExactType(109 , message.getExtension(optionalSfixed32ExtensionLite));
- assertEqualsExactType(110L , message.getExtension(optionalSfixed64ExtensionLite));
- assertEqualsExactType(111F , message.getExtension(optionalFloatExtensionLite ));
- assertEqualsExactType(112D , message.getExtension(optionalDoubleExtensionLite ));
- assertEqualsExactType(true , message.getExtension(optionalBoolExtensionLite ));
- assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite ));
+ assertEqualsExactType(101, message.getExtension(optionalInt32ExtensionLite));
+ assertEqualsExactType(102L, message.getExtension(optionalInt64ExtensionLite));
+ assertEqualsExactType(103, message.getExtension(optionalUint32ExtensionLite));
+ assertEqualsExactType(104L, message.getExtension(optionalUint64ExtensionLite));
+ assertEqualsExactType(105, message.getExtension(optionalSint32ExtensionLite));
+ assertEqualsExactType(106L, message.getExtension(optionalSint64ExtensionLite));
+ assertEqualsExactType(107, message.getExtension(optionalFixed32ExtensionLite));
+ assertEqualsExactType(108L, message.getExtension(optionalFixed64ExtensionLite));
+ assertEqualsExactType(109, message.getExtension(optionalSfixed32ExtensionLite));
+ assertEqualsExactType(110L, message.getExtension(optionalSfixed64ExtensionLite));
+ assertEqualsExactType(111F, message.getExtension(optionalFloatExtensionLite));
+ assertEqualsExactType(112D, message.getExtension(optionalDoubleExtensionLite));
+ assertEqualsExactType(true, message.getExtension(optionalBoolExtensionLite));
+ assertEqualsExactType("115", message.getExtension(optionalStringExtensionLite));
assertEqualsExactType(toBytes("116"), message.getExtension(optionalBytesExtensionLite));
- assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite ).getA());
- assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite ).getBb());
+ assertEqualsExactType(117, message.getExtension(optionalGroupExtensionLite).getA());
+ assertEqualsExactType(118, message.getExtension(optionalNestedMessageExtensionLite).getBb());
assertEqualsExactType(119, message.getExtension(optionalForeignMessageExtensionLite).getC());
- assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite ).getD());
- assertEqualsExactType(126, message.getExtension(
- optionalPublicImportMessageExtensionLite).getE());
+ assertEqualsExactType(120, message.getExtension(optionalImportMessageExtensionLite).getD());
+ assertEqualsExactType(
+ 126, message.getExtension(optionalPublicImportMessageExtensionLite).getE());
assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtensionLite).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ,
- message.getExtension(optionalNestedEnumExtensionLite));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(optionalForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ,
- message.getExtension(optionalImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(optionalForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(optionalImportEnumExtensionLite));
assertEqualsExactType("124", message.getExtension(optionalStringPieceExtensionLite));
assertEqualsExactType("125", message.getExtension(optionalCordExtensionLite));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb());
- assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb());
+ assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtensionLite, 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(repeatedForeignEnumExtensionLite, 0));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(repeatedImportEnumExtensionLite, 0));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR,
+ message.getExtension(repeatedForeignEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0));
- assertEqualsExactType(301 , message.getExtension(repeatedInt32ExtensionLite , 1));
- assertEqualsExactType(302L , message.getExtension(repeatedInt64ExtensionLite , 1));
- assertEqualsExactType(303 , message.getExtension(repeatedUint32ExtensionLite , 1));
- assertEqualsExactType(304L , message.getExtension(repeatedUint64ExtensionLite , 1));
- assertEqualsExactType(305 , message.getExtension(repeatedSint32ExtensionLite , 1));
- assertEqualsExactType(306L , message.getExtension(repeatedSint64ExtensionLite , 1));
- assertEqualsExactType(307 , message.getExtension(repeatedFixed32ExtensionLite , 1));
- assertEqualsExactType(308L , message.getExtension(repeatedFixed64ExtensionLite , 1));
- assertEqualsExactType(309 , message.getExtension(repeatedSfixed32ExtensionLite, 1));
- assertEqualsExactType(310L , message.getExtension(repeatedSfixed64ExtensionLite, 1));
- assertEqualsExactType(311F , message.getExtension(repeatedFloatExtensionLite , 1));
- assertEqualsExactType(312D , message.getExtension(repeatedDoubleExtensionLite , 1));
- assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite , 1));
- assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite , 1));
+ assertEqualsExactType(301, message.getExtension(repeatedInt32ExtensionLite, 1));
+ assertEqualsExactType(302L, message.getExtension(repeatedInt64ExtensionLite, 1));
+ assertEqualsExactType(303, message.getExtension(repeatedUint32ExtensionLite, 1));
+ assertEqualsExactType(304L, message.getExtension(repeatedUint64ExtensionLite, 1));
+ assertEqualsExactType(305, message.getExtension(repeatedSint32ExtensionLite, 1));
+ assertEqualsExactType(306L, message.getExtension(repeatedSint64ExtensionLite, 1));
+ assertEqualsExactType(307, message.getExtension(repeatedFixed32ExtensionLite, 1));
+ assertEqualsExactType(308L, message.getExtension(repeatedFixed64ExtensionLite, 1));
+ assertEqualsExactType(309, message.getExtension(repeatedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(310L, message.getExtension(repeatedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(311F, message.getExtension(repeatedFloatExtensionLite, 1));
+ assertEqualsExactType(312D, message.getExtension(repeatedDoubleExtensionLite, 1));
+ assertEqualsExactType(false, message.getExtension(repeatedBoolExtensionLite, 1));
+ assertEqualsExactType("315", message.getExtension(repeatedStringExtensionLite, 1));
assertEqualsExactType(toBytes("316"), message.getExtension(repeatedBytesExtensionLite, 1));
- assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite ,1).getA());
- assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb());
- assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite,1).getC());
- assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite ,1).getD());
- assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb());
+ assertEqualsExactType(317, message.getExtension(repeatedGroupExtensionLite, 1).getA());
+ assertEqualsExactType(318, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb());
+ assertEqualsExactType(319, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC());
+ assertEqualsExactType(320, message.getExtension(repeatedImportMessageExtensionLite, 1).getD());
+ assertEqualsExactType(327, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAZ,
- message.getExtension(repeatedNestedEnumExtensionLite, 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(repeatedForeignEnumExtensionLite, 1));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAZ,
- message.getExtension(repeatedImportEnumExtensionLite, 1));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAZ, message.getExtension(repeatedNestedEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ,
+ message.getExtension(repeatedForeignEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAZ, message.getExtension(repeatedImportEnumExtensionLite, 1));
assertEqualsExactType("324", message.getExtension(repeatedStringPieceExtensionLite, 1));
assertEqualsExactType("325", message.getExtension(repeatedCordExtensionLite, 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultInt32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultInt64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultUint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultUint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultSint32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultSint64ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultFixed32ExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultFixed64ExtensionLite));
Assert.assertTrue(message.hasExtension(defaultSfixed32ExtensionLite));
Assert.assertTrue(message.hasExtension(defaultSfixed64ExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultStringExtensionLite ));
- Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultFloatExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultDoubleExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultBoolExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultStringExtensionLite));
+ Assert.assertTrue(message.hasExtension(defaultBytesExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultNestedEnumExtensionLite));
Assert.assertTrue(message.hasExtension(defaultForeignEnumExtensionLite));
- Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite ));
+ Assert.assertTrue(message.hasExtension(defaultImportEnumExtensionLite));
Assert.assertTrue(message.hasExtension(defaultStringPieceExtensionLite));
Assert.assertTrue(message.hasExtension(defaultCordExtensionLite));
- assertEqualsExactType(401 , message.getExtension(defaultInt32ExtensionLite ));
- assertEqualsExactType(402L , message.getExtension(defaultInt64ExtensionLite ));
- assertEqualsExactType(403 , message.getExtension(defaultUint32ExtensionLite ));
- assertEqualsExactType(404L , message.getExtension(defaultUint64ExtensionLite ));
- assertEqualsExactType(405 , message.getExtension(defaultSint32ExtensionLite ));
- assertEqualsExactType(406L , message.getExtension(defaultSint64ExtensionLite ));
- assertEqualsExactType(407 , message.getExtension(defaultFixed32ExtensionLite ));
- assertEqualsExactType(408L , message.getExtension(defaultFixed64ExtensionLite ));
- assertEqualsExactType(409 , message.getExtension(defaultSfixed32ExtensionLite));
- assertEqualsExactType(410L , message.getExtension(defaultSfixed64ExtensionLite));
- assertEqualsExactType(411F , message.getExtension(defaultFloatExtensionLite ));
- assertEqualsExactType(412D , message.getExtension(defaultDoubleExtensionLite ));
- assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite ));
- assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite ));
+ assertEqualsExactType(401, message.getExtension(defaultInt32ExtensionLite));
+ assertEqualsExactType(402L, message.getExtension(defaultInt64ExtensionLite));
+ assertEqualsExactType(403, message.getExtension(defaultUint32ExtensionLite));
+ assertEqualsExactType(404L, message.getExtension(defaultUint64ExtensionLite));
+ assertEqualsExactType(405, message.getExtension(defaultSint32ExtensionLite));
+ assertEqualsExactType(406L, message.getExtension(defaultSint64ExtensionLite));
+ assertEqualsExactType(407, message.getExtension(defaultFixed32ExtensionLite));
+ assertEqualsExactType(408L, message.getExtension(defaultFixed64ExtensionLite));
+ assertEqualsExactType(409, message.getExtension(defaultSfixed32ExtensionLite));
+ assertEqualsExactType(410L, message.getExtension(defaultSfixed64ExtensionLite));
+ assertEqualsExactType(411F, message.getExtension(defaultFloatExtensionLite));
+ assertEqualsExactType(412D, message.getExtension(defaultDoubleExtensionLite));
+ assertEqualsExactType(false, message.getExtension(defaultBoolExtensionLite));
+ assertEqualsExactType("415", message.getExtension(defaultStringExtensionLite));
assertEqualsExactType(toBytes("416"), message.getExtension(defaultBytesExtensionLite));
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(defaultNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(defaultForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(defaultImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(defaultNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(defaultForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(defaultImportEnumExtensionLite));
assertEqualsExactType("424", message.getExtension(defaultStringPieceExtensionLite));
assertEqualsExactType("425", message.getExtension(defaultCordExtensionLite));
@@ -2232,163 +2212,160 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are cleared, and that getting the extensions returns their
- * default values.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are
+ * cleared, and that getting the extensions returns their default values.
*/
- public static void assertExtensionsClear(
- TestAllExtensionsLiteOrBuilder message) {
+ public static void assertExtensionsClear(TestAllExtensionsLiteOrBuilder message) {
// hasBlah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalInt32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalInt64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalUint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalUint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalSint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalSint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalFixed32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalFixed64ExtensionLite));
Assert.assertFalse(message.hasExtension(optionalSfixed32ExtensionLite));
Assert.assertFalse(message.hasExtension(optionalSfixed64ExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalStringExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite ));
-
- Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite ));
- Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalFloatExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalDoubleExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalBoolExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalStringExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalBytesExtensionLite));
+
+ Assert.assertFalse(message.hasExtension(optionalGroupExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalNestedMessageExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalForeignMessageExtensionLite));
+ Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite));
Assert.assertFalse(message.hasExtension(optionalPublicImportMessageExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite));
Assert.assertFalse(message.hasExtension(optionalForeignEnumExtensionLite));
- Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(optionalImportEnumExtensionLite));
Assert.assertFalse(message.hasExtension(optionalStringPieceExtensionLite));
Assert.assertFalse(message.hasExtension(optionalCordExtensionLite));
// Optional fields without defaults are set to zero or something like it.
- assertEqualsExactType(0 , message.getExtension(optionalInt32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalInt64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalUint32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalUint64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalSint32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalSint64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalFixed32ExtensionLite ));
- assertEqualsExactType(0L , message.getExtension(optionalFixed64ExtensionLite ));
- assertEqualsExactType(0 , message.getExtension(optionalSfixed32ExtensionLite));
- assertEqualsExactType(0L , message.getExtension(optionalSfixed64ExtensionLite));
- assertEqualsExactType(0F , message.getExtension(optionalFloatExtensionLite ));
- assertEqualsExactType(0D , message.getExtension(optionalDoubleExtensionLite ));
- assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite ));
- assertEqualsExactType("" , message.getExtension(optionalStringExtensionLite ));
+ assertEqualsExactType(0, message.getExtension(optionalInt32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalInt64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalUint32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalUint64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalSint32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalSint64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalFixed32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalFixed64ExtensionLite));
+ assertEqualsExactType(0, message.getExtension(optionalSfixed32ExtensionLite));
+ assertEqualsExactType(0L, message.getExtension(optionalSfixed64ExtensionLite));
+ assertEqualsExactType(0F, message.getExtension(optionalFloatExtensionLite));
+ assertEqualsExactType(0D, message.getExtension(optionalDoubleExtensionLite));
+ assertEqualsExactType(false, message.getExtension(optionalBoolExtensionLite));
+ assertEqualsExactType("", message.getExtension(optionalStringExtensionLite));
assertEqualsExactType(ByteString.EMPTY, message.getExtension(optionalBytesExtensionLite));
// Embedded messages should also be clear.
- Assert.assertFalse(message.getExtension(optionalGroupExtensionLite ).hasA());
- Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite ).hasBb());
- Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite ).hasC());
- Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite ).hasD());
+ Assert.assertFalse(message.getExtension(optionalGroupExtensionLite).hasA());
+ Assert.assertFalse(message.getExtension(optionalNestedMessageExtensionLite).hasBb());
+ Assert.assertFalse(message.getExtension(optionalForeignMessageExtensionLite).hasC());
+ Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite).hasD());
Assert.assertFalse(message.getExtension(optionalPublicImportMessageExtensionLite).hasE());
- Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite ).hasBb());
+ Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite).hasBb());
- assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite ).getA());
- assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite).getA());
+ assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite).getBb());
assertEqualsExactType(0, message.getExtension(optionalForeignMessageExtensionLite).getC());
- assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite ).getD());
- assertEqualsExactType(0, message.getExtension(
- optionalPublicImportMessageExtensionLite).getE());
- assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite ).getBb());
+ assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite).getD());
+ assertEqualsExactType(0, message.getExtension(optionalPublicImportMessageExtensionLite).getE());
+ assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite).getBb());
// Enums without defaults are set to the first value in the enum.
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(optionalNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(optionalForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(optionalImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(optionalNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO, message.getExtension(optionalForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(optionalImportEnumExtensionLite));
assertEqualsExactType("", message.getExtension(optionalStringPieceExtensionLite));
assertEqualsExactType("", message.getExtension(optionalCordExtensionLite));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(0, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(0, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(0, message.getExtensionCount(repeatedCordExtensionLite));
// hasBlah() should also be false for all default fields.
- Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultInt32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultInt64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultUint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultUint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultSint32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultSint64ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultFixed32ExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultFixed64ExtensionLite));
Assert.assertFalse(message.hasExtension(defaultSfixed32ExtensionLite));
Assert.assertFalse(message.hasExtension(defaultSfixed64ExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultStringExtensionLite ));
- Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultFloatExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultDoubleExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultBoolExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultStringExtensionLite));
+ Assert.assertFalse(message.hasExtension(defaultBytesExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultNestedEnumExtensionLite));
Assert.assertFalse(message.hasExtension(defaultForeignEnumExtensionLite));
- Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite ));
+ Assert.assertFalse(message.hasExtension(defaultImportEnumExtensionLite));
Assert.assertFalse(message.hasExtension(defaultStringPieceExtensionLite));
Assert.assertFalse(message.hasExtension(defaultCordExtensionLite));
// Fields with defaults have their default values (duh).
- assertEqualsExactType( 41 , message.getExtension(defaultInt32ExtensionLite ));
- assertEqualsExactType( 42L , message.getExtension(defaultInt64ExtensionLite ));
- assertEqualsExactType( 43 , message.getExtension(defaultUint32ExtensionLite ));
- assertEqualsExactType( 44L , message.getExtension(defaultUint64ExtensionLite ));
- assertEqualsExactType(-45 , message.getExtension(defaultSint32ExtensionLite ));
- assertEqualsExactType( 46L , message.getExtension(defaultSint64ExtensionLite ));
- assertEqualsExactType( 47 , message.getExtension(defaultFixed32ExtensionLite ));
- assertEqualsExactType( 48L , message.getExtension(defaultFixed64ExtensionLite ));
- assertEqualsExactType( 49 , message.getExtension(defaultSfixed32ExtensionLite));
- assertEqualsExactType(-50L , message.getExtension(defaultSfixed64ExtensionLite));
- assertEqualsExactType( 51.5F , message.getExtension(defaultFloatExtensionLite ));
- assertEqualsExactType( 52e3D , message.getExtension(defaultDoubleExtensionLite ));
- assertEqualsExactType(true , message.getExtension(defaultBoolExtensionLite ));
- assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite ));
+ assertEqualsExactType(41, message.getExtension(defaultInt32ExtensionLite));
+ assertEqualsExactType(42L, message.getExtension(defaultInt64ExtensionLite));
+ assertEqualsExactType(43, message.getExtension(defaultUint32ExtensionLite));
+ assertEqualsExactType(44L, message.getExtension(defaultUint64ExtensionLite));
+ assertEqualsExactType(-45, message.getExtension(defaultSint32ExtensionLite));
+ assertEqualsExactType(46L, message.getExtension(defaultSint64ExtensionLite));
+ assertEqualsExactType(47, message.getExtension(defaultFixed32ExtensionLite));
+ assertEqualsExactType(48L, message.getExtension(defaultFixed64ExtensionLite));
+ assertEqualsExactType(49, message.getExtension(defaultSfixed32ExtensionLite));
+ assertEqualsExactType(-50L, message.getExtension(defaultSfixed64ExtensionLite));
+ assertEqualsExactType(51.5F, message.getExtension(defaultFloatExtensionLite));
+ assertEqualsExactType(52e3D, message.getExtension(defaultDoubleExtensionLite));
+ assertEqualsExactType(true, message.getExtension(defaultBoolExtensionLite));
+ assertEqualsExactType("hello", message.getExtension(defaultStringExtensionLite));
assertEqualsExactType(toBytes("world"), message.getExtension(defaultBytesExtensionLite));
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(defaultNestedEnumExtensionLite ));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(defaultForeignEnumExtensionLite));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(defaultImportEnumExtensionLite));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(defaultNestedEnumExtensionLite));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(defaultForeignEnumExtensionLite));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(defaultImportEnumExtensionLite));
assertEqualsExactType("abc", message.getExtension(defaultStringPieceExtensionLite));
assertEqualsExactType("123", message.getExtension(defaultCordExtensionLite));
@@ -2402,200 +2379,229 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all extensions of
- * {@code message} are set to the values assigned by {@code setAllExtensions}
- * followed by {@code modifyRepeatedExtensions}.
+ * Assert (using {@code junit.framework.Assert}} that all extensions of {@code message} are set to
+ * the values assigned by {@code setAllExtensions} followed by {@code modifyRepeatedExtensions}.
*/
- public static void assertRepeatedExtensionsModified(
- TestAllExtensionsLiteOrBuilder message) {
+ public static void assertRepeatedExtensionsModified(TestAllExtensionsLiteOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite ));
-
- Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBoolExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedStringExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedBytesExtensionLite));
+
+ Assert.assertEquals(2, message.getExtensionCount(repeatedGroupExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedMessageExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedForeignMessageExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedLazyMessageExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedNestedEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedForeignEnumExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(repeatedImportEnumExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedStringPieceExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(repeatedCordExtensionLite));
- assertEqualsExactType(201 , message.getExtension(repeatedInt32ExtensionLite , 0));
- assertEqualsExactType(202L , message.getExtension(repeatedInt64ExtensionLite , 0));
- assertEqualsExactType(203 , message.getExtension(repeatedUint32ExtensionLite , 0));
- assertEqualsExactType(204L , message.getExtension(repeatedUint64ExtensionLite , 0));
- assertEqualsExactType(205 , message.getExtension(repeatedSint32ExtensionLite , 0));
- assertEqualsExactType(206L , message.getExtension(repeatedSint64ExtensionLite , 0));
- assertEqualsExactType(207 , message.getExtension(repeatedFixed32ExtensionLite , 0));
- assertEqualsExactType(208L , message.getExtension(repeatedFixed64ExtensionLite , 0));
- assertEqualsExactType(209 , message.getExtension(repeatedSfixed32ExtensionLite, 0));
- assertEqualsExactType(210L , message.getExtension(repeatedSfixed64ExtensionLite, 0));
- assertEqualsExactType(211F , message.getExtension(repeatedFloatExtensionLite , 0));
- assertEqualsExactType(212D , message.getExtension(repeatedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 0));
- assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite , 0));
+ assertEqualsExactType(201, message.getExtension(repeatedInt32ExtensionLite, 0));
+ assertEqualsExactType(202L, message.getExtension(repeatedInt64ExtensionLite, 0));
+ assertEqualsExactType(203, message.getExtension(repeatedUint32ExtensionLite, 0));
+ assertEqualsExactType(204L, message.getExtension(repeatedUint64ExtensionLite, 0));
+ assertEqualsExactType(205, message.getExtension(repeatedSint32ExtensionLite, 0));
+ assertEqualsExactType(206L, message.getExtension(repeatedSint64ExtensionLite, 0));
+ assertEqualsExactType(207, message.getExtension(repeatedFixed32ExtensionLite, 0));
+ assertEqualsExactType(208L, message.getExtension(repeatedFixed64ExtensionLite, 0));
+ assertEqualsExactType(209, message.getExtension(repeatedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(210L, message.getExtension(repeatedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(211F, message.getExtension(repeatedFloatExtensionLite, 0));
+ assertEqualsExactType(212D, message.getExtension(repeatedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 0));
+ assertEqualsExactType("215", message.getExtension(repeatedStringExtensionLite, 0));
assertEqualsExactType(toBytes("216"), message.getExtension(repeatedBytesExtensionLite, 0));
- assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite ,0).getA());
- assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite ,0).getBb());
- assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite,0).getC());
- assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite ,0).getD());
- assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite ,0).getBb());
+ assertEqualsExactType(217, message.getExtension(repeatedGroupExtensionLite, 0).getA());
+ assertEqualsExactType(218, message.getExtension(repeatedNestedMessageExtensionLite, 0).getBb());
+ assertEqualsExactType(219, message.getExtension(repeatedForeignMessageExtensionLite, 0).getC());
+ assertEqualsExactType(220, message.getExtension(repeatedImportMessageExtensionLite, 0).getD());
+ assertEqualsExactType(227, message.getExtension(repeatedLazyMessageExtensionLite, 0).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.BAR,
- message.getExtension(repeatedNestedEnumExtensionLite, 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(repeatedForeignEnumExtensionLite, 0));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_BAR,
- message.getExtension(repeatedImportEnumExtensionLite, 0));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.BAR, message.getExtension(repeatedNestedEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR,
+ message.getExtension(repeatedForeignEnumExtensionLite, 0));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_BAR, message.getExtension(repeatedImportEnumExtensionLite, 0));
assertEqualsExactType("224", message.getExtension(repeatedStringPieceExtensionLite, 0));
assertEqualsExactType("225", message.getExtension(repeatedCordExtensionLite, 0));
// Actually verify the second (modified) elements now.
- assertEqualsExactType(501 , message.getExtension(repeatedInt32ExtensionLite , 1));
- assertEqualsExactType(502L , message.getExtension(repeatedInt64ExtensionLite , 1));
- assertEqualsExactType(503 , message.getExtension(repeatedUint32ExtensionLite , 1));
- assertEqualsExactType(504L , message.getExtension(repeatedUint64ExtensionLite , 1));
- assertEqualsExactType(505 , message.getExtension(repeatedSint32ExtensionLite , 1));
- assertEqualsExactType(506L , message.getExtension(repeatedSint64ExtensionLite , 1));
- assertEqualsExactType(507 , message.getExtension(repeatedFixed32ExtensionLite , 1));
- assertEqualsExactType(508L , message.getExtension(repeatedFixed64ExtensionLite , 1));
- assertEqualsExactType(509 , message.getExtension(repeatedSfixed32ExtensionLite, 1));
- assertEqualsExactType(510L , message.getExtension(repeatedSfixed64ExtensionLite, 1));
- assertEqualsExactType(511F , message.getExtension(repeatedFloatExtensionLite , 1));
- assertEqualsExactType(512D , message.getExtension(repeatedDoubleExtensionLite , 1));
- assertEqualsExactType(true , message.getExtension(repeatedBoolExtensionLite , 1));
- assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite , 1));
+ assertEqualsExactType(501, message.getExtension(repeatedInt32ExtensionLite, 1));
+ assertEqualsExactType(502L, message.getExtension(repeatedInt64ExtensionLite, 1));
+ assertEqualsExactType(503, message.getExtension(repeatedUint32ExtensionLite, 1));
+ assertEqualsExactType(504L, message.getExtension(repeatedUint64ExtensionLite, 1));
+ assertEqualsExactType(505, message.getExtension(repeatedSint32ExtensionLite, 1));
+ assertEqualsExactType(506L, message.getExtension(repeatedSint64ExtensionLite, 1));
+ assertEqualsExactType(507, message.getExtension(repeatedFixed32ExtensionLite, 1));
+ assertEqualsExactType(508L, message.getExtension(repeatedFixed64ExtensionLite, 1));
+ assertEqualsExactType(509, message.getExtension(repeatedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(510L, message.getExtension(repeatedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(511F, message.getExtension(repeatedFloatExtensionLite, 1));
+ assertEqualsExactType(512D, message.getExtension(repeatedDoubleExtensionLite, 1));
+ assertEqualsExactType(true, message.getExtension(repeatedBoolExtensionLite, 1));
+ assertEqualsExactType("515", message.getExtension(repeatedStringExtensionLite, 1));
assertEqualsExactType(toBytes("516"), message.getExtension(repeatedBytesExtensionLite, 1));
- assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite ,1).getA());
- assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite ,1).getBb());
- assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite,1).getC());
- assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite ,1).getD());
- assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite ,1).getBb());
+ assertEqualsExactType(517, message.getExtension(repeatedGroupExtensionLite, 1).getA());
+ assertEqualsExactType(518, message.getExtension(repeatedNestedMessageExtensionLite, 1).getBb());
+ assertEqualsExactType(519, message.getExtension(repeatedForeignMessageExtensionLite, 1).getC());
+ assertEqualsExactType(520, message.getExtension(repeatedImportMessageExtensionLite, 1).getD());
+ assertEqualsExactType(527, message.getExtension(repeatedLazyMessageExtensionLite, 1).getBb());
- assertEqualsExactType(TestAllTypesLite.NestedEnum.FOO,
- message.getExtension(repeatedNestedEnumExtensionLite, 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_FOO,
- message.getExtension(repeatedForeignEnumExtensionLite, 1));
- assertEqualsExactType(ImportEnumLite.IMPORT_LITE_FOO,
- message.getExtension(repeatedImportEnumExtensionLite, 1));
+ assertEqualsExactType(
+ TestAllTypesLite.NestedEnum.FOO, message.getExtension(repeatedNestedEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_FOO,
+ message.getExtension(repeatedForeignEnumExtensionLite, 1));
+ assertEqualsExactType(
+ ImportEnumLite.IMPORT_LITE_FOO, message.getExtension(repeatedImportEnumExtensionLite, 1));
assertEqualsExactType("524", message.getExtension(repeatedStringPieceExtensionLite, 1));
assertEqualsExactType("525", message.getExtension(repeatedCordExtensionLite, 1));
}
public static void assertPackedExtensionsSet(TestPackedExtensionsLite message) {
- Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedInt64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedUint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedSint64ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed32ExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedFixed64ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed32ExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedSfixed64ExtensionLite));
- Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite ));
- Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite ));
+ Assert.assertEquals(2, message.getExtensionCount(packedFloatExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedDoubleExtensionLite));
+ Assert.assertEquals(2, message.getExtensionCount(packedBoolExtensionLite));
Assert.assertEquals(2, message.getExtensionCount(packedEnumExtensionLite));
- assertEqualsExactType(601 , message.getExtension(packedInt32ExtensionLite , 0));
- assertEqualsExactType(602L , message.getExtension(packedInt64ExtensionLite , 0));
- assertEqualsExactType(603 , message.getExtension(packedUint32ExtensionLite , 0));
- assertEqualsExactType(604L , message.getExtension(packedUint64ExtensionLite , 0));
- assertEqualsExactType(605 , message.getExtension(packedSint32ExtensionLite , 0));
- assertEqualsExactType(606L , message.getExtension(packedSint64ExtensionLite , 0));
- assertEqualsExactType(607 , message.getExtension(packedFixed32ExtensionLite , 0));
- assertEqualsExactType(608L , message.getExtension(packedFixed64ExtensionLite , 0));
- assertEqualsExactType(609 , message.getExtension(packedSfixed32ExtensionLite, 0));
- assertEqualsExactType(610L , message.getExtension(packedSfixed64ExtensionLite, 0));
- assertEqualsExactType(611F , message.getExtension(packedFloatExtensionLite , 0));
- assertEqualsExactType(612D , message.getExtension(packedDoubleExtensionLite , 0));
- assertEqualsExactType(true , message.getExtension(packedBoolExtensionLite , 0));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAR,
- message.getExtension(packedEnumExtensionLite, 0));
- assertEqualsExactType(701 , message.getExtension(packedInt32ExtensionLite , 1));
- assertEqualsExactType(702L , message.getExtension(packedInt64ExtensionLite , 1));
- assertEqualsExactType(703 , message.getExtension(packedUint32ExtensionLite , 1));
- assertEqualsExactType(704L , message.getExtension(packedUint64ExtensionLite , 1));
- assertEqualsExactType(705 , message.getExtension(packedSint32ExtensionLite , 1));
- assertEqualsExactType(706L , message.getExtension(packedSint64ExtensionLite , 1));
- assertEqualsExactType(707 , message.getExtension(packedFixed32ExtensionLite , 1));
- assertEqualsExactType(708L , message.getExtension(packedFixed64ExtensionLite , 1));
- assertEqualsExactType(709 , message.getExtension(packedSfixed32ExtensionLite, 1));
- assertEqualsExactType(710L , message.getExtension(packedSfixed64ExtensionLite, 1));
- assertEqualsExactType(711F , message.getExtension(packedFloatExtensionLite , 1));
- assertEqualsExactType(712D , message.getExtension(packedDoubleExtensionLite , 1));
- assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite , 1));
- assertEqualsExactType(ForeignEnumLite.FOREIGN_LITE_BAZ,
- message.getExtension(packedEnumExtensionLite, 1));
+ assertEqualsExactType(601, message.getExtension(packedInt32ExtensionLite, 0));
+ assertEqualsExactType(602L, message.getExtension(packedInt64ExtensionLite, 0));
+ assertEqualsExactType(603, message.getExtension(packedUint32ExtensionLite, 0));
+ assertEqualsExactType(604L, message.getExtension(packedUint64ExtensionLite, 0));
+ assertEqualsExactType(605, message.getExtension(packedSint32ExtensionLite, 0));
+ assertEqualsExactType(606L, message.getExtension(packedSint64ExtensionLite, 0));
+ assertEqualsExactType(607, message.getExtension(packedFixed32ExtensionLite, 0));
+ assertEqualsExactType(608L, message.getExtension(packedFixed64ExtensionLite, 0));
+ assertEqualsExactType(609, message.getExtension(packedSfixed32ExtensionLite, 0));
+ assertEqualsExactType(610L, message.getExtension(packedSfixed64ExtensionLite, 0));
+ assertEqualsExactType(611F, message.getExtension(packedFloatExtensionLite, 0));
+ assertEqualsExactType(612D, message.getExtension(packedDoubleExtensionLite, 0));
+ assertEqualsExactType(true, message.getExtension(packedBoolExtensionLite, 0));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAR, message.getExtension(packedEnumExtensionLite, 0));
+ assertEqualsExactType(701, message.getExtension(packedInt32ExtensionLite, 1));
+ assertEqualsExactType(702L, message.getExtension(packedInt64ExtensionLite, 1));
+ assertEqualsExactType(703, message.getExtension(packedUint32ExtensionLite, 1));
+ assertEqualsExactType(704L, message.getExtension(packedUint64ExtensionLite, 1));
+ assertEqualsExactType(705, message.getExtension(packedSint32ExtensionLite, 1));
+ assertEqualsExactType(706L, message.getExtension(packedSint64ExtensionLite, 1));
+ assertEqualsExactType(707, message.getExtension(packedFixed32ExtensionLite, 1));
+ assertEqualsExactType(708L, message.getExtension(packedFixed64ExtensionLite, 1));
+ assertEqualsExactType(709, message.getExtension(packedSfixed32ExtensionLite, 1));
+ assertEqualsExactType(710L, message.getExtension(packedSfixed64ExtensionLite, 1));
+ assertEqualsExactType(711F, message.getExtension(packedFloatExtensionLite, 1));
+ assertEqualsExactType(712D, message.getExtension(packedDoubleExtensionLite, 1));
+ assertEqualsExactType(false, message.getExtension(packedBoolExtensionLite, 1));
+ assertEqualsExactType(
+ ForeignEnumLite.FOREIGN_LITE_BAZ, message.getExtension(packedEnumExtensionLite, 1));
}
// ===================================================================
// oneof
public static void setOneof(TestOneof2.Builder message) {
- message.setFooLazyMessage(
- TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build());
+ message.setFooLazyMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build());
message.setBarString("101");
message.setBazInt(102);
message.setBazString("103");
}
public static void assertOneofSet(TestOneof2 message) {
- Assert.assertTrue(message.hasFooLazyMessage ());
+ Assert.assertTrue(message.hasFooLazyMessage());
Assert.assertTrue(message.getFooLazyMessage().hasQuxInt());
Assert.assertTrue(message.hasBarString());
- Assert.assertTrue(message.hasBazInt ());
+ Assert.assertTrue(message.hasBazInt());
Assert.assertTrue(message.hasBazString());
- Assert.assertEquals(100 , message.getFooLazyMessage().getQuxInt());
- Assert.assertEquals("101", message.getBarString ());
- Assert.assertEquals(102 , message.getBazInt ());
- Assert.assertEquals("103", message.getBazString ());
+ Assert.assertEquals(100, message.getFooLazyMessage().getQuxInt());
+ Assert.assertEquals("101", message.getBarString());
+ Assert.assertEquals(102, message.getBazInt());
+ Assert.assertEquals("103", message.getBazString());
}
public static void assertAtMostOneFieldSetOneof(TestOneof2 message) {
int count = 0;
- if (message.hasFooInt()) { ++count; }
- if (message.hasFooString()) { ++count; }
- if (message.hasFooCord()) { ++count; }
- if (message.hasFooStringPiece()) { ++count; }
- if (message.hasFooBytes()) { ++count; }
- if (message.hasFooEnum()) { ++count; }
- if (message.hasFooMessage()) { ++count; }
- if (message.hasFooGroup()) { ++count; }
- if (message.hasFooLazyMessage()) { ++count; }
+ if (message.hasFooInt()) {
+ ++count;
+ }
+ if (message.hasFooString()) {
+ ++count;
+ }
+ if (message.hasFooCord()) {
+ ++count;
+ }
+ if (message.hasFooStringPiece()) {
+ ++count;
+ }
+ if (message.hasFooBytes()) {
+ ++count;
+ }
+ if (message.hasFooEnum()) {
+ ++count;
+ }
+ if (message.hasFooMessage()) {
+ ++count;
+ }
+ if (message.hasFooGroup()) {
+ ++count;
+ }
+ if (message.hasFooLazyMessage()) {
+ ++count;
+ }
Assert.assertTrue(count <= 1);
count = 0;
- if (message.hasBarInt()) { ++count; }
- if (message.hasBarString()) { ++count; }
- if (message.hasBarCord()) { ++count; }
- if (message.hasBarStringPiece()) { ++count; }
- if (message.hasBarBytes()) { ++count; }
- if (message.hasBarEnum()) { ++count; }
+ if (message.hasBarInt()) {
+ ++count;
+ }
+ if (message.hasBarString()) {
+ ++count;
+ }
+ if (message.hasBarCord()) {
+ ++count;
+ }
+ if (message.hasBarStringPiece()) {
+ ++count;
+ }
+ if (message.hasBarBytes()) {
+ ++count;
+ }
+ if (message.hasBarEnum()) {
+ ++count;
+ }
Assert.assertTrue(count <= 1);
switch (message.getFooCase()) {
@@ -2634,11 +2640,11 @@ public final class TestUtil {
}
// =================================================================
+ // BEGIN FULL-RUNTIME
/**
- * Performs the same things that the methods of {@code TestUtil} do, but
- * via the reflection interface. This is its own class because it needs
- * to know what descriptor to use.
+ * Performs the same things that the methods of {@code TestUtil} do, but via the reflection
+ * interface. This is its own class because it needs to know what descriptor to use.
*/
public static class ReflectionTester {
private final Descriptors.Descriptor baseDescriptor;
@@ -2677,20 +2683,16 @@ public final class TestUtil {
private final Descriptors.EnumValueDescriptor importBaz;
/**
- * Construct a {@code ReflectionTester} that will expect messages using
- * the given descriptor.
+ * Construct a {@code ReflectionTester} that will expect messages using the given descriptor.
*
- * Normally {@code baseDescriptor} should be a descriptor for the type
- * {@code TestAllTypes}, defined in
- * {@code google/protobuf/unittest.proto}. However, if
- * {@code extensionRegistry} is non-null, then {@code baseDescriptor} should
- * be for {@code TestAllExtensions} instead, and instead of reading and
- * writing normal fields, the tester will read and write extensions.
- * All of {@code TestAllExtensions}' extensions must be registered in the
- * registry.
+ * <p>Normally {@code baseDescriptor} should be a descriptor for the type {@code TestAllTypes},
+ * defined in {@code google/protobuf/unittest.proto}. However, if {@code extensionRegistry}
+ * is non-null, then {@code baseDescriptor} should be for {@code TestAllExtensions} instead, and
+ * instead of reading and writing normal fields, the tester will read and write extensions. All
+ * of {@code TestAllExtensions}' extensions must be registered in the registry.
*/
- public ReflectionTester(Descriptors.Descriptor baseDescriptor,
- ExtensionRegistry extensionRegistry) {
+ public ReflectionTester(
+ Descriptors.Descriptor baseDescriptor, ExtensionRegistry extensionRegistry) {
this.baseDescriptor = baseDescriptor;
this.extensionRegistry = extensionRegistry;
@@ -2711,39 +2713,34 @@ public final class TestUtil {
// Use testAllTypes, rather than baseDescriptor, to allow
// initialization using TestPackedTypes descriptors. These objects
// won't be used by the methods for packed fields.
- this.optionalGroup =
- testAllTypes.findNestedTypeByName("OptionalGroup");
- this.repeatedGroup =
- testAllTypes.findNestedTypeByName("RepeatedGroup");
+ this.optionalGroup = testAllTypes.findNestedTypeByName("OptionalGroup");
+ this.repeatedGroup = testAllTypes.findNestedTypeByName("RepeatedGroup");
} else {
- this.optionalGroup =
- file.findMessageTypeByName("OptionalGroup_extension");
- this.repeatedGroup =
- file.findMessageTypeByName("RepeatedGroup_extension");
+ this.optionalGroup = file.findMessageTypeByName("OptionalGroup_extension");
+ this.repeatedGroup = file.findMessageTypeByName("RepeatedGroup_extension");
}
this.nestedMessage = testAllTypes.findNestedTypeByName("NestedMessage");
this.foreignMessage = file.findMessageTypeByName("ForeignMessage");
this.importMessage = importFile.findMessageTypeByName("ImportMessage");
- this.publicImportMessage = publicImportFile.findMessageTypeByName(
- "PublicImportMessage");
+ this.publicImportMessage = publicImportFile.findMessageTypeByName("PublicImportMessage");
this.nestedEnum = testAllTypes.findEnumTypeByName("NestedEnum");
this.foreignEnum = file.findEnumTypeByName("ForeignEnum");
this.importEnum = importFile.findEnumTypeByName("ImportEnum");
- Assert.assertNotNull(optionalGroup );
- Assert.assertNotNull(repeatedGroup );
- Assert.assertNotNull(nestedMessage );
+ Assert.assertNotNull(optionalGroup);
+ Assert.assertNotNull(repeatedGroup);
+ Assert.assertNotNull(nestedMessage);
Assert.assertNotNull(foreignMessage);
- Assert.assertNotNull(importMessage );
- Assert.assertNotNull(nestedEnum );
- Assert.assertNotNull(foreignEnum );
- Assert.assertNotNull(importEnum );
+ Assert.assertNotNull(importMessage);
+ Assert.assertNotNull(nestedEnum);
+ Assert.assertNotNull(foreignEnum);
+ Assert.assertNotNull(importEnum);
- this.nestedB = nestedMessage .findFieldByName("bb");
+ this.nestedB = nestedMessage.findFieldByName("bb");
this.foreignC = foreignMessage.findFieldByName("c");
- this.importD = importMessage .findFieldByName("d");
- this.importE = publicImportMessage.findFieldByName("e");
+ this.importD = importMessage.findFieldByName("d");
+ this.importE = publicImportMessage.findFieldByName("e");
this.nestedFoo = nestedEnum.findValueByName("FOO");
this.nestedBar = nestedEnum.findValueByName("BAR");
this.nestedBaz = nestedEnum.findValueByName("BAZ");
@@ -2757,26 +2754,24 @@ public final class TestUtil {
this.groupA = optionalGroup.findFieldByName("a");
this.repeatedGroupA = repeatedGroup.findFieldByName("a");
- Assert.assertNotNull(groupA );
+ Assert.assertNotNull(groupA);
Assert.assertNotNull(repeatedGroupA);
- Assert.assertNotNull(nestedB );
- Assert.assertNotNull(foreignC );
- Assert.assertNotNull(importD );
- Assert.assertNotNull(importE );
- Assert.assertNotNull(nestedFoo );
- Assert.assertNotNull(nestedBar );
- Assert.assertNotNull(nestedBaz );
- Assert.assertNotNull(foreignFoo );
- Assert.assertNotNull(foreignBar );
- Assert.assertNotNull(foreignBaz );
- Assert.assertNotNull(importFoo );
- Assert.assertNotNull(importBar );
- Assert.assertNotNull(importBaz );
+ Assert.assertNotNull(nestedB);
+ Assert.assertNotNull(foreignC);
+ Assert.assertNotNull(importD);
+ Assert.assertNotNull(importE);
+ Assert.assertNotNull(nestedFoo);
+ Assert.assertNotNull(nestedBar);
+ Assert.assertNotNull(nestedBaz);
+ Assert.assertNotNull(foreignFoo);
+ Assert.assertNotNull(foreignBar);
+ Assert.assertNotNull(foreignBaz);
+ Assert.assertNotNull(importFoo);
+ Assert.assertNotNull(importBar);
+ Assert.assertNotNull(importBaz);
}
- /**
- * Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes.
- */
+ /** Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. */
private Descriptors.FieldDescriptor f(String name) {
Descriptors.FieldDescriptor result;
if (extensionRegistry == null) {
@@ -2789,9 +2784,8 @@ public final class TestUtil {
}
/**
- * Calls {@code parent.newBuilderForField()} or uses the
- * {@code ExtensionRegistry} to find an appropriate builder, depending
- * on what type is being tested.
+ * Calls {@code parent.newBuilderForField()} or uses the {@code ExtensionRegistry} to find an
+ * appropriate builder, depending on what type is being tested.
*/
private Message.Builder newBuilderForField(
Message.Builder parent, Descriptors.FieldDescriptor field) {
@@ -2799,8 +2793,8 @@ public final class TestUtil {
return parent.newBuilderForField(field);
} else {
ExtensionRegistry.ExtensionInfo extension =
- extensionRegistry.findImmutableExtensionByNumber(
- field.getContainingType(), field.getNumber());
+ extensionRegistry.findImmutableExtensionByNumber(
+ field.getContainingType(), field.getNumber());
Assert.assertNotNull(extension);
Assert.assertNotNull(extension.defaultInstance);
return extension.defaultInstance.newBuilderForType();
@@ -2810,210 +2804,223 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllFieldsSet()}, using the {@link Message.Builder}
- * reflection interface.
+ * Set every field of {@code message} to the values expected by {@code assertAllFieldsSet()},
+ * using the {@link Message.Builder} reflection interface.
*/
void setAllFieldsViaReflection(Message.Builder message) {
- message.setField(f("optional_int32" ), 101 );
- message.setField(f("optional_int64" ), 102L);
- message.setField(f("optional_uint32" ), 103 );
- message.setField(f("optional_uint64" ), 104L);
- message.setField(f("optional_sint32" ), 105 );
- message.setField(f("optional_sint64" ), 106L);
- message.setField(f("optional_fixed32" ), 107 );
- message.setField(f("optional_fixed64" ), 108L);
- message.setField(f("optional_sfixed32"), 109 );
+ message.setField(f("optional_int32"), 101);
+ message.setField(f("optional_int64"), 102L);
+ message.setField(f("optional_uint32"), 103);
+ message.setField(f("optional_uint64"), 104L);
+ message.setField(f("optional_sint32"), 105);
+ message.setField(f("optional_sint64"), 106L);
+ message.setField(f("optional_fixed32"), 107);
+ message.setField(f("optional_fixed64"), 108L);
+ message.setField(f("optional_sfixed32"), 109);
message.setField(f("optional_sfixed64"), 110L);
- message.setField(f("optional_float" ), 111F);
- message.setField(f("optional_double" ), 112D);
- message.setField(f("optional_bool" ), true);
- message.setField(f("optional_string" ), "115");
- message.setField(f("optional_bytes" ), toBytes("116"));
-
- message.setField(f("optionalgroup"),
- newBuilderForField(message, f("optionalgroup"))
- .setField(groupA, 117).build());
- message.setField(f("optional_nested_message"),
- newBuilderForField(message, f("optional_nested_message"))
- .setField(nestedB, 118).build());
- message.setField(f("optional_foreign_message"),
- newBuilderForField(message, f("optional_foreign_message"))
- .setField(foreignC, 119).build());
- message.setField(f("optional_import_message"),
- newBuilderForField(message, f("optional_import_message"))
- .setField(importD, 120).build());
- message.setField(f("optional_public_import_message"),
- newBuilderForField(message, f("optional_public_import_message"))
- .setField(importE, 126).build());
- message.setField(f("optional_lazy_message"),
- newBuilderForField(message, f("optional_lazy_message"))
- .setField(nestedB, 127).build());
-
- message.setField(f("optional_nested_enum" ), nestedBaz);
+ message.setField(f("optional_float"), 111F);
+ message.setField(f("optional_double"), 112D);
+ message.setField(f("optional_bool"), true);
+ message.setField(f("optional_string"), "115");
+ message.setField(f("optional_bytes"), toBytes("116"));
+
+ message.setField(
+ f("optionalgroup"),
+ newBuilderForField(message, f("optionalgroup")).setField(groupA, 117).build());
+ message.setField(
+ f("optional_nested_message"),
+ newBuilderForField(message, f("optional_nested_message")).setField(nestedB, 118).build());
+ message.setField(
+ f("optional_foreign_message"),
+ newBuilderForField(message, f("optional_foreign_message"))
+ .setField(foreignC, 119)
+ .build());
+ message.setField(
+ f("optional_import_message"),
+ newBuilderForField(message, f("optional_import_message")).setField(importD, 120).build());
+ message.setField(
+ f("optional_public_import_message"),
+ newBuilderForField(message, f("optional_public_import_message"))
+ .setField(importE, 126)
+ .build());
+ message.setField(
+ f("optional_lazy_message"),
+ newBuilderForField(message, f("optional_lazy_message")).setField(nestedB, 127).build());
+
+ message.setField(f("optional_nested_enum"), nestedBaz);
message.setField(f("optional_foreign_enum"), foreignBaz);
- message.setField(f("optional_import_enum" ), importBaz);
+ message.setField(f("optional_import_enum"), importBaz);
- message.setField(f("optional_string_piece" ), "124");
- message.setField(f("optional_cord" ), "125");
+ message.setField(f("optional_string_piece"), "124");
+ message.setField(f("optional_cord"), "125");
// -----------------------------------------------------------------
- message.addRepeatedField(f("repeated_int32" ), 201 );
- message.addRepeatedField(f("repeated_int64" ), 202L);
- message.addRepeatedField(f("repeated_uint32" ), 203 );
- message.addRepeatedField(f("repeated_uint64" ), 204L);
- message.addRepeatedField(f("repeated_sint32" ), 205 );
- message.addRepeatedField(f("repeated_sint64" ), 206L);
- message.addRepeatedField(f("repeated_fixed32" ), 207 );
- message.addRepeatedField(f("repeated_fixed64" ), 208L);
- message.addRepeatedField(f("repeated_sfixed32"), 209 );
+ message.addRepeatedField(f("repeated_int32"), 201);
+ message.addRepeatedField(f("repeated_int64"), 202L);
+ message.addRepeatedField(f("repeated_uint32"), 203);
+ message.addRepeatedField(f("repeated_uint64"), 204L);
+ message.addRepeatedField(f("repeated_sint32"), 205);
+ message.addRepeatedField(f("repeated_sint64"), 206L);
+ message.addRepeatedField(f("repeated_fixed32"), 207);
+ message.addRepeatedField(f("repeated_fixed64"), 208L);
+ message.addRepeatedField(f("repeated_sfixed32"), 209);
message.addRepeatedField(f("repeated_sfixed64"), 210L);
- message.addRepeatedField(f("repeated_float" ), 211F);
- message.addRepeatedField(f("repeated_double" ), 212D);
- message.addRepeatedField(f("repeated_bool" ), true);
- message.addRepeatedField(f("repeated_string" ), "215");
- message.addRepeatedField(f("repeated_bytes" ), toBytes("216"));
-
- message.addRepeatedField(f("repeatedgroup"),
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 217).build());
- message.addRepeatedField(f("repeated_nested_message"),
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 218).build());
- message.addRepeatedField(f("repeated_foreign_message"),
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 219).build());
- message.addRepeatedField(f("repeated_import_message"),
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 220).build());
- message.addRepeatedField(f("repeated_lazy_message"),
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 227).build());
-
- message.addRepeatedField(f("repeated_nested_enum" ), nestedBar);
+ message.addRepeatedField(f("repeated_float"), 211F);
+ message.addRepeatedField(f("repeated_double"), 212D);
+ message.addRepeatedField(f("repeated_bool"), true);
+ message.addRepeatedField(f("repeated_string"), "215");
+ message.addRepeatedField(f("repeated_bytes"), toBytes("216"));
+
+ message.addRepeatedField(
+ f("repeatedgroup"),
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 217).build());
+ message.addRepeatedField(
+ f("repeated_nested_message"),
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 218).build());
+ message.addRepeatedField(
+ f("repeated_foreign_message"),
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 219)
+ .build());
+ message.addRepeatedField(
+ f("repeated_import_message"),
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 220).build());
+ message.addRepeatedField(
+ f("repeated_lazy_message"),
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 227).build());
+
+ message.addRepeatedField(f("repeated_nested_enum"), nestedBar);
message.addRepeatedField(f("repeated_foreign_enum"), foreignBar);
- message.addRepeatedField(f("repeated_import_enum" ), importBar);
+ message.addRepeatedField(f("repeated_import_enum"), importBar);
- message.addRepeatedField(f("repeated_string_piece" ), "224");
- message.addRepeatedField(f("repeated_cord" ), "225");
+ message.addRepeatedField(f("repeated_string_piece"), "224");
+ message.addRepeatedField(f("repeated_cord"), "225");
// Add a second one of each field.
- message.addRepeatedField(f("repeated_int32" ), 301 );
- message.addRepeatedField(f("repeated_int64" ), 302L);
- message.addRepeatedField(f("repeated_uint32" ), 303 );
- message.addRepeatedField(f("repeated_uint64" ), 304L);
- message.addRepeatedField(f("repeated_sint32" ), 305 );
- message.addRepeatedField(f("repeated_sint64" ), 306L);
- message.addRepeatedField(f("repeated_fixed32" ), 307 );
- message.addRepeatedField(f("repeated_fixed64" ), 308L);
- message.addRepeatedField(f("repeated_sfixed32"), 309 );
+ message.addRepeatedField(f("repeated_int32"), 301);
+ message.addRepeatedField(f("repeated_int64"), 302L);
+ message.addRepeatedField(f("repeated_uint32"), 303);
+ message.addRepeatedField(f("repeated_uint64"), 304L);
+ message.addRepeatedField(f("repeated_sint32"), 305);
+ message.addRepeatedField(f("repeated_sint64"), 306L);
+ message.addRepeatedField(f("repeated_fixed32"), 307);
+ message.addRepeatedField(f("repeated_fixed64"), 308L);
+ message.addRepeatedField(f("repeated_sfixed32"), 309);
message.addRepeatedField(f("repeated_sfixed64"), 310L);
- message.addRepeatedField(f("repeated_float" ), 311F);
- message.addRepeatedField(f("repeated_double" ), 312D);
- message.addRepeatedField(f("repeated_bool" ), false);
- message.addRepeatedField(f("repeated_string" ), "315");
- message.addRepeatedField(f("repeated_bytes" ), toBytes("316"));
-
- message.addRepeatedField(f("repeatedgroup"),
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 317).build());
- message.addRepeatedField(f("repeated_nested_message"),
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 318).build());
- message.addRepeatedField(f("repeated_foreign_message"),
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 319).build());
- message.addRepeatedField(f("repeated_import_message"),
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 320).build());
- message.addRepeatedField(f("repeated_lazy_message"),
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 327).build());
-
- message.addRepeatedField(f("repeated_nested_enum" ), nestedBaz);
+ message.addRepeatedField(f("repeated_float"), 311F);
+ message.addRepeatedField(f("repeated_double"), 312D);
+ message.addRepeatedField(f("repeated_bool"), false);
+ message.addRepeatedField(f("repeated_string"), "315");
+ message.addRepeatedField(f("repeated_bytes"), toBytes("316"));
+
+ message.addRepeatedField(
+ f("repeatedgroup"),
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 317).build());
+ message.addRepeatedField(
+ f("repeated_nested_message"),
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 318).build());
+ message.addRepeatedField(
+ f("repeated_foreign_message"),
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 319)
+ .build());
+ message.addRepeatedField(
+ f("repeated_import_message"),
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 320).build());
+ message.addRepeatedField(
+ f("repeated_lazy_message"),
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 327).build());
+
+ message.addRepeatedField(f("repeated_nested_enum"), nestedBaz);
message.addRepeatedField(f("repeated_foreign_enum"), foreignBaz);
- message.addRepeatedField(f("repeated_import_enum" ), importBaz);
+ message.addRepeatedField(f("repeated_import_enum"), importBaz);
- message.addRepeatedField(f("repeated_string_piece" ), "324");
- message.addRepeatedField(f("repeated_cord" ), "325");
+ message.addRepeatedField(f("repeated_string_piece"), "324");
+ message.addRepeatedField(f("repeated_cord"), "325");
// -----------------------------------------------------------------
- message.setField(f("default_int32" ), 401 );
- message.setField(f("default_int64" ), 402L);
- message.setField(f("default_uint32" ), 403 );
- message.setField(f("default_uint64" ), 404L);
- message.setField(f("default_sint32" ), 405 );
- message.setField(f("default_sint64" ), 406L);
- message.setField(f("default_fixed32" ), 407 );
- message.setField(f("default_fixed64" ), 408L);
- message.setField(f("default_sfixed32"), 409 );
+ message.setField(f("default_int32"), 401);
+ message.setField(f("default_int64"), 402L);
+ message.setField(f("default_uint32"), 403);
+ message.setField(f("default_uint64"), 404L);
+ message.setField(f("default_sint32"), 405);
+ message.setField(f("default_sint64"), 406L);
+ message.setField(f("default_fixed32"), 407);
+ message.setField(f("default_fixed64"), 408L);
+ message.setField(f("default_sfixed32"), 409);
message.setField(f("default_sfixed64"), 410L);
- message.setField(f("default_float" ), 411F);
- message.setField(f("default_double" ), 412D);
- message.setField(f("default_bool" ), false);
- message.setField(f("default_string" ), "415");
- message.setField(f("default_bytes" ), toBytes("416"));
+ message.setField(f("default_float"), 411F);
+ message.setField(f("default_double"), 412D);
+ message.setField(f("default_bool"), false);
+ message.setField(f("default_string"), "415");
+ message.setField(f("default_bytes"), toBytes("416"));
- message.setField(f("default_nested_enum" ), nestedFoo);
+ message.setField(f("default_nested_enum"), nestedFoo);
message.setField(f("default_foreign_enum"), foreignFoo);
- message.setField(f("default_import_enum" ), importFoo);
+ message.setField(f("default_import_enum"), importFoo);
- message.setField(f("default_string_piece" ), "424");
- message.setField(f("default_cord" ), "425");
+ message.setField(f("default_string_piece"), "424");
+ message.setField(f("default_cord"), "425");
- message.setField(f("oneof_uint32" ), 601);
- message.setField(f("oneof_nested_message"),
- newBuilderForField(message, f("oneof_nested_message"))
- .setField(nestedB, 602).build());
- message.setField(f("oneof_string" ), "603");
- message.setField(f("oneof_bytes" ), toBytes("604"));
+ message.setField(f("oneof_uint32"), 601);
+ message.setField(
+ f("oneof_nested_message"),
+ newBuilderForField(message, f("oneof_nested_message")).setField(nestedB, 602).build());
+ message.setField(f("oneof_string"), "603");
+ message.setField(f("oneof_bytes"), toBytes("604"));
}
// -------------------------------------------------------------------
/**
- * Modify the repeated fields of {@code message} to contain the values
- * expected by {@code assertRepeatedFieldsModified()}, using the
- * {@link Message.Builder} reflection interface.
+ * Modify the repeated fields of {@code message} to contain the values expected by {@code
+ * assertRepeatedFieldsModified()}, using the {@link Message.Builder} reflection interface.
*/
void modifyRepeatedFieldsViaReflection(Message.Builder message) {
- message.setRepeatedField(f("repeated_int32" ), 1, 501 );
- message.setRepeatedField(f("repeated_int64" ), 1, 502L);
- message.setRepeatedField(f("repeated_uint32" ), 1, 503 );
- message.setRepeatedField(f("repeated_uint64" ), 1, 504L);
- message.setRepeatedField(f("repeated_sint32" ), 1, 505 );
- message.setRepeatedField(f("repeated_sint64" ), 1, 506L);
- message.setRepeatedField(f("repeated_fixed32" ), 1, 507 );
- message.setRepeatedField(f("repeated_fixed64" ), 1, 508L);
- message.setRepeatedField(f("repeated_sfixed32"), 1, 509 );
+ message.setRepeatedField(f("repeated_int32"), 1, 501);
+ message.setRepeatedField(f("repeated_int64"), 1, 502L);
+ message.setRepeatedField(f("repeated_uint32"), 1, 503);
+ message.setRepeatedField(f("repeated_uint64"), 1, 504L);
+ message.setRepeatedField(f("repeated_sint32"), 1, 505);
+ message.setRepeatedField(f("repeated_sint64"), 1, 506L);
+ message.setRepeatedField(f("repeated_fixed32"), 1, 507);
+ message.setRepeatedField(f("repeated_fixed64"), 1, 508L);
+ message.setRepeatedField(f("repeated_sfixed32"), 1, 509);
message.setRepeatedField(f("repeated_sfixed64"), 1, 510L);
- message.setRepeatedField(f("repeated_float" ), 1, 511F);
- message.setRepeatedField(f("repeated_double" ), 1, 512D);
- message.setRepeatedField(f("repeated_bool" ), 1, true);
- message.setRepeatedField(f("repeated_string" ), 1, "515");
- message.setRepeatedField(f("repeated_bytes" ), 1, toBytes("516"));
-
- message.setRepeatedField(f("repeatedgroup"), 1,
- newBuilderForField(message, f("repeatedgroup"))
- .setField(repeatedGroupA, 517).build());
- message.setRepeatedField(f("repeated_nested_message"), 1,
- newBuilderForField(message, f("repeated_nested_message"))
- .setField(nestedB, 518).build());
- message.setRepeatedField(f("repeated_foreign_message"), 1,
- newBuilderForField(message, f("repeated_foreign_message"))
- .setField(foreignC, 519).build());
- message.setRepeatedField(f("repeated_import_message"), 1,
- newBuilderForField(message, f("repeated_import_message"))
- .setField(importD, 520).build());
- message.setRepeatedField(f("repeated_lazy_message"), 1,
- newBuilderForField(message, f("repeated_lazy_message"))
- .setField(nestedB, 527).build());
-
- message.setRepeatedField(f("repeated_nested_enum" ), 1, nestedFoo);
+ message.setRepeatedField(f("repeated_float"), 1, 511F);
+ message.setRepeatedField(f("repeated_double"), 1, 512D);
+ message.setRepeatedField(f("repeated_bool"), 1, true);
+ message.setRepeatedField(f("repeated_string"), 1, "515");
+ message.setRepeatedField(f("repeated_bytes"), 1, toBytes("516"));
+
+ message.setRepeatedField(
+ f("repeatedgroup"),
+ 1,
+ newBuilderForField(message, f("repeatedgroup")).setField(repeatedGroupA, 517).build());
+ message.setRepeatedField(
+ f("repeated_nested_message"),
+ 1,
+ newBuilderForField(message, f("repeated_nested_message")).setField(nestedB, 518).build());
+ message.setRepeatedField(
+ f("repeated_foreign_message"),
+ 1,
+ newBuilderForField(message, f("repeated_foreign_message"))
+ .setField(foreignC, 519)
+ .build());
+ message.setRepeatedField(
+ f("repeated_import_message"),
+ 1,
+ newBuilderForField(message, f("repeated_import_message")).setField(importD, 520).build());
+ message.setRepeatedField(
+ f("repeated_lazy_message"),
+ 1,
+ newBuilderForField(message, f("repeated_lazy_message")).setField(nestedB, 527).build());
+
+ message.setRepeatedField(f("repeated_nested_enum"), 1, nestedFoo);
message.setRepeatedField(f("repeated_foreign_enum"), 1, foreignFoo);
- message.setRepeatedField(f("repeated_import_enum" ), 1, importFoo);
+ message.setRepeatedField(f("repeated_import_enum"), 1, importFoo);
message.setRepeatedField(f("repeated_string_piece"), 1, "524");
message.setRepeatedField(f("repeated_cord"), 1, "525");
@@ -3022,244 +3029,235 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are set to the values assigned by {@code setAllFields},
- * using the {@link Message} reflection interface.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are set to
+ * the values assigned by {@code setAllFields}, using the {@link Message} reflection interface.
*/
public void assertAllFieldsSetViaReflection(MessageOrBuilder message) {
- Assert.assertTrue(message.hasField(f("optional_int32" )));
- Assert.assertTrue(message.hasField(f("optional_int64" )));
- Assert.assertTrue(message.hasField(f("optional_uint32" )));
- Assert.assertTrue(message.hasField(f("optional_uint64" )));
- Assert.assertTrue(message.hasField(f("optional_sint32" )));
- Assert.assertTrue(message.hasField(f("optional_sint64" )));
- Assert.assertTrue(message.hasField(f("optional_fixed32" )));
- Assert.assertTrue(message.hasField(f("optional_fixed64" )));
+ Assert.assertTrue(message.hasField(f("optional_int32")));
+ Assert.assertTrue(message.hasField(f("optional_int64")));
+ Assert.assertTrue(message.hasField(f("optional_uint32")));
+ Assert.assertTrue(message.hasField(f("optional_uint64")));
+ Assert.assertTrue(message.hasField(f("optional_sint32")));
+ Assert.assertTrue(message.hasField(f("optional_sint64")));
+ Assert.assertTrue(message.hasField(f("optional_fixed32")));
+ Assert.assertTrue(message.hasField(f("optional_fixed64")));
Assert.assertTrue(message.hasField(f("optional_sfixed32")));
Assert.assertTrue(message.hasField(f("optional_sfixed64")));
- Assert.assertTrue(message.hasField(f("optional_float" )));
- Assert.assertTrue(message.hasField(f("optional_double" )));
- Assert.assertTrue(message.hasField(f("optional_bool" )));
- Assert.assertTrue(message.hasField(f("optional_string" )));
- Assert.assertTrue(message.hasField(f("optional_bytes" )));
-
- Assert.assertTrue(message.hasField(f("optionalgroup" )));
- Assert.assertTrue(message.hasField(f("optional_nested_message" )));
+ Assert.assertTrue(message.hasField(f("optional_float")));
+ Assert.assertTrue(message.hasField(f("optional_double")));
+ Assert.assertTrue(message.hasField(f("optional_bool")));
+ Assert.assertTrue(message.hasField(f("optional_string")));
+ Assert.assertTrue(message.hasField(f("optional_bytes")));
+
+ Assert.assertTrue(message.hasField(f("optionalgroup")));
+ Assert.assertTrue(message.hasField(f("optional_nested_message")));
Assert.assertTrue(message.hasField(f("optional_foreign_message")));
- Assert.assertTrue(message.hasField(f("optional_import_message" )));
+ Assert.assertTrue(message.hasField(f("optional_import_message")));
+ Assert.assertTrue(((Message) message.getField(f("optionalgroup"))).hasField(groupA));
Assert.assertTrue(
- ((Message)message.getField(f("optionalgroup"))).hasField(groupA));
- Assert.assertTrue(
- ((Message)message.getField(f("optional_nested_message")))
- .hasField(nestedB));
+ ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB));
Assert.assertTrue(
- ((Message)message.getField(f("optional_foreign_message")))
- .hasField(foreignC));
+ ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC));
Assert.assertTrue(
- ((Message)message.getField(f("optional_import_message")))
- .hasField(importD));
+ ((Message) message.getField(f("optional_import_message"))).hasField(importD));
- Assert.assertTrue(message.hasField(f("optional_nested_enum" )));
+ Assert.assertTrue(message.hasField(f("optional_nested_enum")));
Assert.assertTrue(message.hasField(f("optional_foreign_enum")));
- Assert.assertTrue(message.hasField(f("optional_import_enum" )));
+ Assert.assertTrue(message.hasField(f("optional_import_enum")));
Assert.assertTrue(message.hasField(f("optional_string_piece")));
Assert.assertTrue(message.hasField(f("optional_cord")));
- Assert.assertEquals(101 , message.getField(f("optional_int32" )));
- Assert.assertEquals(102L , message.getField(f("optional_int64" )));
- Assert.assertEquals(103 , message.getField(f("optional_uint32" )));
- Assert.assertEquals(104L , message.getField(f("optional_uint64" )));
- Assert.assertEquals(105 , message.getField(f("optional_sint32" )));
- Assert.assertEquals(106L , message.getField(f("optional_sint64" )));
- Assert.assertEquals(107 , message.getField(f("optional_fixed32" )));
- Assert.assertEquals(108L , message.getField(f("optional_fixed64" )));
- Assert.assertEquals(109 , message.getField(f("optional_sfixed32")));
- Assert.assertEquals(110L , message.getField(f("optional_sfixed64")));
- Assert.assertEquals(111F , message.getField(f("optional_float" )));
- Assert.assertEquals(112D , message.getField(f("optional_double" )));
- Assert.assertEquals(true , message.getField(f("optional_bool" )));
- Assert.assertEquals("115", message.getField(f("optional_string" )));
+ Assert.assertEquals(101, message.getField(f("optional_int32")));
+ Assert.assertEquals(102L, message.getField(f("optional_int64")));
+ Assert.assertEquals(103, message.getField(f("optional_uint32")));
+ Assert.assertEquals(104L, message.getField(f("optional_uint64")));
+ Assert.assertEquals(105, message.getField(f("optional_sint32")));
+ Assert.assertEquals(106L, message.getField(f("optional_sint64")));
+ Assert.assertEquals(107, message.getField(f("optional_fixed32")));
+ Assert.assertEquals(108L, message.getField(f("optional_fixed64")));
+ Assert.assertEquals(109, message.getField(f("optional_sfixed32")));
+ Assert.assertEquals(110L, message.getField(f("optional_sfixed64")));
+ Assert.assertEquals(111F, message.getField(f("optional_float")));
+ Assert.assertEquals(112D, message.getField(f("optional_double")));
+ Assert.assertEquals(true, message.getField(f("optional_bool")));
+ Assert.assertEquals("115", message.getField(f("optional_string")));
Assert.assertEquals(toBytes("116"), message.getField(f("optional_bytes")));
- Assert.assertEquals(117,
- ((Message)message.getField(f("optionalgroup"))).getField(groupA));
- Assert.assertEquals(118,
- ((Message)message.getField(f("optional_nested_message")))
- .getField(nestedB));
- Assert.assertEquals(119,
- ((Message)message.getField(f("optional_foreign_message")))
- .getField(foreignC));
- Assert.assertEquals(120,
- ((Message)message.getField(f("optional_import_message")))
- .getField(importD));
- Assert.assertEquals(126,
- ((Message)message.getField(f("optional_public_import_message")))
- .getField(importE));
- Assert.assertEquals(127,
- ((Message)message.getField(f("optional_lazy_message")))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBaz, message.getField(f("optional_nested_enum" )));
+ Assert.assertEquals(117, ((Message) message.getField(f("optionalgroup"))).getField(groupA));
+ Assert.assertEquals(
+ 118, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB));
+ Assert.assertEquals(
+ 119, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC));
+ Assert.assertEquals(
+ 120, ((Message) message.getField(f("optional_import_message"))).getField(importD));
+ Assert.assertEquals(
+ 126, ((Message) message.getField(f("optional_public_import_message"))).getField(importE));
+ Assert.assertEquals(
+ 127, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB));
+
+ Assert.assertEquals(nestedBaz, message.getField(f("optional_nested_enum")));
Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum")));
- Assert.assertEquals( importBaz, message.getField(f("optional_import_enum" )));
+ Assert.assertEquals(importBaz, message.getField(f("optional_import_enum")));
Assert.assertEquals("124", message.getField(f("optional_string_piece")));
Assert.assertEquals("125", message.getField(f("optional_cord")));
// -----------------------------------------------------------------
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord")));
- Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0));
- Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0));
- Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0));
- Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0));
- Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0));
- Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0));
- Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0));
- Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0));
- Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0));
- Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0));
- Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0));
- Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0));
- Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0));
+ Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0));
+ Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0));
+ Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0));
+ Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0));
+ Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0));
+ Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0));
+ Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0));
+ Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0));
+ Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0));
+ Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0));
+ Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0));
+ Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0));
+ Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0));
Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0));
- Assert.assertEquals(217,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 0))
- .getField(repeatedGroupA));
- Assert.assertEquals(218,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 0))
- .getField(nestedB));
- Assert.assertEquals(219,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0))
- .getField(foreignC));
- Assert.assertEquals(220,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 0))
- .getField(importD));
- Assert.assertEquals(227,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0));
- Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0));
+ Assert.assertEquals(
+ 217,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 218,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB));
+ Assert.assertEquals(
+ 219,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 220,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD));
+ Assert.assertEquals(
+ 227,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB));
+
+ Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0));
+ Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0));
Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0));
Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0));
- Assert.assertEquals(301 , message.getRepeatedField(f("repeated_int32" ), 1));
- Assert.assertEquals(302L , message.getRepeatedField(f("repeated_int64" ), 1));
- Assert.assertEquals(303 , message.getRepeatedField(f("repeated_uint32" ), 1));
- Assert.assertEquals(304L , message.getRepeatedField(f("repeated_uint64" ), 1));
- Assert.assertEquals(305 , message.getRepeatedField(f("repeated_sint32" ), 1));
- Assert.assertEquals(306L , message.getRepeatedField(f("repeated_sint64" ), 1));
- Assert.assertEquals(307 , message.getRepeatedField(f("repeated_fixed32" ), 1));
- Assert.assertEquals(308L , message.getRepeatedField(f("repeated_fixed64" ), 1));
- Assert.assertEquals(309 , message.getRepeatedField(f("repeated_sfixed32"), 1));
- Assert.assertEquals(310L , message.getRepeatedField(f("repeated_sfixed64"), 1));
- Assert.assertEquals(311F , message.getRepeatedField(f("repeated_float" ), 1));
- Assert.assertEquals(312D , message.getRepeatedField(f("repeated_double" ), 1));
- Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool" ), 1));
- Assert.assertEquals("315", message.getRepeatedField(f("repeated_string" ), 1));
+ Assert.assertEquals(301, message.getRepeatedField(f("repeated_int32"), 1));
+ Assert.assertEquals(302L, message.getRepeatedField(f("repeated_int64"), 1));
+ Assert.assertEquals(303, message.getRepeatedField(f("repeated_uint32"), 1));
+ Assert.assertEquals(304L, message.getRepeatedField(f("repeated_uint64"), 1));
+ Assert.assertEquals(305, message.getRepeatedField(f("repeated_sint32"), 1));
+ Assert.assertEquals(306L, message.getRepeatedField(f("repeated_sint64"), 1));
+ Assert.assertEquals(307, message.getRepeatedField(f("repeated_fixed32"), 1));
+ Assert.assertEquals(308L, message.getRepeatedField(f("repeated_fixed64"), 1));
+ Assert.assertEquals(309, message.getRepeatedField(f("repeated_sfixed32"), 1));
+ Assert.assertEquals(310L, message.getRepeatedField(f("repeated_sfixed64"), 1));
+ Assert.assertEquals(311F, message.getRepeatedField(f("repeated_float"), 1));
+ Assert.assertEquals(312D, message.getRepeatedField(f("repeated_double"), 1));
+ Assert.assertEquals(false, message.getRepeatedField(f("repeated_bool"), 1));
+ Assert.assertEquals("315", message.getRepeatedField(f("repeated_string"), 1));
Assert.assertEquals(toBytes("316"), message.getRepeatedField(f("repeated_bytes"), 1));
- Assert.assertEquals(317,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 1))
- .getField(repeatedGroupA));
- Assert.assertEquals(318,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 1))
- .getField(nestedB));
- Assert.assertEquals(319,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1))
- .getField(foreignC));
- Assert.assertEquals(320,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 1))
- .getField(importD));
- Assert.assertEquals(327,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBaz, message.getRepeatedField(f("repeated_nested_enum" ),1));
- Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"),1));
- Assert.assertEquals( importBaz, message.getRepeatedField(f("repeated_import_enum" ),1));
+ Assert.assertEquals(
+ 317,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 318,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB));
+ Assert.assertEquals(
+ 319,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 320,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD));
+ Assert.assertEquals(
+ 327,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB));
+
+ Assert.assertEquals(nestedBaz, message.getRepeatedField(f("repeated_nested_enum"), 1));
+ Assert.assertEquals(foreignBaz, message.getRepeatedField(f("repeated_foreign_enum"), 1));
+ Assert.assertEquals(importBaz, message.getRepeatedField(f("repeated_import_enum"), 1));
Assert.assertEquals("324", message.getRepeatedField(f("repeated_string_piece"), 1));
Assert.assertEquals("325", message.getRepeatedField(f("repeated_cord"), 1));
// -----------------------------------------------------------------
- Assert.assertTrue(message.hasField(f("default_int32" )));
- Assert.assertTrue(message.hasField(f("default_int64" )));
- Assert.assertTrue(message.hasField(f("default_uint32" )));
- Assert.assertTrue(message.hasField(f("default_uint64" )));
- Assert.assertTrue(message.hasField(f("default_sint32" )));
- Assert.assertTrue(message.hasField(f("default_sint64" )));
- Assert.assertTrue(message.hasField(f("default_fixed32" )));
- Assert.assertTrue(message.hasField(f("default_fixed64" )));
+ Assert.assertTrue(message.hasField(f("default_int32")));
+ Assert.assertTrue(message.hasField(f("default_int64")));
+ Assert.assertTrue(message.hasField(f("default_uint32")));
+ Assert.assertTrue(message.hasField(f("default_uint64")));
+ Assert.assertTrue(message.hasField(f("default_sint32")));
+ Assert.assertTrue(message.hasField(f("default_sint64")));
+ Assert.assertTrue(message.hasField(f("default_fixed32")));
+ Assert.assertTrue(message.hasField(f("default_fixed64")));
Assert.assertTrue(message.hasField(f("default_sfixed32")));
Assert.assertTrue(message.hasField(f("default_sfixed64")));
- Assert.assertTrue(message.hasField(f("default_float" )));
- Assert.assertTrue(message.hasField(f("default_double" )));
- Assert.assertTrue(message.hasField(f("default_bool" )));
- Assert.assertTrue(message.hasField(f("default_string" )));
- Assert.assertTrue(message.hasField(f("default_bytes" )));
+ Assert.assertTrue(message.hasField(f("default_float")));
+ Assert.assertTrue(message.hasField(f("default_double")));
+ Assert.assertTrue(message.hasField(f("default_bool")));
+ Assert.assertTrue(message.hasField(f("default_string")));
+ Assert.assertTrue(message.hasField(f("default_bytes")));
- Assert.assertTrue(message.hasField(f("default_nested_enum" )));
+ Assert.assertTrue(message.hasField(f("default_nested_enum")));
Assert.assertTrue(message.hasField(f("default_foreign_enum")));
- Assert.assertTrue(message.hasField(f("default_import_enum" )));
+ Assert.assertTrue(message.hasField(f("default_import_enum")));
Assert.assertTrue(message.hasField(f("default_string_piece")));
Assert.assertTrue(message.hasField(f("default_cord")));
- Assert.assertEquals(401 , message.getField(f("default_int32" )));
- Assert.assertEquals(402L , message.getField(f("default_int64" )));
- Assert.assertEquals(403 , message.getField(f("default_uint32" )));
- Assert.assertEquals(404L , message.getField(f("default_uint64" )));
- Assert.assertEquals(405 , message.getField(f("default_sint32" )));
- Assert.assertEquals(406L , message.getField(f("default_sint64" )));
- Assert.assertEquals(407 , message.getField(f("default_fixed32" )));
- Assert.assertEquals(408L , message.getField(f("default_fixed64" )));
- Assert.assertEquals(409 , message.getField(f("default_sfixed32")));
- Assert.assertEquals(410L , message.getField(f("default_sfixed64")));
- Assert.assertEquals(411F , message.getField(f("default_float" )));
- Assert.assertEquals(412D , message.getField(f("default_double" )));
- Assert.assertEquals(false, message.getField(f("default_bool" )));
- Assert.assertEquals("415", message.getField(f("default_string" )));
+ Assert.assertEquals(401, message.getField(f("default_int32")));
+ Assert.assertEquals(402L, message.getField(f("default_int64")));
+ Assert.assertEquals(403, message.getField(f("default_uint32")));
+ Assert.assertEquals(404L, message.getField(f("default_uint64")));
+ Assert.assertEquals(405, message.getField(f("default_sint32")));
+ Assert.assertEquals(406L, message.getField(f("default_sint64")));
+ Assert.assertEquals(407, message.getField(f("default_fixed32")));
+ Assert.assertEquals(408L, message.getField(f("default_fixed64")));
+ Assert.assertEquals(409, message.getField(f("default_sfixed32")));
+ Assert.assertEquals(410L, message.getField(f("default_sfixed64")));
+ Assert.assertEquals(411F, message.getField(f("default_float")));
+ Assert.assertEquals(412D, message.getField(f("default_double")));
+ Assert.assertEquals(false, message.getField(f("default_bool")));
+ Assert.assertEquals("415", message.getField(f("default_string")));
Assert.assertEquals(toBytes("416"), message.getField(f("default_bytes")));
- Assert.assertEquals( nestedFoo, message.getField(f("default_nested_enum" )));
+ Assert.assertEquals(nestedFoo, message.getField(f("default_nested_enum")));
Assert.assertEquals(foreignFoo, message.getField(f("default_foreign_enum")));
- Assert.assertEquals( importFoo, message.getField(f("default_import_enum" )));
+ Assert.assertEquals(importFoo, message.getField(f("default_import_enum")));
Assert.assertEquals("424", message.getField(f("default_string_piece")));
Assert.assertEquals("425", message.getField(f("default_cord")));
@@ -3276,9 +3274,9 @@ public final class TestUtil {
Assert.assertTrue(message.hasField(f("oneof_nested_message")));
Assert.assertTrue(message.hasField(f("oneof_string")));
Assert.assertEquals(601, message.getField(f("oneof_uint32")));
- Assert.assertEquals(602,
- ((MessageOrBuilder) message.getField(f("oneof_nested_message")))
- .getField(nestedB));
+ Assert.assertEquals(
+ 602,
+ ((MessageOrBuilder) message.getField(f("oneof_nested_message"))).getField(nestedB));
Assert.assertEquals("603", message.getField(f("oneof_string")));
}
}
@@ -3286,175 +3284,163 @@ public final class TestUtil {
// -------------------------------------------------------------------
/**
- * Assert (using {@code junit.framework.Assert}} that all fields of
- * {@code message} are cleared, and that getting the fields returns their
- * default values, using the {@link Message} reflection interface.
+ * Assert (using {@code junit.framework.Assert}} that all fields of {@code message} are cleared,
+ * and that getting the fields returns their default values, using the {@link Message}
+ * reflection interface.
*/
public void assertClearViaReflection(MessageOrBuilder message) {
// has_blah() should initially be false for all optional fields.
- Assert.assertFalse(message.hasField(f("optional_int32" )));
- Assert.assertFalse(message.hasField(f("optional_int64" )));
- Assert.assertFalse(message.hasField(f("optional_uint32" )));
- Assert.assertFalse(message.hasField(f("optional_uint64" )));
- Assert.assertFalse(message.hasField(f("optional_sint32" )));
- Assert.assertFalse(message.hasField(f("optional_sint64" )));
- Assert.assertFalse(message.hasField(f("optional_fixed32" )));
- Assert.assertFalse(message.hasField(f("optional_fixed64" )));
+ Assert.assertFalse(message.hasField(f("optional_int32")));
+ Assert.assertFalse(message.hasField(f("optional_int64")));
+ Assert.assertFalse(message.hasField(f("optional_uint32")));
+ Assert.assertFalse(message.hasField(f("optional_uint64")));
+ Assert.assertFalse(message.hasField(f("optional_sint32")));
+ Assert.assertFalse(message.hasField(f("optional_sint64")));
+ Assert.assertFalse(message.hasField(f("optional_fixed32")));
+ Assert.assertFalse(message.hasField(f("optional_fixed64")));
Assert.assertFalse(message.hasField(f("optional_sfixed32")));
Assert.assertFalse(message.hasField(f("optional_sfixed64")));
- Assert.assertFalse(message.hasField(f("optional_float" )));
- Assert.assertFalse(message.hasField(f("optional_double" )));
- Assert.assertFalse(message.hasField(f("optional_bool" )));
- Assert.assertFalse(message.hasField(f("optional_string" )));
- Assert.assertFalse(message.hasField(f("optional_bytes" )));
-
- Assert.assertFalse(message.hasField(f("optionalgroup" )));
- Assert.assertFalse(message.hasField(f("optional_nested_message" )));
+ Assert.assertFalse(message.hasField(f("optional_float")));
+ Assert.assertFalse(message.hasField(f("optional_double")));
+ Assert.assertFalse(message.hasField(f("optional_bool")));
+ Assert.assertFalse(message.hasField(f("optional_string")));
+ Assert.assertFalse(message.hasField(f("optional_bytes")));
+
+ Assert.assertFalse(message.hasField(f("optionalgroup")));
+ Assert.assertFalse(message.hasField(f("optional_nested_message")));
Assert.assertFalse(message.hasField(f("optional_foreign_message")));
- Assert.assertFalse(message.hasField(f("optional_import_message" )));
+ Assert.assertFalse(message.hasField(f("optional_import_message")));
- Assert.assertFalse(message.hasField(f("optional_nested_enum" )));
+ Assert.assertFalse(message.hasField(f("optional_nested_enum")));
Assert.assertFalse(message.hasField(f("optional_foreign_enum")));
- Assert.assertFalse(message.hasField(f("optional_import_enum" )));
+ Assert.assertFalse(message.hasField(f("optional_import_enum")));
Assert.assertFalse(message.hasField(f("optional_string_piece")));
Assert.assertFalse(message.hasField(f("optional_cord")));
// Optional fields without defaults are set to zero or something like it.
- Assert.assertEquals(0 , message.getField(f("optional_int32" )));
- Assert.assertEquals(0L , message.getField(f("optional_int64" )));
- Assert.assertEquals(0 , message.getField(f("optional_uint32" )));
- Assert.assertEquals(0L , message.getField(f("optional_uint64" )));
- Assert.assertEquals(0 , message.getField(f("optional_sint32" )));
- Assert.assertEquals(0L , message.getField(f("optional_sint64" )));
- Assert.assertEquals(0 , message.getField(f("optional_fixed32" )));
- Assert.assertEquals(0L , message.getField(f("optional_fixed64" )));
- Assert.assertEquals(0 , message.getField(f("optional_sfixed32")));
- Assert.assertEquals(0L , message.getField(f("optional_sfixed64")));
- Assert.assertEquals(0F , message.getField(f("optional_float" )));
- Assert.assertEquals(0D , message.getField(f("optional_double" )));
- Assert.assertEquals(false, message.getField(f("optional_bool" )));
- Assert.assertEquals("" , message.getField(f("optional_string" )));
+ Assert.assertEquals(0, message.getField(f("optional_int32")));
+ Assert.assertEquals(0L, message.getField(f("optional_int64")));
+ Assert.assertEquals(0, message.getField(f("optional_uint32")));
+ Assert.assertEquals(0L, message.getField(f("optional_uint64")));
+ Assert.assertEquals(0, message.getField(f("optional_sint32")));
+ Assert.assertEquals(0L, message.getField(f("optional_sint64")));
+ Assert.assertEquals(0, message.getField(f("optional_fixed32")));
+ Assert.assertEquals(0L, message.getField(f("optional_fixed64")));
+ Assert.assertEquals(0, message.getField(f("optional_sfixed32")));
+ Assert.assertEquals(0L, message.getField(f("optional_sfixed64")));
+ Assert.assertEquals(0F, message.getField(f("optional_float")));
+ Assert.assertEquals(0D, message.getField(f("optional_double")));
+ Assert.assertEquals(false, message.getField(f("optional_bool")));
+ Assert.assertEquals("", message.getField(f("optional_string")));
Assert.assertEquals(ByteString.EMPTY, message.getField(f("optional_bytes")));
// Embedded messages should also be clear.
+ Assert.assertFalse(((Message) message.getField(f("optionalgroup"))).hasField(groupA));
Assert.assertFalse(
- ((Message)message.getField(f("optionalgroup"))).hasField(groupA));
- Assert.assertFalse(
- ((Message)message.getField(f("optional_nested_message")))
- .hasField(nestedB));
+ ((Message) message.getField(f("optional_nested_message"))).hasField(nestedB));
Assert.assertFalse(
- ((Message)message.getField(f("optional_foreign_message")))
- .hasField(foreignC));
+ ((Message) message.getField(f("optional_foreign_message"))).hasField(foreignC));
Assert.assertFalse(
- ((Message)message.getField(f("optional_import_message")))
- .hasField(importD));
+ ((Message) message.getField(f("optional_import_message"))).hasField(importD));
Assert.assertFalse(
- ((Message)message.getField(f("optional_public_import_message")))
- .hasField(importE));
+ ((Message) message.getField(f("optional_public_import_message"))).hasField(importE));
Assert.assertFalse(
- ((Message)message.getField(f("optional_lazy_message")))
- .hasField(nestedB));
-
- Assert.assertEquals(0,
- ((Message)message.getField(f("optionalgroup"))).getField(groupA));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_nested_message")))
- .getField(nestedB));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_foreign_message")))
- .getField(foreignC));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_import_message")))
- .getField(importD));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_public_import_message")))
- .getField(importE));
- Assert.assertEquals(0,
- ((Message)message.getField(f("optional_lazy_message")))
- .getField(nestedB));
+ ((Message) message.getField(f("optional_lazy_message"))).hasField(nestedB));
+
+ Assert.assertEquals(0, ((Message) message.getField(f("optionalgroup"))).getField(groupA));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_nested_message"))).getField(nestedB));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_foreign_message"))).getField(foreignC));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_import_message"))).getField(importD));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_public_import_message"))).getField(importE));
+ Assert.assertEquals(
+ 0, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB));
// Enums without defaults are set to the first value in the enum.
- Assert.assertEquals( nestedFoo, message.getField(f("optional_nested_enum" )));
+ Assert.assertEquals(nestedFoo, message.getField(f("optional_nested_enum")));
Assert.assertEquals(foreignFoo, message.getField(f("optional_foreign_enum")));
- Assert.assertEquals( importFoo, message.getField(f("optional_import_enum" )));
+ Assert.assertEquals(importFoo, message.getField(f("optional_import_enum")));
Assert.assertEquals("", message.getField(f("optional_string_piece")));
Assert.assertEquals("", message.getField(f("optional_cord")));
// Repeated fields are empty.
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(0, message.getRepeatedFieldCount(f("repeated_cord")));
// has_blah() should also be false for all default fields.
- Assert.assertFalse(message.hasField(f("default_int32" )));
- Assert.assertFalse(message.hasField(f("default_int64" )));
- Assert.assertFalse(message.hasField(f("default_uint32" )));
- Assert.assertFalse(message.hasField(f("default_uint64" )));
- Assert.assertFalse(message.hasField(f("default_sint32" )));
- Assert.assertFalse(message.hasField(f("default_sint64" )));
- Assert.assertFalse(message.hasField(f("default_fixed32" )));
- Assert.assertFalse(message.hasField(f("default_fixed64" )));
+ Assert.assertFalse(message.hasField(f("default_int32")));
+ Assert.assertFalse(message.hasField(f("default_int64")));
+ Assert.assertFalse(message.hasField(f("default_uint32")));
+ Assert.assertFalse(message.hasField(f("default_uint64")));
+ Assert.assertFalse(message.hasField(f("default_sint32")));
+ Assert.assertFalse(message.hasField(f("default_sint64")));
+ Assert.assertFalse(message.hasField(f("default_fixed32")));
+ Assert.assertFalse(message.hasField(f("default_fixed64")));
Assert.assertFalse(message.hasField(f("default_sfixed32")));
Assert.assertFalse(message.hasField(f("default_sfixed64")));
- Assert.assertFalse(message.hasField(f("default_float" )));
- Assert.assertFalse(message.hasField(f("default_double" )));
- Assert.assertFalse(message.hasField(f("default_bool" )));
- Assert.assertFalse(message.hasField(f("default_string" )));
- Assert.assertFalse(message.hasField(f("default_bytes" )));
+ Assert.assertFalse(message.hasField(f("default_float")));
+ Assert.assertFalse(message.hasField(f("default_double")));
+ Assert.assertFalse(message.hasField(f("default_bool")));
+ Assert.assertFalse(message.hasField(f("default_string")));
+ Assert.assertFalse(message.hasField(f("default_bytes")));
- Assert.assertFalse(message.hasField(f("default_nested_enum" )));
+ Assert.assertFalse(message.hasField(f("default_nested_enum")));
Assert.assertFalse(message.hasField(f("default_foreign_enum")));
- Assert.assertFalse(message.hasField(f("default_import_enum" )));
+ Assert.assertFalse(message.hasField(f("default_import_enum")));
- Assert.assertFalse(message.hasField(f("default_string_piece" )));
- Assert.assertFalse(message.hasField(f("default_cord" )));
+ Assert.assertFalse(message.hasField(f("default_string_piece")));
+ Assert.assertFalse(message.hasField(f("default_cord")));
// Fields with defaults have their default values (duh).
- Assert.assertEquals( 41 , message.getField(f("default_int32" )));
- Assert.assertEquals( 42L , message.getField(f("default_int64" )));
- Assert.assertEquals( 43 , message.getField(f("default_uint32" )));
- Assert.assertEquals( 44L , message.getField(f("default_uint64" )));
- Assert.assertEquals(-45 , message.getField(f("default_sint32" )));
- Assert.assertEquals( 46L , message.getField(f("default_sint64" )));
- Assert.assertEquals( 47 , message.getField(f("default_fixed32" )));
- Assert.assertEquals( 48L , message.getField(f("default_fixed64" )));
- Assert.assertEquals( 49 , message.getField(f("default_sfixed32")));
- Assert.assertEquals(-50L , message.getField(f("default_sfixed64")));
- Assert.assertEquals( 51.5F , message.getField(f("default_float" )));
- Assert.assertEquals( 52e3D , message.getField(f("default_double" )));
- Assert.assertEquals(true , message.getField(f("default_bool" )));
- Assert.assertEquals("hello", message.getField(f("default_string" )));
+ Assert.assertEquals(41, message.getField(f("default_int32")));
+ Assert.assertEquals(42L, message.getField(f("default_int64")));
+ Assert.assertEquals(43, message.getField(f("default_uint32")));
+ Assert.assertEquals(44L, message.getField(f("default_uint64")));
+ Assert.assertEquals(-45, message.getField(f("default_sint32")));
+ Assert.assertEquals(46L, message.getField(f("default_sint64")));
+ Assert.assertEquals(47, message.getField(f("default_fixed32")));
+ Assert.assertEquals(48L, message.getField(f("default_fixed64")));
+ Assert.assertEquals(49, message.getField(f("default_sfixed32")));
+ Assert.assertEquals(-50L, message.getField(f("default_sfixed64")));
+ Assert.assertEquals(51.5F, message.getField(f("default_float")));
+ Assert.assertEquals(52e3D, message.getField(f("default_double")));
+ Assert.assertEquals(true, message.getField(f("default_bool")));
+ Assert.assertEquals("hello", message.getField(f("default_string")));
Assert.assertEquals(toBytes("world"), message.getField(f("default_bytes")));
- Assert.assertEquals( nestedBar, message.getField(f("default_nested_enum" )));
+ Assert.assertEquals(nestedBar, message.getField(f("default_nested_enum")));
Assert.assertEquals(foreignBar, message.getField(f("default_foreign_enum")));
- Assert.assertEquals( importBar, message.getField(f("default_import_enum" )));
+ Assert.assertEquals(importBar, message.getField(f("default_import_enum")));
Assert.assertEquals("abc", message.getField(f("default_string_piece")));
Assert.assertEquals("123", message.getField(f("default_cord")));
@@ -3469,205 +3455,204 @@ public final class TestUtil {
Assert.assertEquals(toBytes(""), message.getField(f("oneof_bytes")));
}
-
// ---------------------------------------------------------------
- public void assertRepeatedFieldsModifiedViaReflection(
- MessageOrBuilder message) {
+ public void assertRepeatedFieldsModifiedViaReflection(MessageOrBuilder message) {
// ModifyRepeatedFields only sets the second repeated element of each
// field. In addition to verifying this, we also verify that the first
// element and size were *not* modified.
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes" )));
-
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_bytes")));
+
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeatedgroup")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_message")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_message")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_lazy_message")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_nested_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_foreign_enum")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_import_enum")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_string_piece")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("repeated_cord")));
- Assert.assertEquals(201 , message.getRepeatedField(f("repeated_int32" ), 0));
- Assert.assertEquals(202L , message.getRepeatedField(f("repeated_int64" ), 0));
- Assert.assertEquals(203 , message.getRepeatedField(f("repeated_uint32" ), 0));
- Assert.assertEquals(204L , message.getRepeatedField(f("repeated_uint64" ), 0));
- Assert.assertEquals(205 , message.getRepeatedField(f("repeated_sint32" ), 0));
- Assert.assertEquals(206L , message.getRepeatedField(f("repeated_sint64" ), 0));
- Assert.assertEquals(207 , message.getRepeatedField(f("repeated_fixed32" ), 0));
- Assert.assertEquals(208L , message.getRepeatedField(f("repeated_fixed64" ), 0));
- Assert.assertEquals(209 , message.getRepeatedField(f("repeated_sfixed32"), 0));
- Assert.assertEquals(210L , message.getRepeatedField(f("repeated_sfixed64"), 0));
- Assert.assertEquals(211F , message.getRepeatedField(f("repeated_float" ), 0));
- Assert.assertEquals(212D , message.getRepeatedField(f("repeated_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 0));
- Assert.assertEquals("215", message.getRepeatedField(f("repeated_string" ), 0));
+ Assert.assertEquals(201, message.getRepeatedField(f("repeated_int32"), 0));
+ Assert.assertEquals(202L, message.getRepeatedField(f("repeated_int64"), 0));
+ Assert.assertEquals(203, message.getRepeatedField(f("repeated_uint32"), 0));
+ Assert.assertEquals(204L, message.getRepeatedField(f("repeated_uint64"), 0));
+ Assert.assertEquals(205, message.getRepeatedField(f("repeated_sint32"), 0));
+ Assert.assertEquals(206L, message.getRepeatedField(f("repeated_sint64"), 0));
+ Assert.assertEquals(207, message.getRepeatedField(f("repeated_fixed32"), 0));
+ Assert.assertEquals(208L, message.getRepeatedField(f("repeated_fixed64"), 0));
+ Assert.assertEquals(209, message.getRepeatedField(f("repeated_sfixed32"), 0));
+ Assert.assertEquals(210L, message.getRepeatedField(f("repeated_sfixed64"), 0));
+ Assert.assertEquals(211F, message.getRepeatedField(f("repeated_float"), 0));
+ Assert.assertEquals(212D, message.getRepeatedField(f("repeated_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 0));
+ Assert.assertEquals("215", message.getRepeatedField(f("repeated_string"), 0));
Assert.assertEquals(toBytes("216"), message.getRepeatedField(f("repeated_bytes"), 0));
- Assert.assertEquals(217,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 0))
- .getField(repeatedGroupA));
- Assert.assertEquals(218,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 0))
- .getField(nestedB));
- Assert.assertEquals(219,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 0))
- .getField(foreignC));
- Assert.assertEquals(220,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 0))
- .getField(importD));
- Assert.assertEquals(227,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 0))
- .getField(nestedB));
-
- Assert.assertEquals( nestedBar, message.getRepeatedField(f("repeated_nested_enum" ),0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"),0));
- Assert.assertEquals( importBar, message.getRepeatedField(f("repeated_import_enum" ),0));
+ Assert.assertEquals(
+ 217,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 0)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 218,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 0)).getField(nestedB));
+ Assert.assertEquals(
+ 219,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 0))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 220,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 0)).getField(importD));
+ Assert.assertEquals(
+ 227,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 0)).getField(nestedB));
+
+ Assert.assertEquals(nestedBar, message.getRepeatedField(f("repeated_nested_enum"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("repeated_foreign_enum"), 0));
+ Assert.assertEquals(importBar, message.getRepeatedField(f("repeated_import_enum"), 0));
Assert.assertEquals("224", message.getRepeatedField(f("repeated_string_piece"), 0));
Assert.assertEquals("225", message.getRepeatedField(f("repeated_cord"), 0));
- Assert.assertEquals(501 , message.getRepeatedField(f("repeated_int32" ), 1));
- Assert.assertEquals(502L , message.getRepeatedField(f("repeated_int64" ), 1));
- Assert.assertEquals(503 , message.getRepeatedField(f("repeated_uint32" ), 1));
- Assert.assertEquals(504L , message.getRepeatedField(f("repeated_uint64" ), 1));
- Assert.assertEquals(505 , message.getRepeatedField(f("repeated_sint32" ), 1));
- Assert.assertEquals(506L , message.getRepeatedField(f("repeated_sint64" ), 1));
- Assert.assertEquals(507 , message.getRepeatedField(f("repeated_fixed32" ), 1));
- Assert.assertEquals(508L , message.getRepeatedField(f("repeated_fixed64" ), 1));
- Assert.assertEquals(509 , message.getRepeatedField(f("repeated_sfixed32"), 1));
- Assert.assertEquals(510L , message.getRepeatedField(f("repeated_sfixed64"), 1));
- Assert.assertEquals(511F , message.getRepeatedField(f("repeated_float" ), 1));
- Assert.assertEquals(512D , message.getRepeatedField(f("repeated_double" ), 1));
- Assert.assertEquals(true , message.getRepeatedField(f("repeated_bool" ), 1));
- Assert.assertEquals("515", message.getRepeatedField(f("repeated_string" ), 1));
+ Assert.assertEquals(501, message.getRepeatedField(f("repeated_int32"), 1));
+ Assert.assertEquals(502L, message.getRepeatedField(f("repeated_int64"), 1));
+ Assert.assertEquals(503, message.getRepeatedField(f("repeated_uint32"), 1));
+ Assert.assertEquals(504L, message.getRepeatedField(f("repeated_uint64"), 1));
+ Assert.assertEquals(505, message.getRepeatedField(f("repeated_sint32"), 1));
+ Assert.assertEquals(506L, message.getRepeatedField(f("repeated_sint64"), 1));
+ Assert.assertEquals(507, message.getRepeatedField(f("repeated_fixed32"), 1));
+ Assert.assertEquals(508L, message.getRepeatedField(f("repeated_fixed64"), 1));
+ Assert.assertEquals(509, message.getRepeatedField(f("repeated_sfixed32"), 1));
+ Assert.assertEquals(510L, message.getRepeatedField(f("repeated_sfixed64"), 1));
+ Assert.assertEquals(511F, message.getRepeatedField(f("repeated_float"), 1));
+ Assert.assertEquals(512D, message.getRepeatedField(f("repeated_double"), 1));
+ Assert.assertEquals(true, message.getRepeatedField(f("repeated_bool"), 1));
+ Assert.assertEquals("515", message.getRepeatedField(f("repeated_string"), 1));
Assert.assertEquals(toBytes("516"), message.getRepeatedField(f("repeated_bytes"), 1));
- Assert.assertEquals(517,
- ((Message)message.getRepeatedField(f("repeatedgroup"), 1))
- .getField(repeatedGroupA));
- Assert.assertEquals(518,
- ((Message)message.getRepeatedField(f("repeated_nested_message"), 1))
- .getField(nestedB));
- Assert.assertEquals(519,
- ((Message)message.getRepeatedField(f("repeated_foreign_message"), 1))
- .getField(foreignC));
- Assert.assertEquals(520,
- ((Message)message.getRepeatedField(f("repeated_import_message"), 1))
- .getField(importD));
- Assert.assertEquals(527,
- ((Message)message.getRepeatedField(f("repeated_lazy_message"), 1))
- .getField(nestedB));
-
- Assert.assertEquals( nestedFoo, message.getRepeatedField(f("repeated_nested_enum" ),1));
- Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"),1));
- Assert.assertEquals( importFoo, message.getRepeatedField(f("repeated_import_enum" ),1));
+ Assert.assertEquals(
+ 517,
+ ((Message) message.getRepeatedField(f("repeatedgroup"), 1)).getField(repeatedGroupA));
+ Assert.assertEquals(
+ 518,
+ ((Message) message.getRepeatedField(f("repeated_nested_message"), 1)).getField(nestedB));
+ Assert.assertEquals(
+ 519,
+ ((Message) message.getRepeatedField(f("repeated_foreign_message"), 1))
+ .getField(foreignC));
+ Assert.assertEquals(
+ 520,
+ ((Message) message.getRepeatedField(f("repeated_import_message"), 1)).getField(importD));
+ Assert.assertEquals(
+ 527,
+ ((Message) message.getRepeatedField(f("repeated_lazy_message"), 1)).getField(nestedB));
+
+ Assert.assertEquals(nestedFoo, message.getRepeatedField(f("repeated_nested_enum"), 1));
+ Assert.assertEquals(foreignFoo, message.getRepeatedField(f("repeated_foreign_enum"), 1));
+ Assert.assertEquals(importFoo, message.getRepeatedField(f("repeated_import_enum"), 1));
Assert.assertEquals("524", message.getRepeatedField(f("repeated_string_piece"), 1));
Assert.assertEquals("525", message.getRepeatedField(f("repeated_cord"), 1));
}
public void setPackedFieldsViaReflection(Message.Builder message) {
- message.addRepeatedField(f("packed_int32" ), 601 );
- message.addRepeatedField(f("packed_int64" ), 602L);
- message.addRepeatedField(f("packed_uint32" ), 603 );
- message.addRepeatedField(f("packed_uint64" ), 604L);
- message.addRepeatedField(f("packed_sint32" ), 605 );
- message.addRepeatedField(f("packed_sint64" ), 606L);
- message.addRepeatedField(f("packed_fixed32" ), 607 );
- message.addRepeatedField(f("packed_fixed64" ), 608L);
- message.addRepeatedField(f("packed_sfixed32"), 609 );
+ message.addRepeatedField(f("packed_int32"), 601);
+ message.addRepeatedField(f("packed_int64"), 602L);
+ message.addRepeatedField(f("packed_uint32"), 603);
+ message.addRepeatedField(f("packed_uint64"), 604L);
+ message.addRepeatedField(f("packed_sint32"), 605);
+ message.addRepeatedField(f("packed_sint64"), 606L);
+ message.addRepeatedField(f("packed_fixed32"), 607);
+ message.addRepeatedField(f("packed_fixed64"), 608L);
+ message.addRepeatedField(f("packed_sfixed32"), 609);
message.addRepeatedField(f("packed_sfixed64"), 610L);
- message.addRepeatedField(f("packed_float" ), 611F);
- message.addRepeatedField(f("packed_double" ), 612D);
- message.addRepeatedField(f("packed_bool" ), true);
- message.addRepeatedField(f("packed_enum" ), foreignBar);
+ message.addRepeatedField(f("packed_float"), 611F);
+ message.addRepeatedField(f("packed_double"), 612D);
+ message.addRepeatedField(f("packed_bool"), true);
+ message.addRepeatedField(f("packed_enum"), foreignBar);
// Add a second one of each field.
- message.addRepeatedField(f("packed_int32" ), 701 );
- message.addRepeatedField(f("packed_int64" ), 702L);
- message.addRepeatedField(f("packed_uint32" ), 703 );
- message.addRepeatedField(f("packed_uint64" ), 704L);
- message.addRepeatedField(f("packed_sint32" ), 705 );
- message.addRepeatedField(f("packed_sint64" ), 706L);
- message.addRepeatedField(f("packed_fixed32" ), 707 );
- message.addRepeatedField(f("packed_fixed64" ), 708L);
- message.addRepeatedField(f("packed_sfixed32"), 709 );
+ message.addRepeatedField(f("packed_int32"), 701);
+ message.addRepeatedField(f("packed_int64"), 702L);
+ message.addRepeatedField(f("packed_uint32"), 703);
+ message.addRepeatedField(f("packed_uint64"), 704L);
+ message.addRepeatedField(f("packed_sint32"), 705);
+ message.addRepeatedField(f("packed_sint64"), 706L);
+ message.addRepeatedField(f("packed_fixed32"), 707);
+ message.addRepeatedField(f("packed_fixed64"), 708L);
+ message.addRepeatedField(f("packed_sfixed32"), 709);
message.addRepeatedField(f("packed_sfixed64"), 710L);
- message.addRepeatedField(f("packed_float" ), 711F);
- message.addRepeatedField(f("packed_double" ), 712D);
- message.addRepeatedField(f("packed_bool" ), false);
- message.addRepeatedField(f("packed_enum" ), foreignBaz);
+ message.addRepeatedField(f("packed_float"), 711F);
+ message.addRepeatedField(f("packed_double"), 712D);
+ message.addRepeatedField(f("packed_bool"), false);
+ message.addRepeatedField(f("packed_enum"), foreignBaz);
}
public void assertPackedFieldsSetViaReflection(MessageOrBuilder message) {
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64" )));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_int64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_uint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sint64")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed32")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_fixed64")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed32")));
Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_sfixed64")));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool" )));
- Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum" )));
- Assert.assertEquals(601 , message.getRepeatedField(f("packed_int32" ), 0));
- Assert.assertEquals(602L , message.getRepeatedField(f("packed_int64" ), 0));
- Assert.assertEquals(603 , message.getRepeatedField(f("packed_uint32" ), 0));
- Assert.assertEquals(604L , message.getRepeatedField(f("packed_uint64" ), 0));
- Assert.assertEquals(605 , message.getRepeatedField(f("packed_sint32" ), 0));
- Assert.assertEquals(606L , message.getRepeatedField(f("packed_sint64" ), 0));
- Assert.assertEquals(607 , message.getRepeatedField(f("packed_fixed32" ), 0));
- Assert.assertEquals(608L , message.getRepeatedField(f("packed_fixed64" ), 0));
- Assert.assertEquals(609 , message.getRepeatedField(f("packed_sfixed32"), 0));
- Assert.assertEquals(610L , message.getRepeatedField(f("packed_sfixed64"), 0));
- Assert.assertEquals(611F , message.getRepeatedField(f("packed_float" ), 0));
- Assert.assertEquals(612D , message.getRepeatedField(f("packed_double" ), 0));
- Assert.assertEquals(true , message.getRepeatedField(f("packed_bool" ), 0));
- Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum" ),0));
- Assert.assertEquals(701 , message.getRepeatedField(f("packed_int32" ), 1));
- Assert.assertEquals(702L , message.getRepeatedField(f("packed_int64" ), 1));
- Assert.assertEquals(703 , message.getRepeatedField(f("packed_uint32" ), 1));
- Assert.assertEquals(704L , message.getRepeatedField(f("packed_uint64" ), 1));
- Assert.assertEquals(705 , message.getRepeatedField(f("packed_sint32" ), 1));
- Assert.assertEquals(706L , message.getRepeatedField(f("packed_sint64" ), 1));
- Assert.assertEquals(707 , message.getRepeatedField(f("packed_fixed32" ), 1));
- Assert.assertEquals(708L , message.getRepeatedField(f("packed_fixed64" ), 1));
- Assert.assertEquals(709 , message.getRepeatedField(f("packed_sfixed32"), 1));
- Assert.assertEquals(710L , message.getRepeatedField(f("packed_sfixed64"), 1));
- Assert.assertEquals(711F , message.getRepeatedField(f("packed_float" ), 1));
- Assert.assertEquals(712D , message.getRepeatedField(f("packed_double" ), 1));
- Assert.assertEquals(false, message.getRepeatedField(f("packed_bool" ), 1));
- Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum" ),1));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_float")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_double")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_bool")));
+ Assert.assertEquals(2, message.getRepeatedFieldCount(f("packed_enum")));
+ Assert.assertEquals(601, message.getRepeatedField(f("packed_int32"), 0));
+ Assert.assertEquals(602L, message.getRepeatedField(f("packed_int64"), 0));
+ Assert.assertEquals(603, message.getRepeatedField(f("packed_uint32"), 0));
+ Assert.assertEquals(604L, message.getRepeatedField(f("packed_uint64"), 0));
+ Assert.assertEquals(605, message.getRepeatedField(f("packed_sint32"), 0));
+ Assert.assertEquals(606L, message.getRepeatedField(f("packed_sint64"), 0));
+ Assert.assertEquals(607, message.getRepeatedField(f("packed_fixed32"), 0));
+ Assert.assertEquals(608L, message.getRepeatedField(f("packed_fixed64"), 0));
+ Assert.assertEquals(609, message.getRepeatedField(f("packed_sfixed32"), 0));
+ Assert.assertEquals(610L, message.getRepeatedField(f("packed_sfixed64"), 0));
+ Assert.assertEquals(611F, message.getRepeatedField(f("packed_float"), 0));
+ Assert.assertEquals(612D, message.getRepeatedField(f("packed_double"), 0));
+ Assert.assertEquals(true, message.getRepeatedField(f("packed_bool"), 0));
+ Assert.assertEquals(foreignBar, message.getRepeatedField(f("packed_enum"), 0));
+ Assert.assertEquals(701, message.getRepeatedField(f("packed_int32"), 1));
+ Assert.assertEquals(702L, message.getRepeatedField(f("packed_int64"), 1));
+ Assert.assertEquals(703, message.getRepeatedField(f("packed_uint32"), 1));
+ Assert.assertEquals(704L, message.getRepeatedField(f("packed_uint64"), 1));
+ Assert.assertEquals(705, message.getRepeatedField(f("packed_sint32"), 1));
+ Assert.assertEquals(706L, message.getRepeatedField(f("packed_sint64"), 1));
+ Assert.assertEquals(707, message.getRepeatedField(f("packed_fixed32"), 1));
+ Assert.assertEquals(708L, message.getRepeatedField(f("packed_fixed64"), 1));
+ Assert.assertEquals(709, message.getRepeatedField(f("packed_sfixed32"), 1));
+ Assert.assertEquals(710L, message.getRepeatedField(f("packed_sfixed64"), 1));
+ Assert.assertEquals(711F, message.getRepeatedField(f("packed_float"), 1));
+ Assert.assertEquals(712D, message.getRepeatedField(f("packed_double"), 1));
+ Assert.assertEquals(false, message.getRepeatedField(f("packed_bool"), 1));
+ Assert.assertEquals(foreignBaz, message.getRepeatedField(f("packed_enum"), 1));
}
/**
* Verifies that the reflection setters for the given.Builder object throw a
- * NullPointerException if they are passed a null value. Uses Assert to throw an
- * appropriate assertion failure, if the condition is not verified.
+ * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
+ * assertion failure, if the condition is not verified.
*/
- public void assertReflectionSettersRejectNull(Message.Builder builder)
- throws Exception {
+ public void assertReflectionSettersRejectNull(Message.Builder builder) throws Exception {
try {
builder.setField(f("optional_string"), null);
Assert.fail("Exception was not thrown");
@@ -3687,15 +3672,13 @@ public final class TestUtil {
// We expect this exception.
}
try {
- builder.setField(f("optional_nested_message"),
- (TestAllTypes.NestedMessage) null);
+ builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage) null);
Assert.fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
}
try {
- builder.setField(f("optional_nested_message"),
- (TestAllTypes.NestedMessage.Builder) null);
+ builder.setField(f("optional_nested_message"), (TestAllTypes.NestedMessage.Builder) null);
Assert.fail("Exception was not thrown");
} catch (NullPointerException e) {
// We expect this exception.
@@ -3729,7 +3712,7 @@ public final class TestUtil {
/**
* Verifies that the reflection repeated setters for the given Builder object throw a
- * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
+ * NullPointerException if they are passed a null value. Uses Assert to throw an appropriate
* assertion failure, if the condition is not verified.
*/
public void assertReflectionRepeatedSettersRejectNull(Message.Builder builder)
@@ -3759,8 +3742,7 @@ public final class TestUtil {
}
builder.addRepeatedField(
- f("repeated_nested_message"),
- TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
+ f("repeated_nested_message"), TestAllTypes.NestedMessage.newBuilder().setBb(218).build());
try {
builder.setRepeatedField(f("repeated_nested_message"), 0, null);
Assert.fail("Exception was not thrown");
@@ -3770,10 +3752,7 @@ public final class TestUtil {
}
}
- /**
- * @param filePath The path relative to
- * {@link #getTestDataDir}.
- */
+ /** @param filePath The path relative to {@link #getTestDataDir}. */
public static String readTextFromFile(String filePath) {
return readBytesFromFile(filePath).toStringUtf8();
}
@@ -3785,8 +3764,7 @@ public final class TestUtil {
try {
ancestor = ancestor.getCanonicalFile();
} catch (IOException e) {
- throw new RuntimeException(
- "Couldn't get canonical name of working directory.", e);
+ throw new RuntimeException("Couldn't get canonical name of working directory.", e);
}
while (ancestor != null && ancestor.exists()) {
if (new File(ancestor, "src/google/protobuf").exists()) {
@@ -3796,15 +3774,13 @@ public final class TestUtil {
}
throw new RuntimeException(
- "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: " + initialPath);
+ "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: "
+ + initialPath);
}
- /**
- * @param filename The path relative to
- * {@link #getTestDataDir}.
- */
+ /** @param filename The path relative to {@link #getTestDataDir}. */
public static ByteString readBytesFromFile(String filename) {
File fullPath = new File(getTestDataDir(), filename);
try {
@@ -3815,50 +3791,59 @@ public final class TestUtil {
} catch (IOException e) {
// Throw a RuntimeException here so that we can call this function from
// static initializers.
- throw new IllegalArgumentException(
- "Couldn't read file: " + fullPath.getPath(), e);
+ throw new IllegalArgumentException("Couldn't read file: " + fullPath.getPath(), e);
+ }
+ }
+ // END FULL-RUNTIME
+
+ private static ByteString readBytesFromResource(String name) {
+ try {
+ return ByteString.copyFrom(
+ com.google.common.io.ByteStreams.toByteArray(TestUtil.class.getResourceAsStream(name)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
}
}
/**
- * Get the bytes of the "golden message". This is a serialized TestAllTypes
- * with all fields set as they would be by
- * {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file
- * on disk rather than generated dynamically. The file is actually generated
- * by C++ code, so testing against it verifies compatibility with C++.
+ * Get the bytes of the "golden message". This is a serialized TestAllTypes with all fields set as
+ * they would be by {@link #setAllFields(TestAllTypes.Builder)}, but it is loaded from a file on
+ * disk rather than generated dynamically. The file is actually generated by C++ code, so testing
+ * against it verifies compatibility with C++.
*/
public static ByteString getGoldenMessage() {
if (goldenMessage == null) {
- goldenMessage = readBytesFromFile("golden_message_oneof_implemented");
+ goldenMessage =
+ readBytesFromResource("/google/protobuf/testdata/golden_message_oneof_implemented");
}
return goldenMessage;
}
+
private static ByteString goldenMessage = null;
/**
- * Get the bytes of the "golden packed fields message". This is a serialized
- * TestPackedTypes with all fields set as they would be by
- * {@link #setPackedFields(TestPackedTypes.Builder)}, but it is loaded from a
- * file on disk rather than generated dynamically. The file is actually
- * generated by C++ code, so testing against it verifies compatibility with
- * C++.
+ * Get the bytes of the "golden packed fields message". This is a serialized TestPackedTypes with
+ * all fields set as they would be by {@link #setPackedFields(TestPackedTypes.Builder)}, but it is
+ * loaded from a file on disk rather than generated dynamically. The file is actually generated by
+ * C++ code, so testing against it verifies compatibility with C++.
*/
public static ByteString getGoldenPackedFieldsMessage() {
if (goldenPackedFieldsMessage == null) {
goldenPackedFieldsMessage =
- readBytesFromFile("golden_packed_fields_message");
+ readBytesFromResource("/google/protobuf/testdata/golden_packed_fields_message");
}
return goldenPackedFieldsMessage;
}
+
private static ByteString goldenPackedFieldsMessage = null;
+ // BEGIN FULL-RUNTIME
/**
* Mock implementation of {@link GeneratedMessage.BuilderParent} for testing.
*
* @author jonp@google.com (Jon Perlow)
*/
- public static class MockBuilderParent
- implements GeneratedMessage.BuilderParent {
+ public static class MockBuilderParent implements GeneratedMessage.BuilderParent {
private int invalidations;
@@ -3871,4 +3856,5 @@ public final class TestUtil {
return invalidations;
}
}
+ // END FULL-RUNTIME
}
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
index 8f33fa14..31565fc4 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
@@ -30,8 +30,6 @@
package com.google.protobuf;
-import static com.google.protobuf.UnittestLite.OptionalGroup_extension_lite;
-import static com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite;
import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite;
import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite;
import static com.google.protobuf.UnittestLite.defaultCordExtensionLite;
@@ -127,6 +125,8 @@ import com.google.protobuf.UnittestImportLite.ImportMessageLite;
import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite;
import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.ForeignMessageLite;
+import com.google.protobuf.UnittestLite.OptionalGroup_extension_lite;
+import com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite;
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
@@ -136,8 +136,7 @@ import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
* and {@code TestPackedExtensionsLite}. This is analogous to the functionality in TestUtil.java but
* does not depend on the presence of any non-lite protos.
*
- * <p>This code is not to be used outside of {@code com.google.protobuf} and
- * subpackages.
+ * <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages.
*/
public final class TestUtilLite {
private TestUtilLite() {}
@@ -148,8 +147,8 @@ public final class TestUtilLite {
}
/**
- * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by
- * {@link #setAllFields(TestAllTypesLite.Builder)}.
+ * Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by {@link
+ * #setAllFields(TestAllTypesLite.Builder)}.
*/
public static TestAllTypesLite.Builder getAllLiteSetBuilder() {
TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder();
@@ -158,8 +157,8 @@ public final class TestUtilLite {
}
/**
- * Get a {@code TestAllExtensionsLite} with all fields set as they would be by
- * {@link #setAllExtensions(TestAllExtensionsLite.Builder)}.
+ * Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link
+ * #setAllExtensions(TestAllExtensionsLite.Builder)}.
*/
public static TestAllExtensionsLite getAllLiteExtensionsSet() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
@@ -172,154 +171,137 @@ public final class TestUtilLite {
setPackedExtensions(builder);
return builder.build();
}
-
- /**
- * Set every field of {@code builder} to the values expected by
- * {@code assertAllFieldsSet()}.
- */
+
+ /** Set every field of {@code builder} to the values expected by {@code assertAllFieldsSet()}. */
public static void setAllFields(TestAllTypesLite.Builder builder) {
- builder.setOptionalInt32 (101);
- builder.setOptionalInt64 (102);
- builder.setOptionalUint32 (103);
- builder.setOptionalUint64 (104);
- builder.setOptionalSint32 (105);
- builder.setOptionalSint64 (106);
- builder.setOptionalFixed32 (107);
- builder.setOptionalFixed64 (108);
+ builder.setOptionalInt32(101);
+ builder.setOptionalInt64(102);
+ builder.setOptionalUint32(103);
+ builder.setOptionalUint64(104);
+ builder.setOptionalSint32(105);
+ builder.setOptionalSint64(106);
+ builder.setOptionalFixed32(107);
+ builder.setOptionalFixed64(108);
builder.setOptionalSfixed32(109);
builder.setOptionalSfixed64(110);
- builder.setOptionalFloat (111);
- builder.setOptionalDouble (112);
- builder.setOptionalBool (true);
- builder.setOptionalString ("115");
- builder.setOptionalBytes (toBytes("116"));
-
- builder.setOptionalGroup(
- TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build());
+ builder.setOptionalFloat(111);
+ builder.setOptionalDouble(112);
+ builder.setOptionalBool(true);
+ builder.setOptionalString("115");
+ builder.setOptionalBytes(toBytes("116"));
+
+ builder.setOptionalGroup(TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build());
builder.setOptionalNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
- builder.setOptionalForeignMessage(
- ForeignMessageLite.newBuilder().setC(119).build());
- builder.setOptionalImportMessage(
- ImportMessageLite.newBuilder().setD(120).build());
- builder.setOptionalPublicImportMessage(
- PublicImportMessageLite.newBuilder().setE(126).build());
- builder.setOptionalLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
+ builder.setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(119).build());
+ builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build());
+ builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build());
+ builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
- builder.setOptionalNestedEnum (TestAllTypesLite.NestedEnum.BAZ);
+ builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
- builder.setOptionalImportEnum (ImportEnumLite.IMPORT_LITE_BAZ);
+ builder.setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.setOptionalStringPiece("124");
builder.setOptionalCord("125");
// -----------------------------------------------------------------
- builder.addRepeatedInt32 (201);
- builder.addRepeatedInt64 (202);
- builder.addRepeatedUint32 (203);
- builder.addRepeatedUint64 (204);
- builder.addRepeatedSint32 (205);
- builder.addRepeatedSint64 (206);
- builder.addRepeatedFixed32 (207);
- builder.addRepeatedFixed64 (208);
+ builder.addRepeatedInt32(201);
+ builder.addRepeatedInt64(202);
+ builder.addRepeatedUint32(203);
+ builder.addRepeatedUint64(204);
+ builder.addRepeatedSint32(205);
+ builder.addRepeatedSint64(206);
+ builder.addRepeatedFixed32(207);
+ builder.addRepeatedFixed64(208);
builder.addRepeatedSfixed32(209);
builder.addRepeatedSfixed64(210);
- builder.addRepeatedFloat (211);
- builder.addRepeatedDouble (212);
- builder.addRepeatedBool (true);
- builder.addRepeatedString ("215");
- builder.addRepeatedBytes (toBytes("216"));
-
- builder.addRepeatedGroup(
- TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build());
+ builder.addRepeatedFloat(211);
+ builder.addRepeatedDouble(212);
+ builder.addRepeatedBool(true);
+ builder.addRepeatedString("215");
+ builder.addRepeatedBytes(toBytes("216"));
+
+ builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
- builder.addRepeatedForeignMessage(
- ForeignMessageLite.newBuilder().setC(219).build());
- builder.addRepeatedImportMessage(
- ImportMessageLite.newBuilder().setD(220).build());
- builder.addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
+ builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(219).build());
+ builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(220).build());
+ builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
- builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAR);
+ builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAR);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR);
- builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAR);
+ builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR);
builder.addRepeatedStringPiece("224");
builder.addRepeatedCord("225");
// Add a second one of each field.
- builder.addRepeatedInt32 (301);
- builder.addRepeatedInt64 (302);
- builder.addRepeatedUint32 (303);
- builder.addRepeatedUint64 (304);
- builder.addRepeatedSint32 (305);
- builder.addRepeatedSint64 (306);
- builder.addRepeatedFixed32 (307);
- builder.addRepeatedFixed64 (308);
+ builder.addRepeatedInt32(301);
+ builder.addRepeatedInt64(302);
+ builder.addRepeatedUint32(303);
+ builder.addRepeatedUint64(304);
+ builder.addRepeatedSint32(305);
+ builder.addRepeatedSint64(306);
+ builder.addRepeatedFixed32(307);
+ builder.addRepeatedFixed64(308);
builder.addRepeatedSfixed32(309);
builder.addRepeatedSfixed64(310);
- builder.addRepeatedFloat (311);
- builder.addRepeatedDouble (312);
- builder.addRepeatedBool (false);
- builder.addRepeatedString ("315");
- builder.addRepeatedBytes (toBytes("316"));
-
- builder.addRepeatedGroup(
- TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build());
+ builder.addRepeatedFloat(311);
+ builder.addRepeatedDouble(312);
+ builder.addRepeatedBool(false);
+ builder.addRepeatedString("315");
+ builder.addRepeatedBytes(toBytes("316"));
+
+ builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
- builder.addRepeatedForeignMessage(
- ForeignMessageLite.newBuilder().setC(319).build());
- builder.addRepeatedImportMessage(
- ImportMessageLite.newBuilder().setD(320).build());
- builder.addRepeatedLazyMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
+ builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(319).build());
+ builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(320).build());
+ builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
- builder.addRepeatedNestedEnum (TestAllTypesLite.NestedEnum.BAZ);
+ builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
- builder.addRepeatedImportEnum (ImportEnumLite.IMPORT_LITE_BAZ);
+ builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.addRepeatedStringPiece("324");
builder.addRepeatedCord("325");
// -----------------------------------------------------------------
- builder.setDefaultInt32 (401);
- builder.setDefaultInt64 (402);
- builder.setDefaultUint32 (403);
- builder.setDefaultUint64 (404);
- builder.setDefaultSint32 (405);
- builder.setDefaultSint64 (406);
- builder.setDefaultFixed32 (407);
- builder.setDefaultFixed64 (408);
+ builder.setDefaultInt32(401);
+ builder.setDefaultInt64(402);
+ builder.setDefaultUint32(403);
+ builder.setDefaultUint64(404);
+ builder.setDefaultSint32(405);
+ builder.setDefaultSint64(406);
+ builder.setDefaultFixed32(407);
+ builder.setDefaultFixed64(408);
builder.setDefaultSfixed32(409);
builder.setDefaultSfixed64(410);
- builder.setDefaultFloat (411);
- builder.setDefaultDouble (412);
- builder.setDefaultBool (false);
- builder.setDefaultString ("415");
- builder.setDefaultBytes (toBytes("416"));
+ builder.setDefaultFloat(411);
+ builder.setDefaultDouble(412);
+ builder.setDefaultBool(false);
+ builder.setDefaultString("415");
+ builder.setDefaultBytes(toBytes("416"));
- builder.setDefaultNestedEnum (TestAllTypesLite.NestedEnum.FOO);
+ builder.setDefaultNestedEnum(TestAllTypesLite.NestedEnum.FOO);
builder.setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO);
- builder.setDefaultImportEnum (ImportEnumLite.IMPORT_LITE_FOO);
+ builder.setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_FOO);
builder.setDefaultStringPiece("424");
builder.setDefaultCord("425");
builder.setOneofUint32(601);
- builder.setOneofNestedMessage(
- TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
+ builder.setOneofNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
builder.setOneofString("603");
builder.setOneofBytes(toBytes("604"));
}
/**
- * Get an unmodifiable {@link ExtensionRegistryLite} containing all the
- * extensions of {@code TestAllExtensionsLite}.
+ * Get an unmodifiable {@link ExtensionRegistryLite} containing all the extensions of {@code
+ * TestAllExtensionsLite}.
*/
public static ExtensionRegistryLite getExtensionRegistryLite() {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
@@ -328,8 +310,8 @@ public final class TestUtilLite {
}
/**
- * Register all of {@code TestAllExtensionsLite}'s extensions with the
- * given {@link ExtensionRegistryLite}.
+ * Register all of {@code TestAllExtensionsLite}'s extensions with the given {@link
+ * ExtensionRegistryLite}.
*/
public static void registerAllExtensionsLite(ExtensionRegistryLite registry) {
UnittestLite.registerAllExtensions(registry);
@@ -339,38 +321,40 @@ public final class TestUtilLite {
// Lite extensions
/**
- * Set every field of {@code message} to the values expected by
- * {@code assertAllExtensionsSet()}.
+ * Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
*/
public static void setAllExtensions(TestAllExtensionsLite.Builder message) {
- message.setExtension(optionalInt32ExtensionLite , 101);
- message.setExtension(optionalInt64ExtensionLite , 102L);
- message.setExtension(optionalUint32ExtensionLite , 103);
- message.setExtension(optionalUint64ExtensionLite , 104L);
- message.setExtension(optionalSint32ExtensionLite , 105);
- message.setExtension(optionalSint64ExtensionLite , 106L);
- message.setExtension(optionalFixed32ExtensionLite , 107);
- message.setExtension(optionalFixed64ExtensionLite , 108L);
+ message.setExtension(optionalInt32ExtensionLite, 101);
+ message.setExtension(optionalInt64ExtensionLite, 102L);
+ message.setExtension(optionalUint32ExtensionLite, 103);
+ message.setExtension(optionalUint64ExtensionLite, 104L);
+ message.setExtension(optionalSint32ExtensionLite, 105);
+ message.setExtension(optionalSint64ExtensionLite, 106L);
+ message.setExtension(optionalFixed32ExtensionLite, 107);
+ message.setExtension(optionalFixed64ExtensionLite, 108L);
message.setExtension(optionalSfixed32ExtensionLite, 109);
message.setExtension(optionalSfixed64ExtensionLite, 110L);
- message.setExtension(optionalFloatExtensionLite , 111F);
- message.setExtension(optionalDoubleExtensionLite , 112D);
- message.setExtension(optionalBoolExtensionLite , true);
- message.setExtension(optionalStringExtensionLite , "115");
- message.setExtension(optionalBytesExtensionLite , toBytes("116"));
-
- message.setExtension(optionalGroupExtensionLite,
- OptionalGroup_extension_lite.newBuilder().setA(117).build());
- message.setExtension(optionalNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
- message.setExtension(optionalForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(119).build());
- message.setExtension(optionalImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(120).build());
- message.setExtension(optionalPublicImportMessageExtensionLite,
- PublicImportMessageLite.newBuilder().setE(126).build());
- message.setExtension(optionalLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
+ message.setExtension(optionalFloatExtensionLite, 111F);
+ message.setExtension(optionalDoubleExtensionLite, 112D);
+ message.setExtension(optionalBoolExtensionLite, true);
+ message.setExtension(optionalStringExtensionLite, "115");
+ message.setExtension(optionalBytesExtensionLite, toBytes("116"));
+
+ message.setExtension(
+ optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build());
+ message.setExtension(
+ optionalNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
+ message.setExtension(
+ optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build());
+ message.setExtension(
+ optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build());
+ message.setExtension(
+ optionalPublicImportMessageExtensionLite,
+ PublicImportMessageLite.newBuilder().setE(126).build());
+ message.setExtension(
+ optionalLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
@@ -381,32 +365,34 @@ public final class TestUtilLite {
// -----------------------------------------------------------------
- message.addExtension(repeatedInt32ExtensionLite , 201);
- message.addExtension(repeatedInt64ExtensionLite , 202L);
- message.addExtension(repeatedUint32ExtensionLite , 203);
- message.addExtension(repeatedUint64ExtensionLite , 204L);
- message.addExtension(repeatedSint32ExtensionLite , 205);
- message.addExtension(repeatedSint64ExtensionLite , 206L);
- message.addExtension(repeatedFixed32ExtensionLite , 207);
- message.addExtension(repeatedFixed64ExtensionLite , 208L);
+ message.addExtension(repeatedInt32ExtensionLite, 201);
+ message.addExtension(repeatedInt64ExtensionLite, 202L);
+ message.addExtension(repeatedUint32ExtensionLite, 203);
+ message.addExtension(repeatedUint64ExtensionLite, 204L);
+ message.addExtension(repeatedSint32ExtensionLite, 205);
+ message.addExtension(repeatedSint64ExtensionLite, 206L);
+ message.addExtension(repeatedFixed32ExtensionLite, 207);
+ message.addExtension(repeatedFixed64ExtensionLite, 208L);
message.addExtension(repeatedSfixed32ExtensionLite, 209);
message.addExtension(repeatedSfixed64ExtensionLite, 210L);
- message.addExtension(repeatedFloatExtensionLite , 211F);
- message.addExtension(repeatedDoubleExtensionLite , 212D);
- message.addExtension(repeatedBoolExtensionLite , true);
- message.addExtension(repeatedStringExtensionLite , "215");
- message.addExtension(repeatedBytesExtensionLite , toBytes("216"));
-
- message.addExtension(repeatedGroupExtensionLite,
- RepeatedGroup_extension_lite.newBuilder().setA(217).build());
- message.addExtension(repeatedNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
- message.addExtension(repeatedForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(219).build());
- message.addExtension(repeatedImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(220).build());
- message.addExtension(repeatedLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
+ message.addExtension(repeatedFloatExtensionLite, 211F);
+ message.addExtension(repeatedDoubleExtensionLite, 212D);
+ message.addExtension(repeatedBoolExtensionLite, true);
+ message.addExtension(repeatedStringExtensionLite, "215");
+ message.addExtension(repeatedBytesExtensionLite, toBytes("216"));
+
+ message.addExtension(
+ repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build());
+ message.addExtension(
+ repeatedNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
+ message.addExtension(
+ repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build());
+ message.addExtension(
+ repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build());
+ message.addExtension(
+ repeatedLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
@@ -416,32 +402,34 @@ public final class TestUtilLite {
message.addExtension(repeatedCordExtensionLite, "225");
// Add a second one of each field.
- message.addExtension(repeatedInt32ExtensionLite , 301);
- message.addExtension(repeatedInt64ExtensionLite , 302L);
- message.addExtension(repeatedUint32ExtensionLite , 303);
- message.addExtension(repeatedUint64ExtensionLite , 304L);
- message.addExtension(repeatedSint32ExtensionLite , 305);
- message.addExtension(repeatedSint64ExtensionLite , 306L);
- message.addExtension(repeatedFixed32ExtensionLite , 307);
- message.addExtension(repeatedFixed64ExtensionLite , 308L);
+ message.addExtension(repeatedInt32ExtensionLite, 301);
+ message.addExtension(repeatedInt64ExtensionLite, 302L);
+ message.addExtension(repeatedUint32ExtensionLite, 303);
+ message.addExtension(repeatedUint64ExtensionLite, 304L);
+ message.addExtension(repeatedSint32ExtensionLite, 305);
+ message.addExtension(repeatedSint64ExtensionLite, 306L);
+ message.addExtension(repeatedFixed32ExtensionLite, 307);
+ message.addExtension(repeatedFixed64ExtensionLite, 308L);
message.addExtension(repeatedSfixed32ExtensionLite, 309);
message.addExtension(repeatedSfixed64ExtensionLite, 310L);
- message.addExtension(repeatedFloatExtensionLite , 311F);
- message.addExtension(repeatedDoubleExtensionLite , 312D);
- message.addExtension(repeatedBoolExtensionLite , false);
- message.addExtension(repeatedStringExtensionLite , "315");
- message.addExtension(repeatedBytesExtensionLite , toBytes("316"));
-
- message.addExtension(repeatedGroupExtensionLite,
- RepeatedGroup_extension_lite.newBuilder().setA(317).build());
- message.addExtension(repeatedNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
- message.addExtension(repeatedForeignMessageExtensionLite,
- ForeignMessageLite.newBuilder().setC(319).build());
- message.addExtension(repeatedImportMessageExtensionLite,
- ImportMessageLite.newBuilder().setD(320).build());
- message.addExtension(repeatedLazyMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
+ message.addExtension(repeatedFloatExtensionLite, 311F);
+ message.addExtension(repeatedDoubleExtensionLite, 312D);
+ message.addExtension(repeatedBoolExtensionLite, false);
+ message.addExtension(repeatedStringExtensionLite, "315");
+ message.addExtension(repeatedBytesExtensionLite, toBytes("316"));
+
+ message.addExtension(
+ repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build());
+ message.addExtension(
+ repeatedNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
+ message.addExtension(
+ repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build());
+ message.addExtension(
+ repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build());
+ message.addExtension(
+ repeatedLazyMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
@@ -452,21 +440,21 @@ public final class TestUtilLite {
// -----------------------------------------------------------------
- message.setExtension(defaultInt32ExtensionLite , 401);
- message.setExtension(defaultInt64ExtensionLite , 402L);
- message.setExtension(defaultUint32ExtensionLite , 403);
- message.setExtension(defaultUint64ExtensionLite , 404L);
- message.setExtension(defaultSint32ExtensionLite , 405);
- message.setExtension(defaultSint64ExtensionLite , 406L);
- message.setExtension(defaultFixed32ExtensionLite , 407);
- message.setExtension(defaultFixed64ExtensionLite , 408L);
+ message.setExtension(defaultInt32ExtensionLite, 401);
+ message.setExtension(defaultInt64ExtensionLite, 402L);
+ message.setExtension(defaultUint32ExtensionLite, 403);
+ message.setExtension(defaultUint64ExtensionLite, 404L);
+ message.setExtension(defaultSint32ExtensionLite, 405);
+ message.setExtension(defaultSint64ExtensionLite, 406L);
+ message.setExtension(defaultFixed32ExtensionLite, 407);
+ message.setExtension(defaultFixed64ExtensionLite, 408L);
message.setExtension(defaultSfixed32ExtensionLite, 409);
message.setExtension(defaultSfixed64ExtensionLite, 410L);
- message.setExtension(defaultFloatExtensionLite , 411F);
- message.setExtension(defaultDoubleExtensionLite , 412D);
- message.setExtension(defaultBoolExtensionLite , false);
- message.setExtension(defaultStringExtensionLite , "415");
- message.setExtension(defaultBytesExtensionLite , toBytes("416"));
+ message.setExtension(defaultFloatExtensionLite, 411F);
+ message.setExtension(defaultDoubleExtensionLite, 412D);
+ message.setExtension(defaultBoolExtensionLite, false);
+ message.setExtension(defaultStringExtensionLite, "415");
+ message.setExtension(defaultBytesExtensionLite, toBytes("416"));
message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO);
@@ -476,8 +464,9 @@ public final class TestUtilLite {
message.setExtension(defaultCordExtensionLite, "425");
message.setExtension(oneofUint32ExtensionLite, 601);
- message.setExtension(oneofNestedMessageExtensionLite,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
+ message.setExtension(
+ oneofNestedMessageExtensionLite,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
message.setExtension(oneofStringExtensionLite, "603");
message.setExtension(oneofBytesExtensionLite, toBytes("604"));
}
@@ -485,75 +474,78 @@ public final class TestUtilLite {
// -------------------------------------------------------------------
/**
- * Modify the repeated extensions of {@code message} to contain the values
- * expected by {@code assertRepeatedExtensionsModified()}.
+ * Modify the repeated extensions of {@code message} to contain the values expected by {@code
+ * assertRepeatedExtensionsModified()}.
*/
- public static void modifyRepeatedExtensions(
- TestAllExtensionsLite.Builder message) {
- message.setExtension(repeatedInt32ExtensionLite , 1, 501);
- message.setExtension(repeatedInt64ExtensionLite , 1, 502L);
- message.setExtension(repeatedUint32ExtensionLite , 1, 503);
- message.setExtension(repeatedUint64ExtensionLite , 1, 504L);
- message.setExtension(repeatedSint32ExtensionLite , 1, 505);
- message.setExtension(repeatedSint64ExtensionLite , 1, 506L);
- message.setExtension(repeatedFixed32ExtensionLite , 1, 507);
- message.setExtension(repeatedFixed64ExtensionLite , 1, 508L);
+ public static void modifyRepeatedExtensions(TestAllExtensionsLite.Builder message) {
+ message.setExtension(repeatedInt32ExtensionLite, 1, 501);
+ message.setExtension(repeatedInt64ExtensionLite, 1, 502L);
+ message.setExtension(repeatedUint32ExtensionLite, 1, 503);
+ message.setExtension(repeatedUint64ExtensionLite, 1, 504L);
+ message.setExtension(repeatedSint32ExtensionLite, 1, 505);
+ message.setExtension(repeatedSint64ExtensionLite, 1, 506L);
+ message.setExtension(repeatedFixed32ExtensionLite, 1, 507);
+ message.setExtension(repeatedFixed64ExtensionLite, 1, 508L);
message.setExtension(repeatedSfixed32ExtensionLite, 1, 509);
message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L);
- message.setExtension(repeatedFloatExtensionLite , 1, 511F);
- message.setExtension(repeatedDoubleExtensionLite , 1, 512D);
- message.setExtension(repeatedBoolExtensionLite , 1, true);
- message.setExtension(repeatedStringExtensionLite , 1, "515");
- message.setExtension(repeatedBytesExtensionLite , 1, toBytes("516"));
-
- message.setExtension(repeatedGroupExtensionLite, 1,
- RepeatedGroup_extension_lite.newBuilder().setA(517).build());
- message.setExtension(repeatedNestedMessageExtensionLite, 1,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build());
- message.setExtension(repeatedForeignMessageExtensionLite, 1,
- ForeignMessageLite.newBuilder().setC(519).build());
- message.setExtension(repeatedImportMessageExtensionLite, 1,
- ImportMessageLite.newBuilder().setD(520).build());
- message.setExtension(repeatedLazyMessageExtensionLite, 1,
- TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build());
-
- message.setExtension(repeatedNestedEnumExtensionLite , 1, TestAllTypesLite.NestedEnum.FOO);
+ message.setExtension(repeatedFloatExtensionLite, 1, 511F);
+ message.setExtension(repeatedDoubleExtensionLite, 1, 512D);
+ message.setExtension(repeatedBoolExtensionLite, 1, true);
+ message.setExtension(repeatedStringExtensionLite, 1, "515");
+ message.setExtension(repeatedBytesExtensionLite, 1, toBytes("516"));
+
+ message.setExtension(
+ repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build());
+ message.setExtension(
+ repeatedNestedMessageExtensionLite,
+ 1,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build());
+ message.setExtension(
+ repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build());
+ message.setExtension(
+ repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build());
+ message.setExtension(
+ repeatedLazyMessageExtensionLite,
+ 1,
+ TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build());
+
+ message.setExtension(repeatedNestedEnumExtensionLite, 1, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO);
- message.setExtension(repeatedImportEnumExtensionLite , 1, ImportEnumLite.IMPORT_LITE_FOO);
+ message.setExtension(repeatedImportEnumExtensionLite, 1, ImportEnumLite.IMPORT_LITE_FOO);
message.setExtension(repeatedStringPieceExtensionLite, 1, "524");
message.setExtension(repeatedCordExtensionLite, 1, "525");
}
public static void setPackedExtensions(TestPackedExtensionsLite.Builder message) {
- message.addExtension(packedInt32ExtensionLite , 601);
- message.addExtension(packedInt64ExtensionLite , 602L);
- message.addExtension(packedUint32ExtensionLite , 603);
- message.addExtension(packedUint64ExtensionLite , 604L);
- message.addExtension(packedSint32ExtensionLite , 605);
- message.addExtension(packedSint64ExtensionLite , 606L);
- message.addExtension(packedFixed32ExtensionLite , 607);
- message.addExtension(packedFixed64ExtensionLite , 608L);
+ message.addExtension(packedInt32ExtensionLite, 601);
+ message.addExtension(packedInt64ExtensionLite, 602L);
+ message.addExtension(packedUint32ExtensionLite, 603);
+ message.addExtension(packedUint64ExtensionLite, 604L);
+ message.addExtension(packedSint32ExtensionLite, 605);
+ message.addExtension(packedSint64ExtensionLite, 606L);
+ message.addExtension(packedFixed32ExtensionLite, 607);
+ message.addExtension(packedFixed64ExtensionLite, 608L);
message.addExtension(packedSfixed32ExtensionLite, 609);
message.addExtension(packedSfixed64ExtensionLite, 610L);
- message.addExtension(packedFloatExtensionLite , 611F);
- message.addExtension(packedDoubleExtensionLite , 612D);
- message.addExtension(packedBoolExtensionLite , true);
+ message.addExtension(packedFloatExtensionLite, 611F);
+ message.addExtension(packedDoubleExtensionLite, 612D);
+ message.addExtension(packedBoolExtensionLite, true);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
// Add a second one of each field.
- message.addExtension(packedInt32ExtensionLite , 701);
- message.addExtension(packedInt64ExtensionLite , 702L);
- message.addExtension(packedUint32ExtensionLite , 703);
- message.addExtension(packedUint64ExtensionLite , 704L);
- message.addExtension(packedSint32ExtensionLite , 705);
- message.addExtension(packedSint64ExtensionLite , 706L);
- message.addExtension(packedFixed32ExtensionLite , 707);
- message.addExtension(packedFixed64ExtensionLite , 708L);
+ message.addExtension(packedInt32ExtensionLite, 701);
+ message.addExtension(packedInt64ExtensionLite, 702L);
+ message.addExtension(packedUint32ExtensionLite, 703);
+ message.addExtension(packedUint64ExtensionLite, 704L);
+ message.addExtension(packedSint32ExtensionLite, 705);
+ message.addExtension(packedSint64ExtensionLite, 706L);
+ message.addExtension(packedFixed32ExtensionLite, 707);
+ message.addExtension(packedFixed64ExtensionLite, 708L);
message.addExtension(packedSfixed32ExtensionLite, 709);
message.addExtension(packedSfixed64ExtensionLite, 710L);
- message.addExtension(packedFloatExtensionLite , 711F);
- message.addExtension(packedDoubleExtensionLite , 712D);
- message.addExtension(packedBoolExtensionLite , false);
+ message.addExtension(packedFloatExtensionLite, 711F);
+ message.addExtension(packedDoubleExtensionLite, 712D);
+ message.addExtension(packedBoolExtensionLite, false);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
index e338af21..ff413720 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseInfoTreeTest.java
@@ -33,12 +33,9 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
import junit.framework.TestCase;
-/**
- * Test @{link TextFormatParseInfoTree}.
- */
+/** Test @{link TextFormatParseInfoTree}. */
public class TextFormatParseInfoTreeTest extends TestCase {
private static final Descriptor DESCRIPTOR = TestAllTypes.getDescriptor();
@@ -75,7 +72,7 @@ public class TextFormatParseInfoTreeTest extends TestCase {
TextFormatParseInfoTree root = rootBuilder.build();
assertEquals(LOC0, root.getLocation(OPTIONAL_INT32, 0));
assertEquals(1, root.getLocations(OPTIONAL_INT32).size());
- }
+ }
public void testGetLocationsReturnsNoParseLocationsForUnknownField() {
assertTrue(rootBuilder.build().getLocations(OPTIONAL_INT32).isEmpty());
diff --git a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
index c42bfa6e..19abc3f8 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatParseLocationTest.java
@@ -32,9 +32,7 @@ package com.google.protobuf;
import junit.framework.TestCase;
-/**
- * Test @{link TextFormatParseLocation}.
- */
+/** Test @{link TextFormatParseLocation}. */
public class TextFormatParseLocationTest extends TestCase {
public void testCreateEmpty() {
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 720061d2..d240088c 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -54,7 +54,7 @@ import junit.framework.TestCase;
/**
* Test case for {@link TextFormat}.
*
- * TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc.
+ * <p>TODO(wenboz): ExtensionTest and rest of text_format_unittest.cc.
*
* @author wenboz@google.com (Wenbo Zhu)
*/
@@ -62,76 +62,82 @@ public class TextFormatTest extends TestCase {
// A basic string with different escapable characters for testing.
private static final String ESCAPE_TEST_STRING =
- "\"A string with ' characters \n and \r newlines and \t tabs and \001 " + "slashes \\";
+ "\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\";
// A representation of the above string with all the characters escaped.
private static final String ESCAPE_TEST_STRING_ESCAPED =
"\\\"A string with \\' characters \\n and \\r newlines "
+ "and \\t tabs and \\001 slashes \\\\";
- private static String allFieldsSetText = TestUtil.readTextFromFile(
- "text_format_unittest_data_oneof_implemented.txt");
- private static String allExtensionsSetText = TestUtil.readTextFromFile(
- "text_format_unittest_extensions_data.txt");
+ private static String allFieldsSetText =
+ TestUtil.readTextFromFile("text_format_unittest_data_oneof_implemented.txt");
+ private static String allExtensionsSetText =
+ TestUtil.readTextFromFile("text_format_unittest_extensions_data.txt");
private static String exoticText =
- "repeated_int32: -1\n" +
- "repeated_int32: -2147483648\n" +
- "repeated_int64: -1,\n" +
- "repeated_int64: -9223372036854775808\n" +
- "repeated_uint32: 4294967295\n" +
- "repeated_uint32: 2147483648\n" +
- "repeated_uint64: 18446744073709551615\n" +
- "repeated_uint64: 9223372036854775808\n" +
- "repeated_double: 123.0\n" +
- "repeated_double: 123.5\n" +
- "repeated_double: 0.125\n" +
- "repeated_double: .125\n" +
- "repeated_double: -.125\n" +
- "repeated_double: 1.23E17\n" +
- "repeated_double: 1.23E+17\n" +
- "repeated_double: -1.23e-17\n" +
- "repeated_double: .23e+17\n" +
- "repeated_double: -.23E17\n" +
- "repeated_double: 1.235E22\n" +
- "repeated_double: 1.235E-18\n" +
- "repeated_double: 123.456789\n" +
- "repeated_double: Infinity\n" +
- "repeated_double: -Infinity\n" +
- "repeated_double: NaN\n" +
- "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" +
- "\\341\\210\\264\"\n" +
- "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
+ ""
+ + "repeated_int32: -1\n"
+ + "repeated_int32: -2147483648\n"
+ + "repeated_int64: -1,\n"
+ + "repeated_int64: -9223372036854775808\n"
+ + "repeated_uint32: 4294967295\n"
+ + "repeated_uint32: 2147483648\n"
+ + "repeated_uint64: 18446744073709551615\n"
+ + "repeated_uint64: 9223372036854775808\n"
+ + "repeated_double: 123.0\n"
+ + "repeated_double: 123.5\n"
+ + "repeated_double: 0.125\n"
+ + "repeated_double: .125\n"
+ + "repeated_double: -.125\n"
+ + "repeated_double: 1.23E17\n"
+ + "repeated_double: 1.23E+17\n"
+ + "repeated_double: -1.23e-17\n"
+ + "repeated_double: .23e+17\n"
+ + "repeated_double: -.23E17\n"
+ + "repeated_double: 1.235E22\n"
+ + "repeated_double: 1.235E-18\n"
+ + "repeated_double: 123.456789\n"
+ + "repeated_double: Infinity\n"
+ + "repeated_double: -Infinity\n"
+ + "repeated_double: NaN\n"
+ + "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""
+ + "\\341\\210\\264\"\n"
+ + "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
private static String canonicalExoticText =
- exoticText.replace(": .", ": 0.").replace(": -.", ": -0.") // short-form double
- .replace("23e", "23E").replace("E+", "E").replace("0.23E17", "2.3E16").replace(",", "");
+ exoticText
+ .replace(": .", ": 0.")
+ .replace(": -.", ": -0.") // short-form double
+ .replace("23e", "23E")
+ .replace("E+", "E")
+ .replace("0.23E17", "2.3E16")
+ .replace(",", "");
private String messageSetText =
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 123\n" +
- "}\n" +
- "[protobuf_unittest.TestMessageSetExtension2] {\n" +
- " str: \"foo\"\n" +
- "}\n";
+ ""
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 123\n"
+ + "}\n"
+ + "[protobuf_unittest.TestMessageSetExtension2] {\n"
+ + " str: \"foo\"\n"
+ + "}\n";
private String messageSetTextWithRepeatedExtension =
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 123\n" +
- "}\n" +
- "[protobuf_unittest.TestMessageSetExtension1] {\n" +
- " i: 456\n" +
- "}\n";
+ ""
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 123\n"
+ + "}\n"
+ + "[protobuf_unittest.TestMessageSetExtension1] {\n"
+ + " i: 456\n"
+ + "}\n";
private final TextFormat.Parser parserWithOverwriteForbidden =
TextFormat.Parser.newBuilder()
- .setSingularOverwritePolicy(
- SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
+ .setSingularOverwritePolicy(SingularOverwritePolicy.FORBID_SINGULAR_OVERWRITES)
.build();
- private final TextFormat.Parser defaultParser =
- TextFormat.Parser.newBuilder().build();
+ private final TextFormat.Parser defaultParser = TextFormat.Parser.newBuilder().build();
/** Print TestAllTypes and compare with golden file. */
public void testPrintMessage() throws Exception {
@@ -173,38 +179,32 @@ public class TextFormatTest extends TestCase {
private UnknownFieldSet makeUnknownFieldSet() {
return UnknownFieldSet.newBuilder()
- .addField(5,
+ .addField(
+ 5,
UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .addFixed32(2)
- .addFixed64(3)
- .addLengthDelimited(ByteString.copyFromUtf8("4"))
- .addLengthDelimited(UnknownFieldSet.newBuilder()
- .addField(12,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(6)
+ .addVarint(1)
+ .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, UnknownFieldSet.Field.newBuilder().addVarint(5).build())
.build())
- .build().toByteString())
- .addGroup(
- UnknownFieldSet.newBuilder()
- .addField(10,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(5)
- .build())
.build())
- .build())
- .addField(8,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .addVarint(2)
- .addVarint(3)
- .build())
- .addField(15,
+ .addField(
+ 8, UnknownFieldSet.Field.newBuilder().addVarint(1).addVarint(2).addVarint(3).build())
+ .addField(
+ 15,
UnknownFieldSet.Field.newBuilder()
- .addVarint(0xABCDEF1234567890L)
- .addFixed32(0xABCD1234)
- .addFixed64(0xABCDEF1234567890L)
- .build())
+ .addVarint(0xABCDEF1234567890L)
+ .addFixed32(0xABCD1234)
+ .addFixed64(0xABCDEF1234567890L)
+ .build())
.build();
}
@@ -212,9 +212,7 @@ public class TextFormatTest extends TestCase {
// Test printing of unknown fields in a message.
TestEmptyMessage message =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(makeUnknownFieldSet())
- .build();
+ TestEmptyMessage.newBuilder().setUnknownFields(makeUnknownFieldSet()).build();
assertEquals(
"5: 1\n"
@@ -237,34 +235,29 @@ public class TextFormatTest extends TestCase {
}
public void testPrintField() throws Exception {
- final FieldDescriptor dataField =
- OneString.getDescriptor().findFieldByName("data");
- assertEquals(
- "data: \"test data\"\n",
- TextFormat.printFieldToString(dataField, "test data"));
+ final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data");
+ assertEquals("data: \"test data\"\n", TextFormat.printFieldToString(dataField, "test data"));
final FieldDescriptor optionalField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
final Object value = NestedMessage.newBuilder().setBb(42).build();
assertEquals(
- "optional_nested_message {\n bb: 42\n}\n",
- TextFormat.printFieldToString(optionalField, value));
+ "optional_nested_message {\n bb: 42\n}\n",
+ TextFormat.printFieldToString(optionalField, value));
}
/**
- * Helper to construct a ByteString from a String containing only 8-bit
- * characters. The characters are converted directly to bytes, *not*
- * encoded using UTF-8.
+ * Helper to construct a ByteString from a String containing only 8-bit characters. The characters
+ * are converted directly to bytes, *not* encoded using UTF-8.
*/
private ByteString bytes(String str) {
return ByteString.copyFrom(str.getBytes(Internal.ISO_8859_1));
}
/**
- * Helper to construct a ByteString from a bunch of bytes. The inputs are
- * actually ints so that I can use hex notation and not get stupid errors
- * about precision.
+ * Helper to construct a ByteString from a bunch of bytes. The inputs are actually ints so that I
+ * can use hex notation and not get stupid errors about precision.
*/
private ByteString bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
@@ -275,54 +268,54 @@ public class TextFormatTest extends TestCase {
}
public void testPrintExotic() throws Exception {
- Message message = TestAllTypes.newBuilder()
- // Signed vs. unsigned numbers.
- .addRepeatedInt32 (-1)
- .addRepeatedUint32(-1)
- .addRepeatedInt64 (-1)
- .addRepeatedUint64(-1)
-
- .addRepeatedInt32 (1 << 31)
- .addRepeatedUint32(1 << 31)
- .addRepeatedInt64 (1L << 63)
- .addRepeatedUint64(1L << 63)
-
- // Floats of various precisions and exponents.
- .addRepeatedDouble(123)
- .addRepeatedDouble(123.5)
- .addRepeatedDouble(0.125)
- .addRepeatedDouble(.125)
- .addRepeatedDouble(-.125)
- .addRepeatedDouble(123e15)
- .addRepeatedDouble(123e15)
- .addRepeatedDouble(-1.23e-17)
- .addRepeatedDouble(.23e17)
- .addRepeatedDouble(-23e15)
- .addRepeatedDouble(123.5e20)
- .addRepeatedDouble(123.5e-20)
- .addRepeatedDouble(123.456789)
- .addRepeatedDouble(Double.POSITIVE_INFINITY)
- .addRepeatedDouble(Double.NEGATIVE_INFINITY)
- .addRepeatedDouble(Double.NaN)
-
- // Strings and bytes that needing escaping.
- .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234")
- .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe"))
- .build();
+ Message message =
+ TestAllTypes.newBuilder()
+ // Signed vs. unsigned numbers.
+ .addRepeatedInt32(-1)
+ .addRepeatedUint32(-1)
+ .addRepeatedInt64(-1)
+ .addRepeatedUint64(-1)
+ .addRepeatedInt32(1 << 31)
+ .addRepeatedUint32(1 << 31)
+ .addRepeatedInt64(1L << 63)
+ .addRepeatedUint64(1L << 63)
+
+ // Floats of various precisions and exponents.
+ .addRepeatedDouble(123)
+ .addRepeatedDouble(123.5)
+ .addRepeatedDouble(0.125)
+ .addRepeatedDouble(.125)
+ .addRepeatedDouble(-.125)
+ .addRepeatedDouble(123e15)
+ .addRepeatedDouble(123e15)
+ .addRepeatedDouble(-1.23e-17)
+ .addRepeatedDouble(.23e17)
+ .addRepeatedDouble(-23e15)
+ .addRepeatedDouble(123.5e20)
+ .addRepeatedDouble(123.5e-20)
+ .addRepeatedDouble(123.456789)
+ .addRepeatedDouble(Double.POSITIVE_INFINITY)
+ .addRepeatedDouble(Double.NEGATIVE_INFINITY)
+ .addRepeatedDouble(Double.NaN)
+
+ // Strings and bytes that needing escaping.
+ .addRepeatedString("\0\001\007\b\f\n\r\t\013\\\'\"\u1234")
+ .addRepeatedBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\u00fe"))
+ .build();
assertEquals(canonicalExoticText, message.toString());
}
public void testPrintMessageSet() throws Exception {
TestMessageSet messageSet =
- TestMessageSet.newBuilder()
- .setExtension(
- TestMessageSetExtension1.messageSetExtension,
- TestMessageSetExtension1.newBuilder().setI(123).build())
- .setExtension(
- TestMessageSetExtension2.messageSetExtension,
- TestMessageSetExtension2.newBuilder().setStr("foo").build())
- .build();
+ TestMessageSet.newBuilder()
+ .setExtension(
+ TestMessageSetExtension1.messageSetExtension,
+ TestMessageSetExtension1.newBuilder().setI(123).build())
+ .setExtension(
+ TestMessageSetExtension2.messageSetExtension,
+ TestMessageSetExtension2.newBuilder().setStr("foo").build())
+ .build();
assertEquals(messageSetText, messageSet.toString());
}
@@ -336,22 +329,19 @@ public class TextFormatTest extends TestCase {
}
public void testParse() throws Exception {
- TestUtil.assertAllFieldsSet(
- TextFormat.parse(allFieldsSetText, TestAllTypes.class));
+ TestUtil.assertAllFieldsSet(TextFormat.parse(allFieldsSetText, TestAllTypes.class));
}
public void testMergeInitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
TextFormat.merge(TEST_REQUIRED_INITIALIZED.toString(), builder);
- assertEquals(TEST_REQUIRED_INITIALIZED.toString(),
- builder.buildPartial().toString());
+ assertEquals(TEST_REQUIRED_INITIALIZED.toString(), builder.buildPartial().toString());
assertTrue(builder.isInitialized());
}
public void testParseInitialized() throws Exception {
TestRequired parsed =
- TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(),
- TestRequired.class);
+ TextFormat.parse(TEST_REQUIRED_INITIALIZED.toString(), TestRequired.class);
assertEquals(TEST_REQUIRED_INITIALIZED.toString(), parsed.toString());
assertTrue(parsed.isInitialized());
}
@@ -359,15 +349,13 @@ public class TextFormatTest extends TestCase {
public void testMergeUninitialized() throws Exception {
TestRequired.Builder builder = TestRequired.newBuilder();
TextFormat.merge(TEST_REQUIRED_UNINITIALIZED.toString(), builder);
- assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(),
- builder.buildPartial().toString());
+ assertEquals(TEST_REQUIRED_UNINITIALIZED.toString(), builder.buildPartial().toString());
assertFalse(builder.isInitialized());
}
public void testParseUninitialized() throws Exception {
try {
- TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(),
- TestRequired.class);
+ TextFormat.parse(TEST_REQUIRED_UNINITIALIZED.toString(), TestRequired.class);
fail("Expected UninitializedMessageException.");
} catch (UninitializedMessageException e) {
assertEquals("Message missing required fields: b, c", e.getMessage());
@@ -382,44 +370,43 @@ public class TextFormatTest extends TestCase {
public void testMergeExtensions() throws Exception {
TestAllExtensions.Builder builder = TestAllExtensions.newBuilder();
- TextFormat.merge(allExtensionsSetText,
- TestUtil.getExtensionRegistry(),
- builder);
+ TextFormat.merge(allExtensionsSetText, TestUtil.getFullExtensionRegistry(), builder);
TestUtil.assertAllExtensionsSet(builder.build());
}
public void testParseExtensions() throws Exception {
TestUtil.assertAllExtensionsSet(
- TextFormat.parse(allExtensionsSetText,
- TestUtil.getExtensionRegistry(),
- TestAllExtensions.class));
+ TextFormat.parse(
+ allExtensionsSetText, TestUtil.getFullExtensionRegistry(), TestAllExtensions.class));
}
public void testMergeAndParseCompatibility() throws Exception {
- String original = "repeated_float: inf\n" +
- "repeated_float: -inf\n" +
- "repeated_float: nan\n" +
- "repeated_float: inff\n" +
- "repeated_float: -inff\n" +
- "repeated_float: nanf\n" +
- "repeated_float: 1.0f\n" +
- "repeated_float: infinityf\n" +
- "repeated_float: -Infinityf\n" +
- "repeated_double: infinity\n" +
- "repeated_double: -infinity\n" +
- "repeated_double: nan\n";
- String canonical = "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_float: NaN\n" +
- "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_float: NaN\n" +
- "repeated_float: 1.0\n" +
- "repeated_float: Infinity\n" +
- "repeated_float: -Infinity\n" +
- "repeated_double: Infinity\n" +
- "repeated_double: -Infinity\n" +
- "repeated_double: NaN\n";
+ String original =
+ "repeated_float: inf\n"
+ + "repeated_float: -inf\n"
+ + "repeated_float: nan\n"
+ + "repeated_float: inff\n"
+ + "repeated_float: -inff\n"
+ + "repeated_float: nanf\n"
+ + "repeated_float: 1.0f\n"
+ + "repeated_float: infinityf\n"
+ + "repeated_float: -Infinityf\n"
+ + "repeated_double: infinity\n"
+ + "repeated_double: -infinity\n"
+ + "repeated_double: nan\n";
+ String canonical =
+ "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_float: NaN\n"
+ + "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_float: NaN\n"
+ + "repeated_float: 1.0\n"
+ + "repeated_float: Infinity\n"
+ + "repeated_float: -Infinity\n"
+ + "repeated_double: Infinity\n"
+ + "repeated_double: -Infinity\n"
+ + "repeated_double: NaN\n";
// Test merge().
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
@@ -427,8 +414,7 @@ public class TextFormatTest extends TestCase {
assertEquals(canonical, builder.build().toString());
// Test parse().
- assertEquals(canonical,
- TextFormat.parse(original, TestAllTypes.class).toString());
+ assertEquals(canonical, TextFormat.parse(original, TestAllTypes.class).toString());
}
public void testMergeAndParseExotic() throws Exception {
@@ -438,8 +424,7 @@ public class TextFormatTest extends TestCase {
// Too lazy to check things individually. Don't try to debug this
// if testPrintExotic() is failing.
assertEquals(canonicalExoticText, builder.build().toString());
- assertEquals(canonicalExoticText,
- TextFormat.parse(exoticText, TestAllTypes.class).toString());
+ assertEquals(canonicalExoticText, TextFormat.parse(exoticText, TestAllTypes.class).toString());
}
public void testMergeMessageSet() throws Exception {
@@ -451,21 +436,16 @@ public class TextFormatTest extends TestCase {
TextFormat.merge(messageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.build();
- assertTrue(messageSet.hasExtension(
- TestMessageSetExtension1.messageSetExtension));
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertTrue(messageSet.hasExtension(
- TestMessageSetExtension2.messageSetExtension));
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertTrue(messageSet.hasExtension(TestMessageSetExtension1.messageSetExtension));
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertTrue(messageSet.hasExtension(TestMessageSetExtension2.messageSetExtension));
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
builder = TestMessageSet.newBuilder();
- TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry,
- builder);
+ TextFormat.merge(messageSetTextWithRepeatedExtension, extensionRegistry, builder);
messageSet = builder.build();
- assertEquals(456, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(456, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeMessageSetWithOverwriteForbidden() throws Exception {
@@ -474,13 +454,11 @@ public class TextFormatTest extends TestCase {
extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);
TestMessageSet.Builder builder = TestMessageSet.newBuilder();
- parserWithOverwriteForbidden.merge(
- messageSetText, extensionRegistry, builder);
+ parserWithOverwriteForbidden.merge(messageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
builder = TestMessageSet.newBuilder();
try {
@@ -488,9 +466,10 @@ public class TextFormatTest extends TestCase {
messageSetTextWithRepeatedExtension, extensionRegistry, builder);
fail("expected parse exception");
} catch (TextFormat.ParseException e) {
- assertEquals("6:1: Non-repeated field "
- + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\""
- + " cannot be overwritten.",
+ assertEquals(
+ "6:1: Non-repeated field "
+ + "\"protobuf_unittest.TestMessageSetExtension1.message_set_extension\""
+ + " cannot be overwritten.",
e.getMessage());
}
}
@@ -511,10 +490,11 @@ public class TextFormatTest extends TestCase {
public void testMergeComment() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(
- "# this is a comment\n" +
- "optional_int32: 1 # another comment\n" +
- "optional_int64: 2\n" +
- "# EOF comment", builder);
+ "# this is a comment\n"
+ + "optional_int32: 1 # another comment\n"
+ + "optional_int64: 2\n"
+ + "# EOF comment",
+ builder);
assertEquals(1, builder.getOptionalInt32());
assertEquals(2, builder.getOptionalInt64());
}
@@ -523,7 +503,7 @@ public class TextFormatTest extends TestCase {
// Test merge().
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
- TextFormat.merge(text, TestUtil.getExtensionRegistry(), builder);
+ TextFormat.merge(text, TestUtil.getFullExtensionRegistry(), builder);
fail("Expected parse exception.");
} catch (TextFormat.ParseException e) {
assertEquals(error, e.getMessage());
@@ -531,8 +511,7 @@ public class TextFormatTest extends TestCase {
// Test parse().
try {
- TextFormat.parse(
- text, TestUtil.getExtensionRegistry(), TestAllTypes.class);
+ TextFormat.parse(text, TestUtil.getFullExtensionRegistry(), TestAllTypes.class);
fail("Expected parse exception.");
} catch (TextFormat.ParseException e) {
assertEquals(error, e.getMessage());
@@ -540,131 +519,101 @@ public class TextFormatTest extends TestCase {
}
- private void assertParseErrorWithOverwriteForbidden(String error,
- String text) {
+ private void assertParseErrorWithOverwriteForbidden(String error, String text) {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
try {
- parserWithOverwriteForbidden.merge(
- text, TestUtil.getExtensionRegistry(), builder);
+ parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder);
fail("Expected parse exception.");
} catch (TextFormat.ParseException e) {
assertEquals(error, e.getMessage());
}
}
- private TestAllTypes assertParseSuccessWithOverwriteForbidden(
- String text) throws TextFormat.ParseException {
+ private TestAllTypes assertParseSuccessWithOverwriteForbidden(String text)
+ throws TextFormat.ParseException {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- parserWithOverwriteForbidden.merge(
- text, TestUtil.getExtensionRegistry(), builder);
+ parserWithOverwriteForbidden.merge(text, TestUtil.getFullExtensionRegistry(), builder);
return builder.build();
}
public void testParseErrors() throws Exception {
+ assertParseError("1:16: Expected \":\".", "optional_int32 123");
+ assertParseError("1:23: Expected identifier. Found '?'", "optional_nested_enum: ?");
assertParseError(
- "1:16: Expected \":\".",
- "optional_int32 123");
- assertParseError(
- "1:23: Expected identifier. Found '?'",
- "optional_nested_enum: ?");
- assertParseError(
- "1:18: Couldn't parse integer: Number must be positive: -1",
- "optional_uint32: -1");
- assertParseError(
- "1:17: Couldn't parse integer: Number out of range for 32-bit signed " +
- "integer: 82301481290849012385230157",
- "optional_int32: 82301481290849012385230157");
+ "1:18: Couldn't parse integer: Number must be positive: -1", "optional_uint32: -1");
assertParseError(
- "1:16: Expected \"true\" or \"false\". Found \"maybe\".",
- "optional_bool: maybe");
+ "1:17: Couldn't parse integer: Number out of range for 32-bit signed "
+ + "integer: 82301481290849012385230157",
+ "optional_int32: 82301481290849012385230157");
assertParseError(
- "1:16: Expected \"true\" or \"false\". Found \"2\".",
- "optional_bool: 2");
+ "1:16: Expected \"true\" or \"false\". Found \"maybe\".", "optional_bool: maybe");
+ assertParseError("1:16: Expected \"true\" or \"false\". Found \"2\".", "optional_bool: 2");
+ assertParseError("1:18: Expected string.", "optional_string: 123");
+ assertParseError("1:18: String missing ending quote.", "optional_string: \"ueoauaoe");
assertParseError(
- "1:18: Expected string.",
- "optional_string: 123");
+ "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123");
+ assertParseError("1:18: Invalid escape sequence: '\\z'", "optional_string: \"\\z\"");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe");
+ "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\noptional_int32: 123");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe\n" +
- "optional_int32: 123");
+ "1:2: Input contains unknown fields and/or extensions:\n"
+ + "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]",
+ "[nosuchext]: 123");
assertParseError(
- "1:18: Invalid escape sequence: '\\z'",
- "optional_string: \"\\z\"");
+ "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does "
+ + "not extend message type \"protobuf_unittest.TestAllTypes\".",
+ "[protobuf_unittest.optional_int32_extension]: 123");
assertParseError(
- "1:18: String missing ending quote.",
- "optional_string: \"ueoauaoe\n" +
- "optional_int32: 123");
+ "1:1: Input contains unknown fields and/or extensions:\n"
+ + "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield",
+ "nosuchfield: 123");
+ assertParseError("1:21: Expected \">\".", "OptionalGroup < a: 1");
assertParseError(
- "1:2: Input contains unknown fields and/or extensions:\n" +
- "1:2:\tprotobuf_unittest.TestAllTypes.[nosuchext]",
- "[nosuchext]: 123");
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no "
+ + "value named \"NO_SUCH_VALUE\".",
+ "optional_nested_enum: NO_SUCH_VALUE");
assertParseError(
- "1:20: Extension \"protobuf_unittest.optional_int32_extension\" does " +
- "not extend message type \"protobuf_unittest.TestAllTypes\".",
- "[protobuf_unittest.optional_int32_extension]: 123");
- assertParseError(
- "1:1: Input contains unknown fields and/or extensions:\n" +
- "1:1:\tprotobuf_unittest.TestAllTypes.nosuchfield",
- "nosuchfield: 123");
- assertParseError(
- "1:21: Expected \">\".",
- "OptionalGroup < a: 1");
- assertParseError(
- "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
- "value named \"NO_SUCH_VALUE\".",
- "optional_nested_enum: NO_SUCH_VALUE");
- assertParseError(
- "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
- "value with number 123.",
- "optional_nested_enum: 123");
+ "1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no "
+ + "value with number 123.",
+ "optional_nested_enum: 123");
// Delimiters must match.
- assertParseError(
- "1:22: Expected identifier. Found '}'",
- "OptionalGroup < a: 1 }");
- assertParseError(
- "1:22: Expected identifier. Found '>'",
- "OptionalGroup { a: 1 >");
+ assertParseError("1:22: Expected identifier. Found '}'", "OptionalGroup < a: 1 }");
+ assertParseError("1:22: Expected identifier. Found '>'", "OptionalGroup { a: 1 >");
}
// =================================================================
public void testEscape() throws Exception {
// Escape sequences.
- assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
- TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177")));
- assertEquals("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
- TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177"));
- assertEquals(bytes("\0\001\007\b\f\n\r\t\013\\\'\""),
- TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
- assertEquals("\0\001\007\b\f\n\r\t\013\\\'\"",
- TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+ assertEquals(
+ "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
+ TextFormat.escapeBytes(bytes("\0\001\007\b\f\n\r\t\013\\\'\"\177")));
+ assertEquals(
+ "\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\177",
+ TextFormat.escapeText("\0\001\007\b\f\n\r\t\013\\\'\"\177"));
+ assertEquals(
+ bytes("\0\001\007\b\f\n\r\t\013\\\'\""),
+ TextFormat.unescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
+ assertEquals(
+ "\0\001\007\b\f\n\r\t\013\\\'\"",
+ TextFormat.unescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
assertEquals(ESCAPE_TEST_STRING_ESCAPED, TextFormat.escapeText(ESCAPE_TEST_STRING));
assertEquals(ESCAPE_TEST_STRING, TextFormat.unescapeText(ESCAPE_TEST_STRING_ESCAPED));
// Invariant
- assertEquals("hello",
- TextFormat.escapeBytes(bytes("hello")));
- assertEquals("hello",
- TextFormat.escapeText("hello"));
- assertEquals(bytes("hello"),
- TextFormat.unescapeBytes("hello"));
- assertEquals("hello",
- TextFormat.unescapeText("hello"));
+ assertEquals("hello", TextFormat.escapeBytes(bytes("hello")));
+ assertEquals("hello", TextFormat.escapeText("hello"));
+ assertEquals(bytes("hello"), TextFormat.unescapeBytes("hello"));
+ assertEquals("hello", TextFormat.unescapeText("hello"));
// Unicode handling.
assertEquals("\\341\\210\\264", TextFormat.escapeText("\u1234"));
- assertEquals("\\341\\210\\264",
- TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4)));
+ assertEquals("\\341\\210\\264", TextFormat.escapeBytes(bytes(0xe1, 0x88, 0xb4)));
assertEquals("\u1234", TextFormat.unescapeText("\\341\\210\\264"));
- assertEquals(bytes(0xe1, 0x88, 0xb4),
- TextFormat.unescapeBytes("\\341\\210\\264"));
+ assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\341\\210\\264"));
assertEquals("\u1234", TextFormat.unescapeText("\\xe1\\x88\\xb4"));
- assertEquals(bytes(0xe1, 0x88, 0xb4),
- TextFormat.unescapeBytes("\\xe1\\x88\\xb4"));
+ assertEquals(bytes(0xe1, 0x88, 0xb4), TextFormat.unescapeBytes("\\xe1\\x88\\xb4"));
// Handling of strings with unescaped Unicode characters > 255.
final String zh = "\u9999\u6e2f\u4e0a\u6d77\ud84f\udf80\u8c50\u9280\u884c";
@@ -695,53 +644,48 @@ public class TextFormatTest extends TestCase {
}
public void testParseInteger() throws Exception {
- assertEquals( 0, TextFormat.parseInt32( "0"));
- assertEquals( 1, TextFormat.parseInt32( "1"));
- assertEquals( -1, TextFormat.parseInt32( "-1"));
- assertEquals( 12345, TextFormat.parseInt32( "12345"));
- assertEquals( -12345, TextFormat.parseInt32( "-12345"));
- assertEquals( 2147483647, TextFormat.parseInt32( "2147483647"));
+ assertEquals(0, TextFormat.parseInt32("0"));
+ assertEquals(1, TextFormat.parseInt32("1"));
+ assertEquals(-1, TextFormat.parseInt32("-1"));
+ assertEquals(12345, TextFormat.parseInt32("12345"));
+ assertEquals(-12345, TextFormat.parseInt32("-12345"));
+ assertEquals(2147483647, TextFormat.parseInt32("2147483647"));
assertEquals(-2147483648, TextFormat.parseInt32("-2147483648"));
- assertEquals( 0, TextFormat.parseUInt32( "0"));
- assertEquals( 1, TextFormat.parseUInt32( "1"));
- assertEquals( 12345, TextFormat.parseUInt32( "12345"));
- assertEquals( 2147483647, TextFormat.parseUInt32("2147483647"));
+ assertEquals(0, TextFormat.parseUInt32("0"));
+ assertEquals(1, TextFormat.parseUInt32("1"));
+ assertEquals(12345, TextFormat.parseUInt32("12345"));
+ assertEquals(2147483647, TextFormat.parseUInt32("2147483647"));
assertEquals((int) 2147483648L, TextFormat.parseUInt32("2147483648"));
assertEquals((int) 4294967295L, TextFormat.parseUInt32("4294967295"));
- assertEquals( 0L, TextFormat.parseInt64( "0"));
- assertEquals( 1L, TextFormat.parseInt64( "1"));
- assertEquals( -1L, TextFormat.parseInt64( "-1"));
- assertEquals( 12345L, TextFormat.parseInt64( "12345"));
- assertEquals( -12345L, TextFormat.parseInt64( "-12345"));
- assertEquals( 2147483647L, TextFormat.parseInt64( "2147483647"));
+ assertEquals(0L, TextFormat.parseInt64("0"));
+ assertEquals(1L, TextFormat.parseInt64("1"));
+ assertEquals(-1L, TextFormat.parseInt64("-1"));
+ assertEquals(12345L, TextFormat.parseInt64("12345"));
+ assertEquals(-12345L, TextFormat.parseInt64("-12345"));
+ assertEquals(2147483647L, TextFormat.parseInt64("2147483647"));
assertEquals(-2147483648L, TextFormat.parseInt64("-2147483648"));
- assertEquals( 4294967295L, TextFormat.parseInt64( "4294967295"));
- assertEquals( 4294967296L, TextFormat.parseInt64( "4294967296"));
- assertEquals(9223372036854775807L,
- TextFormat.parseInt64("9223372036854775807"));
- assertEquals(-9223372036854775808L,
- TextFormat.parseInt64("-9223372036854775808"));
-
- assertEquals( 0L, TextFormat.parseUInt64( "0"));
- assertEquals( 1L, TextFormat.parseUInt64( "1"));
- assertEquals( 12345L, TextFormat.parseUInt64( "12345"));
- assertEquals( 2147483647L, TextFormat.parseUInt64( "2147483647"));
- assertEquals( 4294967295L, TextFormat.parseUInt64( "4294967295"));
- assertEquals( 4294967296L, TextFormat.parseUInt64( "4294967296"));
- assertEquals(9223372036854775807L,
- TextFormat.parseUInt64("9223372036854775807"));
- assertEquals(-9223372036854775808L,
- TextFormat.parseUInt64("9223372036854775808"));
+ assertEquals(4294967295L, TextFormat.parseInt64("4294967295"));
+ assertEquals(4294967296L, TextFormat.parseInt64("4294967296"));
+ assertEquals(9223372036854775807L, TextFormat.parseInt64("9223372036854775807"));
+ assertEquals(-9223372036854775808L, TextFormat.parseInt64("-9223372036854775808"));
+
+ assertEquals(0L, TextFormat.parseUInt64("0"));
+ assertEquals(1L, TextFormat.parseUInt64("1"));
+ assertEquals(12345L, TextFormat.parseUInt64("12345"));
+ assertEquals(2147483647L, TextFormat.parseUInt64("2147483647"));
+ assertEquals(4294967295L, TextFormat.parseUInt64("4294967295"));
+ assertEquals(4294967296L, TextFormat.parseUInt64("4294967296"));
+ assertEquals(9223372036854775807L, TextFormat.parseUInt64("9223372036854775807"));
+ assertEquals(-9223372036854775808L, TextFormat.parseUInt64("9223372036854775808"));
assertEquals(-1L, TextFormat.parseUInt64("18446744073709551615"));
// Hex
assertEquals(0x1234abcd, TextFormat.parseInt32("0x1234abcd"));
assertEquals(-0x1234abcd, TextFormat.parseInt32("-0x1234abcd"));
assertEquals(-1, TextFormat.parseUInt64("0xffffffffffffffff"));
- assertEquals(0x7fffffffffffffffL,
- TextFormat.parseInt64("0x7fffffffffffffff"));
+ assertEquals(0x7fffffffffffffffL, TextFormat.parseInt64("0x7fffffffffffffff"));
// Octal
assertEquals(01234567, TextFormat.parseInt32("01234567"));
@@ -821,26 +765,26 @@ public class TextFormatTest extends TestCase {
public void testParseLongString() throws Exception {
String longText =
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890" +
- "123456789012345678901234567890123456789012345678901234567890";
+ "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890"
+ + "123456789012345678901234567890123456789012345678901234567890";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge("optional_string: \"" + longText + "\"", builder);
@@ -849,16 +793,16 @@ public class TextFormatTest extends TestCase {
public void testParseBoolean() throws Exception {
String goodText =
- "repeated_bool: t repeated_bool : 0\n" +
- "repeated_bool :f repeated_bool:1\n" +
- "repeated_bool: False repeated_bool: True";
+ "repeated_bool: t repeated_bool : 0\n"
+ + "repeated_bool :f repeated_bool:1\n"
+ + "repeated_bool: False repeated_bool: True";
String goodTextCanonical =
- "repeated_bool: true\n" +
- "repeated_bool: false\n" +
- "repeated_bool: false\n" +
- "repeated_bool: true\n" +
- "repeated_bool: false\n" +
- "repeated_bool: true\n";
+ "repeated_bool: true\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: true\n"
+ + "repeated_bool: false\n"
+ + "repeated_bool: true\n";
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(goodText, builder);
assertEquals(goodTextCanonical, builder.build().toString());
@@ -887,83 +831,75 @@ public class TextFormatTest extends TestCase {
public void testPrintFieldValue() throws Exception {
assertPrintFieldValue("\"Hello\"", "Hello", "repeated_string");
- assertPrintFieldValue("123.0", 123f, "repeated_float");
- assertPrintFieldValue("123.0", 123d, "repeated_double");
- assertPrintFieldValue("123", 123, "repeated_int32");
- assertPrintFieldValue("123", 123L, "repeated_int64");
- assertPrintFieldValue("true", true, "repeated_bool");
+ assertPrintFieldValue("123.0", 123f, "repeated_float");
+ assertPrintFieldValue("123.0", 123d, "repeated_double");
+ assertPrintFieldValue("123", 123, "repeated_int32");
+ assertPrintFieldValue("123", 123L, "repeated_int64");
+ assertPrintFieldValue("true", true, "repeated_bool");
assertPrintFieldValue("4294967295", 0xFFFFFFFF, "repeated_uint32");
- assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL,
- "repeated_uint64");
- assertPrintFieldValue("\"\\001\\002\\003\"",
- ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes");
+ assertPrintFieldValue("18446744073709551615", 0xFFFFFFFFFFFFFFFFL, "repeated_uint64");
+ assertPrintFieldValue(
+ "\"\\001\\002\\003\"", ByteString.copyFrom(new byte[] {1, 2, 3}), "repeated_bytes");
}
- private void assertPrintFieldValue(String expect, Object value,
- String fieldName) throws Exception {
+ private void assertPrintFieldValue(String expect, Object value, String fieldName)
+ throws Exception {
StringBuilder sb = new StringBuilder();
- TextFormat.printFieldValue(
- TestAllTypes.getDescriptor().findFieldByName(fieldName),
- value, sb);
+ TextFormat.printFieldValue(TestAllTypes.getDescriptor().findFieldByName(fieldName), value, sb);
assertEquals(expect, sb.toString());
}
public void testShortDebugString() {
- assertEquals("optional_nested_message { bb: 42 } repeated_int32: 1"
- + " repeated_uint32: 2",
- TextFormat.shortDebugString(TestAllTypes.newBuilder()
- .addRepeatedInt32(1)
- .addRepeatedUint32(2)
- .setOptionalNestedMessage(
- NestedMessage.newBuilder().setBb(42).build())
- .build()));
+ assertEquals(
+ "optional_nested_message { bb: 42 } repeated_int32: 1 repeated_uint32: 2",
+ TextFormat.shortDebugString(
+ TestAllTypes.newBuilder()
+ .addRepeatedInt32(1)
+ .addRepeatedUint32(2)
+ .setOptionalNestedMessage(NestedMessage.newBuilder().setBb(42).build())
+ .build()));
}
public void testShortDebugString_field() {
- final FieldDescriptor dataField =
- OneString.getDescriptor().findFieldByName("data");
- assertEquals(
- "data: \"test data\"",
- TextFormat.shortDebugString(dataField, "test data"));
+ final FieldDescriptor dataField = OneString.getDescriptor().findFieldByName("data");
+ assertEquals("data: \"test data\"", TextFormat.shortDebugString(dataField, "test data"));
final FieldDescriptor optionalField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_message");
final Object value = NestedMessage.newBuilder().setBb(42).build();
assertEquals(
- "optional_nested_message { bb: 42 }",
- TextFormat.shortDebugString(optionalField, value));
+ "optional_nested_message { bb: 42 }", TextFormat.shortDebugString(optionalField, value));
}
public void testShortDebugString_unknown() {
- 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",
+ 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()));
}
public void testPrintToUnicodeString() throws Exception {
assertEquals(
- "optional_string: \"abc\u3042efg\"\n" +
- "optional_bytes: \"\\343\\201\\202\"\n" +
- "repeated_string: \"\u3093XYZ\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("abc\u3042efg")
- .setOptionalBytes(bytes(0xe3, 0x81, 0x82))
- .addRepeatedString("\u3093XYZ")
- .build()));
+ "optional_string: \"abc\u3042efg\"\n"
+ + "optional_bytes: \"\\343\\201\\202\"\n"
+ + "repeated_string: \"\u3093XYZ\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder()
+ .setOptionalString("abc\u3042efg")
+ .setOptionalBytes(bytes(0xe3, 0x81, 0x82))
+ .addRepeatedString("\u3093XYZ")
+ .build()));
// Double quotes and backslashes should be escaped
assertEquals(
"optional_string: \"a\\\\bc\\\"ef\\\"g\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("a\\bc\"ef\"g")
- .build()));
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("a\\bc\"ef\"g").build()));
// Test escaping roundtrip
- TestAllTypes message = TestAllTypes.newBuilder()
- .setOptionalString("a\\bc\\\"ef\"g")
- .build();
+ TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("a\\bc\\\"ef\"g").build();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(TextFormat.printToUnicodeString(message), builder);
assertEquals(message.getOptionalString(), builder.getOptionalString());
@@ -971,35 +907,34 @@ public class TextFormatTest extends TestCase {
public void testPrintToUnicodeStringWithNewlines() throws Exception {
// No newlines at start and end
- assertEquals("optional_string: \"test newlines\\n\\nin\\nstring\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("test newlines\n\nin\nstring")
- .build()));
+ assertEquals(
+ "optional_string: \"test newlines\\n\\nin\\nstring\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("test newlines\n\nin\nstring").build()));
// Newlines at start and end
- assertEquals("optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
- .build()));
+ assertEquals(
+ "optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder()
+ .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
+ .build()));
// Strings with 0, 1 and 2 newlines.
- assertEquals("optional_string: \"\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("")
- .build()));
- assertEquals("optional_string: \"\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\n")
- .build()));
- assertEquals("optional_string: \"\\n\\n\"\n",
- TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
- .setOptionalString("\n\n")
- .build()));
+ assertEquals(
+ "optional_string: \"\"\n",
+ TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("").build()));
+ assertEquals(
+ "optional_string: \"\\n\"\n",
+ TextFormat.printToUnicodeString(TestAllTypes.newBuilder().setOptionalString("\n").build()));
+ assertEquals(
+ "optional_string: \"\\n\\n\"\n",
+ TextFormat.printToUnicodeString(
+ TestAllTypes.newBuilder().setOptionalString("\n\n").build()));
// Test escaping roundtrip
- TestAllTypes message = TestAllTypes.newBuilder()
- .setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
- .build();
+ TestAllTypes message =
+ TestAllTypes.newBuilder().setOptionalString("\ntest\nnewlines\n\nin\nstring\n").build();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(TextFormat.printToUnicodeString(message), builder);
assertEquals(message.getOptionalString(), builder.getOptionalString());
@@ -1008,57 +943,51 @@ public class TextFormatTest extends TestCase {
public void testPrintToUnicodeString_unknown() {
assertEquals(
"1: \"\\343\\201\\202\"\n",
- TextFormat.printToUnicodeString(UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(bytes(0xe3, 0x81, 0x82)).build())
- .build()));
+ TextFormat.printToUnicodeString(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ 1,
+ UnknownFieldSet.Field.newBuilder()
+ .addLengthDelimited(bytes(0xe3, 0x81, 0x82))
+ .build())
+ .build()));
}
// See additional coverage in testOneofOverwriteForbidden and testMapOverwriteForbidden.
public void testParseNonRepeatedFields() throws Exception {
+ assertParseSuccessWithOverwriteForbidden("repeated_int32: 1\nrepeated_int32: 2\n");
+ assertParseSuccessWithOverwriteForbidden("RepeatedGroup { a: 1 }\nRepeatedGroup { a: 2 }\n");
assertParseSuccessWithOverwriteForbidden(
- "repeated_int32: 1\n" +
- "repeated_int32: 2\n");
- assertParseSuccessWithOverwriteForbidden(
- "RepeatedGroup { a: 1 }\n" +
- "RepeatedGroup { a: 2 }\n");
- assertParseSuccessWithOverwriteForbidden(
- "repeated_nested_message { bb: 1 }\n" +
- "repeated_nested_message { bb: 2 }\n");
+ "repeated_nested_message { bb: 1 }\nrepeated_nested_message { bb: 2 }\n");
assertParseErrorWithOverwriteForbidden(
- "3:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optional_int32\" " +
- "cannot be overwritten.",
- "optional_int32: 1\n" +
- "optional_bool: true\n" +
- "optional_int32: 1\n");
+ "3:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optional_int32\" "
+ + "cannot be overwritten.",
+ "optional_int32: 1\noptional_bool: true\noptional_int32: 1\n");
assertParseErrorWithOverwriteForbidden(
- "2:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optionalgroup\" " +
- "cannot be overwritten.",
- "OptionalGroup { a: 1 }\n" +
- "OptionalGroup { }\n");
+ "2:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optionalgroup\" "
+ + "cannot be overwritten.",
+ "OptionalGroup { a: 1 }\nOptionalGroup { }\n");
assertParseErrorWithOverwriteForbidden(
- "2:33: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.optional_nested_message\" " +
- "cannot be overwritten.",
- "optional_nested_message { }\n" +
- "optional_nested_message { bb: 3 }\n");
+ "2:33: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.optional_nested_message\" "
+ + "cannot be overwritten.",
+ "optional_nested_message { }\noptional_nested_message { bb: 3 }\n");
assertParseErrorWithOverwriteForbidden(
- "2:16: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.default_int32\" " +
- "cannot be overwritten.",
- "default_int32: 41\n" + // the default value
- "default_int32: 41\n");
+ "2:16: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.default_int32\" "
+ + "cannot be overwritten.",
+ "default_int32: 41\n"
+ + // the default value
+ "default_int32: 41\n");
assertParseErrorWithOverwriteForbidden(
- "2:17: Non-repeated field " +
- "\"protobuf_unittest.TestAllTypes.default_string\" " +
- "cannot be overwritten.",
- "default_string: \"zxcv\"\n" +
- "default_string: \"asdf\"\n");
+ "2:17: Non-repeated field "
+ + "\"protobuf_unittest.TestAllTypes.default_string\" "
+ + "cannot be overwritten.",
+ "default_string: \"zxcv\"\ndefault_string: \"asdf\"\n");
}
public void testParseShortRepeatedFormOfRepeatedFields() throws Exception {
@@ -1079,27 +1008,20 @@ public class TextFormatTest extends TestCase {
public void testParseShortRepeatedFormWithTrailingComma() throws Exception {
assertParseErrorWithOverwriteForbidden(
- "1:38: Expected identifier. Found \']\'",
- "repeated_foreign_enum: [FOREIGN_FOO, ]\n");
- assertParseErrorWithOverwriteForbidden(
- "1:22: Couldn't parse integer: For input string: \"]\"",
- "repeated_int32: [ 1, ]\n");
+ "1:38: Expected identifier. Found \']\'", "repeated_foreign_enum: [FOREIGN_FOO, ]\n");
assertParseErrorWithOverwriteForbidden(
- "1:25: Expected \"{\".",
- "RepeatedGroup [{ a: 1 },]\n");
+ "1:22: Couldn't parse integer: For input string: \"]\"", "repeated_int32: [ 1, ]\n");
+ assertParseErrorWithOverwriteForbidden("1:25: Expected \"{\".", "RepeatedGroup [{ a: 1 },]\n");
assertParseErrorWithOverwriteForbidden(
- "1:37: Expected \"{\".",
- "repeated_nested_message [{ bb: 1 }, ]\n");
+ "1:37: Expected \"{\".", "repeated_nested_message [{ bb: 1 }, ]\n");
// See also testMapShortFormTrailingComma.
}
public void testParseShortRepeatedFormOfNonRepeatedFields() throws Exception {
assertParseErrorWithOverwriteForbidden(
- "1:17: Couldn't parse integer: For input string: \"[\"",
- "optional_int32: [1]\n");
+ "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: [1]\n");
assertParseErrorWithOverwriteForbidden(
- "1:17: Couldn't parse integer: For input string: \"[\"",
- "optional_int32: []\n");
+ "1:17: Couldn't parse integer: For input string: \"[\"", "optional_int32: []\n");
}
// =======================================================================
@@ -1118,20 +1040,21 @@ public class TextFormatTest extends TestCase {
String input = "foo_string: \"stringvalue\" foo_int: 123";
TestOneof2.Builder builder = TestOneof2.newBuilder();
try {
- parserWithOverwriteForbidden.merge(
- input, TestUtil.getExtensionRegistry(), builder);
+ parserWithOverwriteForbidden.merge(input, TestUtil.getFullExtensionRegistry(), builder);
fail("Expected parse exception.");
} catch (TextFormat.ParseException e) {
- assertEquals("1:36: Field \"protobuf_unittest.TestOneof2.foo_int\""
- + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\","
- + " another member of oneof \"foo\".", e.getMessage());
+ assertEquals(
+ "1:36: Field \"protobuf_unittest.TestOneof2.foo_int\""
+ + " is specified along with field \"protobuf_unittest.TestOneof2.foo_string\","
+ + " another member of oneof \"foo\".",
+ e.getMessage());
}
}
public void testOneofOverwriteAllowed() throws Exception {
String input = "foo_string: \"stringvalue\" foo_int: 123";
TestOneof2.Builder builder = TestOneof2.newBuilder();
- defaultParser.merge(input, TestUtil.getExtensionRegistry(), builder);
+ defaultParser.merge(input, TestUtil.getFullExtensionRegistry(), builder);
// Only the last value sticks.
TestOneof2 oneof = builder.build();
assertFalse(oneof.hasFooString());
@@ -1164,8 +1087,8 @@ public class TextFormatTest extends TestCase {
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";
+ + "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();
@@ -1176,8 +1099,7 @@ public class TextFormatTest extends TestCase {
}
public void testMapShortFormEmpty() throws Exception {
- String text = "string_to_int32_field []\n"
- + "int32_to_message_field: []\n";
+ String text = "string_to_int32_field []\nint32_to_message_field: []\n";
TestMap.Builder dest = TestMap.newBuilder();
parserWithOverwriteForbidden.merge(text, dest);
TestMap message = dest.build();
@@ -1238,19 +1160,19 @@ public class TextFormatTest extends TestCase {
final String stringData =
"optional_int32: 1\n"
- + "optional_int64: 2\n"
- + " optional_double: 2.4\n"
- + "repeated_int32: 5\n"
- + "repeated_int32: 10\n"
- + "optional_nested_message <\n"
- + " bb: 78\n"
- + ">\n"
- + "repeated_nested_message <\n"
- + " bb: 79\n"
- + ">\n"
- + "repeated_nested_message <\n"
- + " bb: 80\n"
- + ">";
+ + "optional_int64: 2\n"
+ + " optional_double: 2.4\n"
+ + "repeated_int32: 5\n"
+ + "repeated_int32: 10\n"
+ + "optional_nested_message <\n"
+ + " bb: 78\n"
+ + ">\n"
+ + "repeated_nested_message <\n"
+ + " bb: 79\n"
+ + ">\n"
+ + "repeated_nested_message <\n"
+ + " bb: 80\n"
+ + ">";
parser.merge(stringData, builder);
TextFormatParseInfoTree tree = treeBuilder.build();
@@ -1310,9 +1232,7 @@ public class TextFormatTest extends TestCase {
fail(
String.format(
"Tree/descriptor/fieldname did not contain index %d, line %d column %d expected",
- index,
- line,
- column));
+ index, line, column));
}
}
}
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 88cbbf86..cc18547b 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownEnumValueTest.java
@@ -39,8 +39,7 @@ import com.google.protobuf.TextFormat.ParseException;
import junit.framework.TestCase;
/**
- * Unit tests for protos that keep unknown enum values rather than discard
- * them as unknown fields.
+ * Unit tests for protos that keep unknown enum values rather than discard them as unknown fields.
*/
public class UnknownEnumValueTest extends TestCase {
public void testUnknownEnumValues() throws Exception {
@@ -58,7 +57,7 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0));
-
+
// Test serialization and parsing.
ByteString data = message.toByteString();
message = TestAllTypes.parseFrom(data);
@@ -71,19 +70,19 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, message.getPackedNestedEnum(0));
-
+
// Test toBuilder().
builder = message.toBuilder();
assertEquals(4321, builder.getOptionalNestedEnumValue());
assertEquals(5432, builder.getRepeatedNestedEnumValue(0));
assertEquals(5432, builder.getRepeatedNestedEnumValueList().get(0).intValue());
- assertEquals(6543, builder.getPackedNestedEnumValue(0));
+ assertEquals(6543, builder.getPackedNestedEnumValue(0));
// Returns UNRECOGNIZED if an enum type is requested.
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getOptionalNestedEnum());
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0));
-
+
// Test mergeFrom().
builder = TestAllTypes.newBuilder().mergeFrom(message);
assertEquals(4321, builder.getOptionalNestedEnumValue());
@@ -95,7 +94,7 @@ public class UnknownEnumValueTest extends TestCase {
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnum(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getRepeatedNestedEnumList().get(0));
assertEquals(TestAllTypes.NestedEnum.UNRECOGNIZED, builder.getPackedNestedEnum(0));
-
+
// Test equals() and hashCode()
TestAllTypes sameMessage = builder.build();
assertEquals(message, sameMessage);
@@ -123,7 +122,7 @@ public class UnknownEnumValueTest extends TestCase {
// Expected.
}
}
-
+
public void testUnknownEnumValueInReflectionApi() throws Exception {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
@@ -132,14 +131,13 @@ public class UnknownEnumValueTest extends TestCase {
EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
TestAllTypes message = builder.build();
-
+
// Getters will return unknown enum values as EnumValueDescriptor.
EnumValueDescriptor unknown4321 =
(EnumValueDescriptor) message.getField(optionalNestedEnumField);
@@ -166,79 +164,78 @@ public class UnknownEnumValueTest extends TestCase {
message = builder.build();
// Like other descriptors, unknown EnumValueDescriptor can be compared by
// object identity.
- assertTrue(unknown6543 == message.getField(optionalNestedEnumField));
- assertTrue(unknown4321 == message.getRepeatedField(repeatedNestedEnumField, 0));
- assertTrue(unknown5432 == message.getRepeatedField(packedNestedEnumField, 0));
+ assertSame(message.getField(optionalNestedEnumField), unknown6543);
+ assertSame(message.getRepeatedField(repeatedNestedEnumField, 0), unknown4321);
+ assertSame(message.getRepeatedField(packedNestedEnumField, 0), unknown5432);
}
-
+
public void testUnknownEnumValueWithDynamicMessage() throws Exception {
Descriptor descriptor = TestAllTypes.getDescriptor();
FieldDescriptor optionalNestedEnumField = descriptor.findFieldByName("optional_nested_enum");
FieldDescriptor repeatedNestedEnumField = descriptor.findFieldByName("repeated_nested_enum");
FieldDescriptor packedNestedEnumField = descriptor.findFieldByName("packed_nested_enum");
EnumDescriptor enumType = TestAllTypes.NestedEnum.getDescriptor();
-
+
Message dynamicMessageDefaultInstance = DynamicMessage.getDefaultInstance(descriptor);
Message.Builder builder = dynamicMessageDefaultInstance.newBuilderForType();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
Message message = builder.build();
- assertEquals(4321,
- ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
- assertEquals(5432,
+ assertEquals(
+ 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
+ assertEquals(
+ 5432,
((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber());
- assertEquals(6543,
+ assertEquals(
+ 6543,
((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber());
-
+
// Test reflection based serialization/parsing implementation.
ByteString data = message.toByteString();
- message = dynamicMessageDefaultInstance
- .newBuilderForType()
- .mergeFrom(data)
- .build();
- assertEquals(4321,
- ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
- assertEquals(5432,
+ message = dynamicMessageDefaultInstance.newBuilderForType().mergeFrom(data).build();
+ assertEquals(
+ 4321, ((EnumValueDescriptor) message.getField(optionalNestedEnumField)).getNumber());
+ assertEquals(
+ 5432,
((EnumValueDescriptor) message.getRepeatedField(repeatedNestedEnumField, 0)).getNumber());
- assertEquals(6543,
+ assertEquals(
+ 6543,
((EnumValueDescriptor) message.getRepeatedField(packedNestedEnumField, 0)).getNumber());
-
+
// Test reflection based equals()/hashCode().
builder = dynamicMessageDefaultInstance.newBuilderForType();
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(4321));
- builder.addRepeatedField(repeatedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(5432));
- builder.addRepeatedField(packedNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(6543));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(4321));
+ builder.addRepeatedField(
+ repeatedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(5432));
+ builder.addRepeatedField(
+ packedNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(6543));
Message sameMessage = builder.build();
assertEquals(message, sameMessage);
assertEquals(message.hashCode(), sameMessage.hashCode());
- builder.setField(optionalNestedEnumField,
- enumType.findValueByNumberCreatingIfUnknown(0));
+ builder.setField(optionalNestedEnumField, enumType.findValueByNumberCreatingIfUnknown(0));
Message differentMessage = builder.build();
assertFalse(message.equals(differentMessage));
}
-
+
public void testUnknownEnumValuesInTextFormat() {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
builder.setOptionalNestedEnumValue(4321);
builder.addRepeatedNestedEnumValue(5432);
builder.addPackedNestedEnumValue(6543);
TestAllTypes message = builder.build();
-
+
// We can print a message with unknown enum values.
String textData = TextFormat.printToString(message);
assertEquals(
"optional_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_4321\n"
- + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n"
- + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n", textData);
-
+ + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n"
+ + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n",
+ textData);
+
// Parsing unknown enum values will fail just like parsing other kinds of
// unknown fields.
try {
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 8ce0ca73..a947d271 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
@@ -110,9 +110,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testMergeFieldFrom() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray());
@@ -123,9 +121,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testSerializedSize() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
CodedInputStream input = CodedInputStream.newInstance(foo.toByteArray());
@@ -136,9 +132,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testHashCodeAfterDeserialization() throws IOException {
- Foo foo = Foo.newBuilder()
- .setValue(2)
- .build();
+ Foo foo = Foo.newBuilder().setValue(2).build();
Foo fooDeserialized = Foo.parseFrom(foo.toByteArray());
@@ -172,8 +166,7 @@ public class UnknownFieldSetLiteTest extends TestCase {
UnknownFieldSetLite builder = UnknownFieldSetLite.newInstance();
builder.mergeVarintField(10, -6);
- CodedInputStream input =
- CodedInputStream.newInstance(toByteString(builder).toByteArray());
+ CodedInputStream input = CodedInputStream.newInstance(toByteString(builder).toByteArray());
int tag = input.readTag();
assertEquals(10, WireFormat.getTagFieldNumber(tag));
@@ -217,8 +210,9 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testMutableCopyOf_empty() {
- UnknownFieldSetLite unknownFields = UnknownFieldSetLite.mutableCopyOf(
- UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance());
+ UnknownFieldSetLite unknownFields =
+ UnknownFieldSetLite.mutableCopyOf(
+ UnknownFieldSetLite.getDefaultInstance(), UnknownFieldSetLite.getDefaultInstance());
unknownFields.checkMutable();
assertEquals(0, unknownFields.getSerializedSize());
@@ -226,18 +220,17 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testRoundTrips() throws InvalidProtocolBufferException {
- Foo foo = Foo.newBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .setExtension(LiteEqualsAndHash.varint, 22)
- .setExtension(LiteEqualsAndHash.fixed32, 44)
- .setExtension(LiteEqualsAndHash.fixed64, 66L)
- .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder()
- .setGroupValue("value")
- .build())
- .build();
+ Foo foo =
+ Foo.newBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .setExtension(LiteEqualsAndHash.varint, 22)
+ .setExtension(LiteEqualsAndHash.fixed32, 44)
+ .setExtension(LiteEqualsAndHash.fixed64, 66L)
+ .setExtension(
+ LiteEqualsAndHash.myGroup,
+ LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build())
+ .build();
Foo copy = Foo.parseFrom(foo.toByteArray());
@@ -310,16 +303,15 @@ public class UnknownFieldSetLiteTest extends TestCase {
}
public void testTruncatedInput() {
- Foo foo = Foo.newBuilder()
- .setValue(1)
- .setExtension(Bar.fooExt, Bar.newBuilder()
- .setName("name")
- .build())
- .setExtension(LiteEqualsAndHash.varint, 22)
- .setExtension(LiteEqualsAndHash.myGroup, LiteEqualsAndHash.MyGroup.newBuilder()
- .setGroupValue("value")
- .build())
- .build();
+ Foo foo =
+ Foo.newBuilder()
+ .setValue(1)
+ .setExtension(Bar.fooExt, Bar.newBuilder().setName("name").build())
+ .setExtension(LiteEqualsAndHash.varint, 22)
+ .setExtension(
+ LiteEqualsAndHash.myGroup,
+ LiteEqualsAndHash.MyGroup.newBuilder().setGroupValue("value").build())
+ .build();
try {
Foo.parseFrom(foo.toByteString().substring(0, foo.toByteString().size() - 10));
@@ -328,63 +320,72 @@ public class UnknownFieldSetLiteTest extends TestCase {
// Expected.
}
}
-
+
public void testMakeImmutable() throws Exception {
UnknownFieldSetLite unknownFields = UnknownFieldSetLite.newInstance();
unknownFields.makeImmutable();
-
+
try {
unknownFields.mergeVarintField(1, 1);
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
try {
unknownFields.mergeLengthDelimitedField(2, ByteString.copyFromUtf8("hello"));
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
try {
unknownFields.mergeFieldFrom(1, CodedInputStream.newInstance(new byte[0]));
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
-
+
public void testEndToEnd() throws Exception {
TestAllTypesLite testAllTypes = TestAllTypesLite.getDefaultInstance();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
testAllTypes = TestAllTypesLite.parseFrom(new byte[0]);
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
+ } catch (UnsupportedOperationException expected) {
+ }
+
testAllTypes = TestAllTypesLite.newBuilder().build();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
- testAllTypes = TestAllTypesLite.newBuilder()
- .setDefaultBool(true)
- .build();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ testAllTypes = TestAllTypesLite.newBuilder().setDefaultBool(true).build();
try {
testAllTypes.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
-
- TestAllExtensionsLite testAllExtensions = TestAllExtensionsLite.newBuilder()
- .mergeFrom(TestAllExtensionsLite.newBuilder()
- .setExtension(UnittestLite.optionalInt32ExtensionLite, 2)
- .build().toByteArray())
- .build();
+ } catch (UnsupportedOperationException expected) {
+ }
+
+ TestAllExtensionsLite testAllExtensions =
+ TestAllExtensionsLite.newBuilder()
+ .mergeFrom(
+ TestAllExtensionsLite.newBuilder()
+ .setExtension(UnittestLite.optionalInt32ExtensionLite, 2)
+ .build()
+ .toByteArray())
+ .build();
try {
testAllExtensions.unknownFields.checkMutable();
fail();
- } catch (UnsupportedOperationException expected) {}
+ } catch (UnsupportedOperationException expected) {
+ }
}
private ByteString toByteString(UnknownFieldSetLite unknownFields) {
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 1a84806a..86630f65 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
@@ -69,13 +69,10 @@ public class UnknownFieldSetTest extends TestCase {
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();
+ 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()) {
+ 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);
@@ -102,34 +99,30 @@ public class UnknownFieldSetTest extends TestCase {
public void testVarint() throws Exception {
UnknownFieldSet.Field field = getField("optional_int32");
assertEquals(1, field.getVarintList().size());
- assertEquals(allFields.getOptionalInt32(),
- (long) field.getVarintList().get(0));
+ assertEquals(allFields.getOptionalInt32(), (long) field.getVarintList().get(0));
}
public void testFixed32() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed32");
assertEquals(1, field.getFixed32List().size());
- assertEquals(allFields.getOptionalFixed32(),
- (int) field.getFixed32List().get(0));
+ assertEquals(allFields.getOptionalFixed32(), (int) field.getFixed32List().get(0));
}
public void testFixed64() throws Exception {
UnknownFieldSet.Field field = getField("optional_fixed64");
assertEquals(1, field.getFixed64List().size());
- assertEquals(allFields.getOptionalFixed64(),
- (long) field.getFixed64List().get(0));
+ assertEquals(allFields.getOptionalFixed64(), (long) field.getFixed64List().get(0));
}
public void testLengthDelimited() throws Exception {
UnknownFieldSet.Field field = getField("optional_bytes");
assertEquals(1, field.getLengthDelimitedList().size());
- assertEquals(allFields.getOptionalBytes(),
- field.getLengthDelimitedList().get(0));
+ assertEquals(allFields.getOptionalBytes(), field.getLengthDelimitedList().get(0));
}
public void testGroup() throws Exception {
Descriptors.FieldDescriptor nestedFieldDescriptor =
- TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a");
+ TestAllTypes.OptionalGroup.getDescriptor().findFieldByName("a");
assertNotNull(nestedFieldDescriptor);
UnknownFieldSet.Field field = getField("optionalgroup");
@@ -139,11 +132,9 @@ public class UnknownFieldSetTest extends TestCase {
assertEquals(1, group.asMap().size());
assertTrue(group.hasField(nestedFieldDescriptor.getNumber()));
- UnknownFieldSet.Field nestedField =
- group.getField(nestedFieldDescriptor.getNumber());
+ UnknownFieldSet.Field nestedField = group.getField(nestedFieldDescriptor.getNumber());
assertEquals(1, nestedField.getVarintList().size());
- assertEquals(allFields.getOptionalGroup().getA(),
- (long) nestedField.getVarintList().get(0));
+ assertEquals(allFields.getOptionalGroup().getA(), (long) nestedField.getVarintList().get(0));
}
public void testSerialize() throws Exception {
@@ -154,59 +145,44 @@ public class UnknownFieldSetTest extends TestCase {
}
public void testCopyFrom() throws Exception {
- TestEmptyMessage message =
- TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build();
+ TestEmptyMessage message = TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).build();
assertEquals(emptyMessage.toString(), message.toString());
}
public void testMergeFrom() throws Exception {
TestEmptyMessage source =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(2,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(2).build())
- .addField(3,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(4).build())
- .build())
- .build();
+ TestEmptyMessage.newBuilder()
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(2, UnknownFieldSet.Field.newBuilder().addVarint(2).build())
+ .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(4).build())
+ .build())
+ .build();
TestEmptyMessage destination =
- TestEmptyMessage.newBuilder()
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1).build())
- .addField(3,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(3).build())
- .build())
- .mergeFrom(source)
- .build();
-
- assertEquals(
- "1: 1\n" +
- "2: 2\n" +
- "3: 3\n" +
- "3: 4\n",
- destination.toString());
+ TestEmptyMessage.newBuilder()
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .addField(3, UnknownFieldSet.Field.newBuilder().addVarint(3).build())
+ .build())
+ .mergeFrom(source)
+ .build();
+
+ assertEquals("1: 1\n2: 2\n3: 3\n3: 4\n", destination.toString());
}
public void testClear() throws Exception {
- UnknownFieldSet fields =
- UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build();
+ UnknownFieldSet fields = UnknownFieldSet.newBuilder().mergeFrom(unknownFields).clear().build();
assertTrue(fields.asMap().isEmpty());
}
public void testClearMessage() throws Exception {
TestEmptyMessage message =
- TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build();
+ TestEmptyMessage.newBuilder().mergeFrom(emptyMessage).clear().build();
assertEquals(0, message.getSerializedSize());
}
-
+
public void testClearField() throws Exception {
int fieldNumber = unknownFields.asMap().keySet().iterator().next();
UnknownFieldSet fields =
@@ -218,10 +194,9 @@ public class UnknownFieldSetTest extends TestCase {
// Test mixing known and unknown fields when parsing.
UnknownFieldSet fields =
- UnknownFieldSet.newBuilder(unknownFields)
- .addField(123456,
- UnknownFieldSet.Field.newBuilder().addVarint(654321).build())
- .build();
+ UnknownFieldSet.newBuilder(unknownFields)
+ .addField(123456, UnknownFieldSet.Field.newBuilder().addVarint(654321).build())
+ .build();
ByteString data = fields.toByteString();
TestAllTypes destination = TestAllTypes.parseFrom(data);
@@ -229,8 +204,7 @@ public class UnknownFieldSetTest extends TestCase {
TestUtil.assertAllFieldsSet(destination);
assertEquals(1, destination.getUnknownFields().asMap().size());
- UnknownFieldSet.Field field =
- destination.getUnknownFields().getField(123456);
+ UnknownFieldSet.Field field = destination.getUnknownFields().getField(123456);
assertEquals(1, field.getVarintList().size());
assertEquals(654321, (long) field.getVarintList().get(0));
}
@@ -253,10 +227,9 @@ public class UnknownFieldSetTest extends TestCase {
// they are declared as extension numbers.
TestEmptyMessageWithExtensions message =
- TestEmptyMessageWithExtensions.parseFrom(allFieldsData);
+ TestEmptyMessageWithExtensions.parseFrom(allFieldsData);
- assertEquals(unknownFields.asMap().size(),
- message.getUnknownFields().asMap().size());
+ assertEquals(unknownFields.asMap().size(), message.getUnknownFields().asMap().size());
assertEquals(allFieldsData, message.toByteString());
}
@@ -265,134 +238,99 @@ public class UnknownFieldSetTest extends TestCase {
// when parsing extensions.
ByteString bizarroData = getBizarroData();
- TestAllExtensions allExtensionsMessage =
- TestAllExtensions.parseFrom(bizarroData);
+ TestAllExtensions allExtensionsMessage = TestAllExtensions.parseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
- assertEquals(emptyMessage.toString(),
- allExtensionsMessage.toString());
+ assertEquals(emptyMessage.toString(), allExtensionsMessage.toString());
}
public void testParseUnknownEnumValue() throws Exception {
Descriptors.FieldDescriptor singularField =
- TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
+ TestAllTypes.getDescriptor().findFieldByName("optional_nested_enum");
Descriptors.FieldDescriptor repeatedField =
- TestAllTypes.getDescriptor().findFieldByName("repeated_nested_enum");
+ 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();
+ 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();
{
TestAllTypes message = TestAllTypes.parseFrom(data);
- assertEquals(TestAllTypes.NestedEnum.BAR,
- message.getOptionalNestedEnum());
+ 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());
+ 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));
+ 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(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());
+ Arrays.asList(5L),
+ message.getUnknownFields().getField(singularField.getNumber()).getVarintList());
+ assertEquals(
+ Arrays.asList(4L, 6L),
+ message.getUnknownFields().getField(repeatedField.getNumber()).getVarintList());
}
}
public void testLargeVarint() throws Exception {
ByteString data =
- UnknownFieldSet.newBuilder()
- .addField(1,
- UnknownFieldSet.Field.newBuilder()
- .addVarint(0x7FFFFFFFFFFFFFFFL)
- .build())
- .build()
- .toByteString();
+ UnknownFieldSet.newBuilder()
+ .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(0x7FFFFFFFFFFFFFFFL).build())
+ .build()
+ .toByteString();
UnknownFieldSet parsed = UnknownFieldSet.parseFrom(data);
UnknownFieldSet.Field field = parsed.getField(1);
assertEquals(1, field.getVarintList().size());
- assertEquals(0x7FFFFFFFFFFFFFFFL, (long)field.getVarintList().get(0));
+ assertEquals(0x7FFFFFFFFFFFFFFFL, (long) field.getVarintList().get(0));
}
public void testEqualsAndHashCode() {
- UnknownFieldSet.Field fixed32Field =
- UnknownFieldSet.Field.newBuilder()
- .addFixed32(1)
- .build();
- UnknownFieldSet.Field fixed64Field =
- UnknownFieldSet.Field.newBuilder()
- .addFixed64(1)
- .build();
- UnknownFieldSet.Field varIntField =
- UnknownFieldSet.Field.newBuilder()
- .addVarint(1)
- .build();
+ UnknownFieldSet.Field fixed32Field = UnknownFieldSet.Field.newBuilder().addFixed32(1).build();
+ UnknownFieldSet.Field fixed64Field = UnknownFieldSet.Field.newBuilder().addFixed64(1).build();
+ UnknownFieldSet.Field varIntField = UnknownFieldSet.Field.newBuilder().addVarint(1).build();
UnknownFieldSet.Field lengthDelimitedField =
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(ByteString.EMPTY)
- .build();
+ UnknownFieldSet.Field.newBuilder().addLengthDelimited(ByteString.EMPTY).build();
UnknownFieldSet.Field groupField =
- UnknownFieldSet.Field.newBuilder()
- .addGroup(unknownFields)
- .build();
+ UnknownFieldSet.Field.newBuilder().addGroup(unknownFields).build();
- UnknownFieldSet a =
- UnknownFieldSet.newBuilder()
- .addField(1, fixed32Field)
- .build();
- UnknownFieldSet b =
- UnknownFieldSet.newBuilder()
- .addField(1, fixed64Field)
- .build();
- UnknownFieldSet c =
- UnknownFieldSet.newBuilder()
- .addField(1, varIntField)
- .build();
- UnknownFieldSet d =
- UnknownFieldSet.newBuilder()
- .addField(1, lengthDelimitedField)
- .build();
- UnknownFieldSet e =
- UnknownFieldSet.newBuilder()
- .addField(1, groupField)
- .build();
+ UnknownFieldSet a = UnknownFieldSet.newBuilder().addField(1, fixed32Field).build();
+ UnknownFieldSet b = UnknownFieldSet.newBuilder().addField(1, fixed64Field).build();
+ UnknownFieldSet c = UnknownFieldSet.newBuilder().addField(1, varIntField).build();
+ UnknownFieldSet d = UnknownFieldSet.newBuilder().addField(1, lengthDelimitedField).build();
+ UnknownFieldSet e = UnknownFieldSet.newBuilder().addField(1, groupField).build();
checkEqualsIsConsistent(a);
checkEqualsIsConsistent(b);
@@ -413,12 +351,10 @@ public class UnknownFieldSetTest extends TestCase {
}
/**
- * Asserts that the given field sets are not equal and have different
- * hash codes.
+ * Asserts that the given field sets are not equal and have different hash codes.
*
- * @warning It's valid for non-equal objects to have the same hash code, so
- * this test is stricter than it needs to be. However, this should happen
- * relatively rarely.
+ * @warning It's valid for non-equal objects to have the same hash code, so this test is stricter
+ * than it needs to be. However, this should happen relatively rarely.
*/
private void checkNotEqual(UnknownFieldSet s1, UnknownFieldSet s2) {
String equalsError = String.format("%s should not be equal to %s", s1, s2);
@@ -430,9 +366,7 @@ public class UnknownFieldSetTest extends TestCase {
s1.hashCode() == s2.hashCode());
}
- /**
- * Asserts that the given field sets are equal and have identical hash codes.
- */
+ /** Asserts that the given field sets are equal and have identical hash codes. */
private void checkEqualsIsConsistent(UnknownFieldSet set) {
// Object should be equal to itself.
assertEquals(set, set);
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 03c33ecf..45a396ac 100644
--- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
@@ -54,6 +54,13 @@ import junit.framework.TestCase;
* @author kenton@google.com (Kenton Varda)
*/
public class WireFormatTest extends TestCase {
+
+ private static final int TYPE_ID_1 =
+ TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber();
+ private static final int TYPE_ID_2 =
+ TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber();
+ private static final int UNKNOWN_TYPE_ID = 1550055;
+
public void testSerialization() throws Exception {
TestAllTypes message = TestUtil.getAllSet();
@@ -102,8 +109,7 @@ public class WireFormatTest extends TestCase {
assertEquals(rawBytes, rawBytes2);
}
- public void testSerializationPackedWithoutGetSerializedSize()
- throws Exception {
+ public void testSerializationPackedWithoutGetSerializedSize() throws Exception {
// Write directly to an OutputStream, without invoking getSerializedSize()
// This used to be a bug where the size of a packed field was incorrect,
// since getSerializedSize() was never invoked.
@@ -118,8 +124,7 @@ public class WireFormatTest extends TestCase {
codedOutput.flush();
- TestPackedTypes message2 = TestPackedTypes.parseFrom(
- outputStream.toByteArray());
+ TestPackedTypes message2 = TestPackedTypes.parseFrom(outputStream.toByteArray());
TestUtil.assertPackedFieldsSet(message2);
}
@@ -132,10 +137,9 @@ public class WireFormatTest extends TestCase {
TestAllTypes message = TestUtil.getAllSet();
ByteString rawBytes = message.toByteString();
- ExtensionRegistry registry = TestUtil.getExtensionRegistry();
+ ExtensionRegistryLite registry = TestUtil.getExtensionRegistry();
- TestAllExtensions message2 =
- TestAllExtensions.parseFrom(rawBytes, registry);
+ TestAllExtensions message2 = TestAllExtensions.parseFrom(rawBytes, registry);
TestUtil.assertAllExtensionsSet(message2);
}
@@ -145,10 +149,9 @@ public class WireFormatTest extends TestCase {
TestPackedExtensions message = TestUtil.getPackedExtensionsSet();
ByteString rawBytes = message.toByteString();
- ExtensionRegistry registry = TestUtil.getExtensionRegistry();
+ ExtensionRegistryLite registry = TestUtil.getExtensionRegistry();
- TestPackedExtensions message2 =
- TestPackedExtensions.parseFrom(rawBytes, registry);
+ TestPackedExtensions message2 = TestPackedExtensions.parseFrom(rawBytes, registry);
TestUtil.assertPackedExtensionsSet(message2);
}
@@ -192,25 +195,27 @@ public class WireFormatTest extends TestCase {
// Tests that fields are written in order even when extension ranges
// are interleaved with field numbers.
ByteString data =
- TestFieldOrderings.newBuilder()
- .setMyInt(1)
- .setMyString("foo")
- .setMyFloat(1.0F)
- .setExtension(UnittestProto.myExtensionInt, 23)
- .setExtension(UnittestProto.myExtensionString, "bar")
- .build().toByteString();
+ TestFieldOrderings.newBuilder()
+ .setMyInt(1)
+ .setMyString("foo")
+ .setMyFloat(1.0F)
+ .setExtension(UnittestProto.myExtensionInt, 23)
+ .setExtension(UnittestProto.myExtensionString, "bar")
+ .build()
+ .toByteString();
assertFieldsInOrder(data);
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
- ByteString dynamic_data =
- DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
- .setField(descriptor.findFieldByName("my_int"), 1L)
- .setField(descriptor.findFieldByName("my_string"), "foo")
- .setField(descriptor.findFieldByName("my_float"), 1.0F)
- .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
- .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
- .build().toByteString();
- assertFieldsInOrder(dynamic_data);
+ ByteString dynamicData =
+ DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
+ .setField(descriptor.findFieldByName("my_int"), 1L)
+ .setField(descriptor.findFieldByName("my_string"), "foo")
+ .setField(descriptor.findFieldByName("my_float"), 1.0F)
+ .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
+ .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
+ .build()
+ .toByteString();
+ assertFieldsInOrder(dynamicData);
}
private ExtensionRegistry getTestFieldOrderingsRegistry() {
@@ -224,36 +229,35 @@ public class WireFormatTest extends TestCase {
// Make sure we can parse a message that contains multiple extensions
// ranges.
TestFieldOrderings source =
- TestFieldOrderings.newBuilder()
- .setMyInt(1)
- .setMyString("foo")
- .setMyFloat(1.0F)
- .setExtension(UnittestProto.myExtensionInt, 23)
- .setExtension(UnittestProto.myExtensionString, "bar")
- .build();
+ TestFieldOrderings.newBuilder()
+ .setMyInt(1)
+ .setMyString("foo")
+ .setMyFloat(1.0F)
+ .setExtension(UnittestProto.myExtensionInt, 23)
+ .setExtension(UnittestProto.myExtensionString, "bar")
+ .build();
TestFieldOrderings dest =
- TestFieldOrderings.parseFrom(source.toByteString(),
- getTestFieldOrderingsRegistry());
+ TestFieldOrderings.parseFrom(source.toByteString(), getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
-
+
private static ExtensionRegistry getTestExtensionInsideTableRegistry() {
ExtensionRegistry result = ExtensionRegistry.newInstance();
result.add(UnittestProto.testExtensionInsideTableExtension);
return result;
}
-
+
public void testExtensionInsideTable() throws Exception {
// Make sure the extension within the range of table is parsed correctly in experimental
// runtime.
TestExtensionInsideTable source =
TestExtensionInsideTable.newBuilder()
- .setField1(1)
- .setExtension(UnittestProto.testExtensionInsideTableExtension, 23)
- .build();
+ .setField1(1)
+ .setExtension(UnittestProto.testExtensionInsideTableExtension, 23)
+ .build();
TestExtensionInsideTable dest =
- TestExtensionInsideTable.parseFrom(source.toByteString(),
- getTestExtensionInsideTableRegistry());
+ TestExtensionInsideTable.parseFrom(
+ source.toByteString(), getTestExtensionInsideTableRegistry());
assertEquals(source, dest);
}
@@ -261,25 +265,19 @@ public class WireFormatTest extends TestCase {
// Same as above except with DynamicMessage.
Descriptors.Descriptor descriptor = TestFieldOrderings.getDescriptor();
DynamicMessage source =
- DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
- .setField(descriptor.findFieldByName("my_int"), 1L)
- .setField(descriptor.findFieldByName("my_string"), "foo")
- .setField(descriptor.findFieldByName("my_float"), 1.0F)
- .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
- .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
- .build();
+ DynamicMessage.newBuilder(TestFieldOrderings.getDescriptor())
+ .setField(descriptor.findFieldByName("my_int"), 1L)
+ .setField(descriptor.findFieldByName("my_string"), "foo")
+ .setField(descriptor.findFieldByName("my_float"), 1.0F)
+ .setField(UnittestProto.myExtensionInt.getDescriptor(), 23)
+ .setField(UnittestProto.myExtensionString.getDescriptor(), "bar")
+ .build();
DynamicMessage dest =
- DynamicMessage.parseFrom(descriptor, source.toByteString(),
- getTestFieldOrderingsRegistry());
+ DynamicMessage.parseFrom(
+ descriptor, source.toByteString(), getTestFieldOrderingsRegistry());
assertEquals(source, dest);
}
- private static final int UNKNOWN_TYPE_ID = 1550055;
- private static final int TYPE_ID_1 =
- TestMessageSetExtension1.getDescriptor().getExtensions().get(0).getNumber();
- private static final int TYPE_ID_2 =
- TestMessageSetExtension2.getDescriptor().getExtensions().get(0).getNumber();
-
public void testSerializeMessageSetEagerly() throws Exception {
testSerializeMessageSetWithFlag(true);
}
@@ -288,26 +286,26 @@ public class WireFormatTest extends TestCase {
testSerializeMessageSetWithFlag(false);
}
- private void testSerializeMessageSetWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testSerializeMessageSetWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
// Set up a TestMessageSet with two known messages and an unknown one.
TestMessageSet messageSet =
- TestMessageSet.newBuilder()
- .setExtension(
- TestMessageSetExtension1.messageSetExtension,
- TestMessageSetExtension1.newBuilder().setI(123).build())
- .setExtension(
- TestMessageSetExtension2.messageSetExtension,
- TestMessageSetExtension2.newBuilder().setStr("foo").build())
- .setUnknownFields(
- UnknownFieldSet.newBuilder()
- .addField(UNKNOWN_TYPE_ID,
- UnknownFieldSet.Field.newBuilder()
- .addLengthDelimited(ByteString.copyFromUtf8("bar"))
- .build())
- .build())
- .build();
+ TestMessageSet.newBuilder()
+ .setExtension(
+ TestMessageSetExtension1.messageSetExtension,
+ TestMessageSetExtension1.newBuilder().setI(123).build())
+ .setExtension(
+ TestMessageSetExtension2.messageSetExtension,
+ TestMessageSetExtension2.newBuilder().setStr("foo").build())
+ .setUnknownFields(
+ UnknownFieldSet.newBuilder()
+ .addField(
+ UNKNOWN_TYPE_ID,
+ UnknownFieldSet.Field.newBuilder()
+ .addLengthDelimited(ByteString.copyFromUtf8("bar"))
+ .build())
+ .build())
+ .build();
ByteString data = messageSet.toByteString();
@@ -322,13 +320,11 @@ public class WireFormatTest extends TestCase {
assertEquals(UNKNOWN_TYPE_ID, raw.getItem(2).getTypeId());
TestMessageSetExtension1 message1 =
- TestMessageSetExtension1.parseFrom(
- raw.getItem(0).getMessage().toByteArray());
+ TestMessageSetExtension1.parseFrom(raw.getItem(0).getMessage());
assertEquals(123, message1.getI());
TestMessageSetExtension2 message2 =
- TestMessageSetExtension2.parseFrom(
- raw.getItem(1).getMessage().toByteArray());
+ TestMessageSetExtension2.parseFrom(raw.getItem(1).getMessage());
assertEquals("foo", message2.getStr());
assertEquals("bar", raw.getItem(2).getMessage().toStringUtf8());
@@ -338,12 +334,11 @@ public class WireFormatTest extends TestCase {
testParseMessageSetWithFlag(true);
}
- public void testParseMessageSetNotEagerly()throws Exception {
+ public void testParseMessageSetNotEagerly() throws Exception {
testParseMessageSetWithFlag(false);
}
- private void testParseMessageSetWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testParseMessageSetWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
@@ -351,40 +346,34 @@ public class WireFormatTest extends TestCase {
// Set up a RawMessageSet with two known messages and an unknown one.
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_2)
- .setMessage(
- TestMessageSetExtension2.newBuilder()
- .setStr("foo")
- .build().toByteString())
- .build())
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(UNKNOWN_TYPE_ID)
- .setMessage(ByteString.copyFromUtf8("bar"))
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_2)
+ .setMessage(
+ TestMessageSetExtension2.newBuilder().setStr("foo").build().toByteString())
+ .build())
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(UNKNOWN_TYPE_ID)
+ .setMessage(ByteString.copyFromUtf8("bar"))
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
- assertEquals("foo", messageSet.getExtension(
- TestMessageSetExtension2.messageSetExtension).getStr());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(
+ "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());
// Check for unknown field with type LENGTH_DELIMITED,
// number UNKNOWN_TYPE_ID, and contents "bar".
@@ -405,35 +394,27 @@ public class WireFormatTest extends TestCase {
testParseMessageSetExtensionWithFlag(false);
}
- private void testParseMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testParseMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and check the contents.
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeLazyMessageSetExtensionEagerly() throws Exception {
@@ -444,38 +425,29 @@ public class WireFormatTest extends TestCase {
testMergeLazyMessageSetExtensionWithFlag(false);
}
- private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testMergeLazyMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
ByteString data = raw.toByteString();
// Parse as a TestMessageSet and store value into lazy field
- TestMessageSet messageSet =
- TestMessageSet.parseFrom(data, extensionRegistry);
+ TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);
// Merge lazy field check the contents.
- messageSet =
- messageSet.toBuilder().mergeFrom(data, extensionRegistry).build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ messageSet = messageSet.toBuilder().mergeFrom(data, extensionRegistry).build();
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
public void testMergeMessageSetExtensionEagerly() throws Exception {
@@ -486,31 +458,24 @@ public class WireFormatTest extends TestCase {
testMergeMessageSetExtensionWithFlag(false);
}
- private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing)
- throws Exception {
+ private void testMergeMessageSetExtensionWithFlag(boolean eagerParsing) throws Exception {
ExtensionRegistryLite.setEagerlyParseMessageSets(eagerParsing);
ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
// Set up a RawMessageSet with a known messages.
- int TYPE_ID_1 =
- TestMessageSetExtension1
- .getDescriptor().getExtensions().get(0).getNumber();
RawMessageSet raw =
- RawMessageSet.newBuilder()
- .addItem(
- RawMessageSet.Item.newBuilder()
- .setTypeId(TYPE_ID_1)
- .setMessage(
- TestMessageSetExtension1.newBuilder()
- .setI(123)
- .build().toByteString())
- .build())
- .build();
+ RawMessageSet.newBuilder()
+ .addItem(
+ RawMessageSet.Item.newBuilder()
+ .setTypeId(TYPE_ID_1)
+ .setMessage(
+ TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
+ .build())
+ .build();
// Serialize RawMessageSet unnormally (message value before type id)
- ByteString.CodedBuilder out = ByteString.newCodedBuilder(
- raw.getSerializedSize());
+ ByteString.CodedBuilder out = ByteString.newCodedBuilder(raw.getSerializedSize());
CodedOutputStream output = out.getCodedOutput();
List<RawMessageSet.Item> items = raw.getItemList();
for (int i = 0; i < items.size(); i++) {
@@ -525,8 +490,7 @@ public class WireFormatTest extends TestCase {
// Merge bytes into TestMessageSet and check the contents.
TestMessageSet messageSet =
TestMessageSet.newBuilder().mergeFrom(data, extensionRegistry).build();
- assertEquals(123, messageSet.getExtension(
- TestMessageSetExtension1.messageSetExtension).getI());
+ assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
}
// ================================================================
@@ -544,8 +508,8 @@ public class WireFormatTest extends TestCase {
}
public void testOneofOnlyLastSet() throws Exception {
- TestOneofBackwardsCompatible source = TestOneofBackwardsCompatible
- .newBuilder().setFooInt(100).setFooString("101").build();
+ TestOneofBackwardsCompatible source =
+ TestOneofBackwardsCompatible.newBuilder().setFooInt(100).setFooString("101").build();
ByteString rawBytes = source.toByteString();
TestOneof2 message = TestOneof2.parseFrom(rawBytes);
diff --git a/java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto b/java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto
index 5580f72d..736a344f 100644
--- a/java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto
+++ b/java/core/src/test/proto/com/google/protobuf/lazy_fields_lite.proto
@@ -36,8 +36,6 @@ syntax = "proto2";
package protobuf_unittest;
-option optimize_for = LITE_RUNTIME;
-
message LazyMessageLite {
optional int32 num = 1;
optional int32 num_with_default = 2 [default = 421];
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 b18b0d79..20fa03b9 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
@@ -34,7 +34,6 @@ syntax = "proto2";
package protobuf_unittest.lite_equals_and_hash;
-option optimize_for = LITE_RUNTIME;
message TestOneofEquals {
oneof oneof_field {
diff --git a/java/pom.xml b/java/pom.xml
index 6526b650..bc71fdc9 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -44,8 +44,8 @@
</licenses>
<scm>
- <url>https://github.com/google/protobuf</url>
- <connection>scm:git:https://github.com/google/protobuf.git</connection>
+ <url>https://github.com/protocolbuffers/protobuf</url>
+ <connection>scm:git:https://github.com/protocolbuffers/protobuf.git</connection>
</scm>
<distributionManagement>
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 fb7f4343..17b41cbb 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
@@ -61,6 +61,9 @@ public final class Durations {
public static final Duration MAX_VALUE =
Duration.newBuilder().setSeconds(DURATION_SECONDS_MAX).setNanos(999999999).build();
+ /** A constant holding the duration of zero. */
+ public static final Duration ZERO = Duration.newBuilder().setSeconds(0L).setNanos(0).build();
+
private Durations() {}
private static final Comparator<Duration> COMPARATOR =
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 4a13fb1d..86f56ad9 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
@@ -240,7 +240,7 @@ final class FieldMaskTree {
"Field \""
+ field.getFullName()
+ "\" is not a "
- + "singluar message field and cannot have sub-fields.");
+ + "singular message field and cannot have sub-fields.");
continue;
}
if (!source.hasField(field) && !destination.hasField(field)) {
@@ -249,12 +249,9 @@ final class FieldMaskTree {
continue;
}
String childPath = path.isEmpty() ? entry.getKey() : path + "." + entry.getKey();
- merge(
- entry.getValue(),
- childPath,
- (Message) source.getField(field),
- destination.getFieldBuilder(field),
- options);
+ Message.Builder childBuilder = ((Message) destination.getField(field)).toBuilder();
+ merge(entry.getValue(), childPath, (Message) source.getField(field), childBuilder, options);
+ destination.setField(field, childBuilder.buildPartial());
continue;
}
if (field.isRepeated()) {
@@ -275,7 +272,12 @@ final class FieldMaskTree {
}
} else {
if (source.hasField(field)) {
- destination.getFieldBuilder(field).mergeFrom((Message) source.getField(field));
+ destination.setField(
+ field,
+ ((Message) destination.getField(field))
+ .toBuilder()
+ .mergeFrom((Message) source.getField(field))
+ .build());
}
}
} else {
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 b2f849c4..aedc5eac 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
@@ -235,7 +235,7 @@ public class FieldMaskUtil {
/**
* Converts a FieldMask to its canonical form. In the canonical form of a
* FieldMask, all field paths are sorted alphabetically and redundant field
- * paths are moved.
+ * paths are removed.
*/
public static FieldMask normalize(FieldMask mask) {
return new FieldMaskTree(mask).toFieldMask();
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 7f69ee68..46deb5d1 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
@@ -50,6 +50,7 @@ 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 com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
import com.google.protobuf.DoubleValue;
@@ -610,7 +611,7 @@ public class JsonFormat {
private final CharSequence blankOrNewLine;
private static class GsonHolder {
- private static final Gson DEFAULT_GSON = new GsonBuilder().disableHtmlEscaping().create();
+ private static final Gson DEFAULT_GSON = new GsonBuilder().create();
}
PrinterImpl(
@@ -1539,7 +1540,11 @@ public class JsonFormat {
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
- throw new InvalidProtocolBufferException("Map value cannot be null.");
+ if (ignoringUnknownFields && valueField.getType() == Type.ENUM) {
+ continue;
+ } else {
+ throw new InvalidProtocolBufferException("Map value cannot be null.");
+ }
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
@@ -1557,8 +1562,12 @@ 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 in field: " + field.getFullName());
+ if (ignoringUnknownFields && field.getType() == Type.ENUM) {
+ continue;
+ } else {
+ throw new InvalidProtocolBufferException(
+ "Repeated field elements cannot be null in field: " + field.getFullName());
+ }
}
builder.addRepeatedField(field, value);
}
@@ -1748,7 +1757,7 @@ public class JsonFormat {
// an exception later.
}
- if (result == null) {
+ if (result == null && !ignoringUnknownFields) {
throw new InvalidProtocolBufferException(
"Invalid enum value: " + value + " for enum type: " + enumDescriptor.getFullName());
}
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 853b6151..a0d317d4 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
@@ -30,9 +30,14 @@
package com.google.protobuf.util;
+import com.google.protobuf.DynamicMessage;
+import com.google.protobuf.Message;
+import com.google.protobuf.UninitializedMessageException;
import protobuf_unittest.UnittestProto.NestedTestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
+import protobuf_unittest.UnittestProto.TestRequired;
+import protobuf_unittest.UnittestProto.TestRequiredMessage;
import junit.framework.TestCase;
public class FieldMaskTreeTest extends TestCase {
@@ -90,8 +95,68 @@ public class FieldMaskTreeTest extends TestCase {
tree.intersectFieldPath("bar", result);
assertEquals("bar.baz,bar.quz,foo", result.toString());
}
-
+
public void testMerge() throws Exception {
+ testMergeImpl(true);
+ testMergeImpl(false);
+ testMergeRequire(false);
+ testMergeRequire(true);
+ }
+
+ private void merge(
+ FieldMaskTree tree,
+ Message source,
+ Message.Builder builder,
+ FieldMaskUtil.MergeOptions options,
+ boolean useDynamicMessage)
+ throws Exception {
+ if (useDynamicMessage) {
+ Message.Builder newBuilder =
+ DynamicMessage.newBuilder(source.getDescriptorForType())
+ .mergeFrom(builder.buildPartial().toByteArray());
+ tree.merge(
+ DynamicMessage.newBuilder(source.getDescriptorForType())
+ .mergeFrom(source.toByteArray())
+ .build(),
+ newBuilder,
+ options);
+ builder.clear();
+ builder.mergeFrom(newBuilder.buildPartial());
+ } else {
+ tree.merge(source, builder, options);
+ }
+ }
+
+ private void testMergeRequire(boolean useDynamicMessage) throws Exception {
+ TestRequired value = TestRequired.newBuilder().setA(4321).setB(8765).setC(233333).build();
+ TestRequiredMessage source = TestRequiredMessage.newBuilder().setRequiredMessage(value).build();
+
+ FieldMaskUtil.MergeOptions options = new FieldMaskUtil.MergeOptions();
+ TestRequiredMessage.Builder builder = TestRequiredMessage.newBuilder();
+ merge(
+ new FieldMaskTree().addFieldPath("required_message.a"),
+ source,
+ builder,
+ options,
+ useDynamicMessage);
+ assertTrue(builder.hasRequiredMessage());
+ assertTrue(builder.getRequiredMessage().hasA());
+ assertFalse(builder.getRequiredMessage().hasB());
+ assertFalse(builder.getRequiredMessage().hasC());
+ merge(
+ new FieldMaskTree().addFieldPath("required_message.b").addFieldPath("required_message.c"),
+ source,
+ builder,
+ options,
+ useDynamicMessage);
+ try {
+ assertEquals(builder.build(), source);
+ } catch (UninitializedMessageException e) {
+ throw new AssertionError("required field isn't set", e);
+ }
+ }
+
+ private void testMergeImpl(boolean useDynamicMessage) throws Exception {
TestAllTypes value =
TestAllTypes.newBuilder()
.setOptionalInt32(1234)
@@ -119,45 +184,51 @@ public class FieldMaskTreeTest extends TestCase {
// Test merging each individual field.
NestedTestAllTypes.Builder builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree().addFieldPath("payload.optional_int32").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.optional_int32"),
+ source, builder, options, useDynamicMessage);
NestedTestAllTypes.Builder expected = NestedTestAllTypes.newBuilder();
expected.getPayloadBuilder().setOptionalInt32(1234);
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("payload.optional_nested_message")
- .merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.optional_nested_message"),
+ source, builder, options, useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected.getPayloadBuilder().setOptionalNestedMessage(NestedMessage.newBuilder().setBb(5678));
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree().addFieldPath("payload.repeated_int32").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.repeated_int32"),
+ source, builder, options, useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected.getPayloadBuilder().addRepeatedInt32(4321);
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("payload.repeated_nested_message")
- .merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.repeated_nested_message"),
+ source, builder, options, useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected.getPayloadBuilder().addRepeatedNestedMessage(NestedMessage.newBuilder().setBb(8765));
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("child.payload.optional_int32")
- .merge(source, builder, options);
+ merge(
+ new FieldMaskTree().addFieldPath("child.payload.optional_int32"),
+ source,
+ builder,
+ options,
+ useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected.getChildBuilder().getPayloadBuilder().setOptionalInt32(1234);
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("child.payload.optional_nested_message")
- .merge(source, builder, options);
+ merge(
+ new FieldMaskTree().addFieldPath("child.payload.optional_nested_message"),
+ source,
+ builder,
+ options,
+ useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected
.getChildBuilder()
@@ -166,17 +237,15 @@ public class FieldMaskTreeTest extends TestCase {
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("child.payload.repeated_int32")
- .merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("child.payload.repeated_int32"),
+ source, builder, options, useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected.getChildBuilder().getPayloadBuilder().addRepeatedInt32(4321);
assertEquals(expected.build(), builder.build());
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("child.payload.repeated_nested_message")
- .merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("child.payload.repeated_nested_message"),
+ source, builder, options, useDynamicMessage);
expected = NestedTestAllTypes.newBuilder();
expected
.getChildBuilder()
@@ -186,23 +255,23 @@ public class FieldMaskTreeTest extends TestCase {
// Test merging all fields.
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree()
- .addFieldPath("child")
- .addFieldPath("payload")
- .merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("child").addFieldPath("payload"),
+ source, builder, options, useDynamicMessage);
assertEquals(source, builder.build());
// Test repeated options.
builder = NestedTestAllTypes.newBuilder();
builder.getPayloadBuilder().addRepeatedInt32(1000);
- new FieldMaskTree().addFieldPath("payload.repeated_int32").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.repeated_int32"),
+ source, builder, options, useDynamicMessage);
// Default behavior is to append repeated fields.
assertEquals(2, builder.getPayload().getRepeatedInt32Count());
assertEquals(1000, builder.getPayload().getRepeatedInt32(0));
assertEquals(4321, builder.getPayload().getRepeatedInt32(1));
// Change to replace repeated fields.
options.setReplaceRepeatedFields(true);
- new FieldMaskTree().addFieldPath("payload.repeated_int32").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.repeated_int32"),
+ source, builder, options, useDynamicMessage);
assertEquals(1, builder.getPayload().getRepeatedInt32Count());
assertEquals(4321, builder.getPayload().getRepeatedInt32(0));
@@ -210,7 +279,8 @@ public class FieldMaskTreeTest extends TestCase {
builder = NestedTestAllTypes.newBuilder();
builder.getPayloadBuilder().setOptionalInt32(1000);
builder.getPayloadBuilder().setOptionalUint32(2000);
- new FieldMaskTree().addFieldPath("payload").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload"),
+ source, builder, options, useDynamicMessage);
// Default behavior is to merge message fields.
assertEquals(1234, builder.getPayload().getOptionalInt32());
assertEquals(2000, builder.getPayload().getOptionalUint32());
@@ -218,14 +288,14 @@ public class FieldMaskTreeTest extends TestCase {
// Test merging unset message fields.
NestedTestAllTypes clearedSource = source.toBuilder().clearPayload().build();
builder = NestedTestAllTypes.newBuilder();
- new FieldMaskTree().addFieldPath("payload").merge(clearedSource, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload"),
+ clearedSource, builder, options, useDynamicMessage);
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);
+ merge(new FieldMaskTree().addFieldPath("payload.optional_int32"),
+ clearedSource, builder, options, useDynamicMessage);
assertEquals(false, builder.hasPayload());
// Change to replace message fields.
@@ -233,7 +303,8 @@ public class FieldMaskTreeTest extends TestCase {
builder = NestedTestAllTypes.newBuilder();
builder.getPayloadBuilder().setOptionalInt32(1000);
builder.getPayloadBuilder().setOptionalUint32(2000);
- new FieldMaskTree().addFieldPath("payload").merge(source, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload"),
+ source, builder, options, useDynamicMessage);
assertEquals(1234, builder.getPayload().getOptionalInt32());
assertEquals(0, builder.getPayload().getOptionalUint32());
@@ -241,7 +312,8 @@ public class FieldMaskTreeTest extends TestCase {
builder = NestedTestAllTypes.newBuilder();
builder.getPayloadBuilder().setOptionalInt32(1000);
builder.getPayloadBuilder().setOptionalUint32(2000);
- new FieldMaskTree().addFieldPath("payload").merge(clearedSource, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload"),
+ clearedSource, builder, options, useDynamicMessage);
assertEquals(false, builder.hasPayload());
// Test merging unset primitive fields.
@@ -249,18 +321,16 @@ public class FieldMaskTreeTest extends TestCase {
builder.getPayloadBuilder().clearOptionalInt32();
NestedTestAllTypes sourceWithPayloadInt32Unset = builder.build();
builder = source.toBuilder();
- new FieldMaskTree()
- .addFieldPath("payload.optional_int32")
- .merge(sourceWithPayloadInt32Unset, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.optional_int32"),
+ sourceWithPayloadInt32Unset, builder, options, useDynamicMessage);
assertEquals(true, builder.getPayload().hasOptionalInt32());
assertEquals(0, builder.getPayload().getOptionalInt32());
// Change to clear unset primitive fields.
options.setReplacePrimitiveFields(true);
builder = source.toBuilder();
- new FieldMaskTree()
- .addFieldPath("payload.optional_int32")
- .merge(sourceWithPayloadInt32Unset, builder, options);
+ merge(new FieldMaskTree().addFieldPath("payload.optional_int32"),
+ sourceWithPayloadInt32Unset, builder, options, useDynamicMessage);
assertEquals(true, builder.hasPayload());
assertEquals(false, builder.getPayload().hasOptionalInt32());
}
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 6ef08508..64413bc1 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
@@ -70,7 +70,6 @@ import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collections;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
@@ -162,6 +161,11 @@ public class JsonFormatTest extends TestCase {
JsonFormat.parser().merge(json, builder);
}
+ private void mergeFromJsonIgnoringUnknownFields(String json, Message.Builder builder)
+ throws IOException {
+ JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
+ }
+
public void testAllFields() throws Exception {
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
setAllFields(builder);
@@ -669,11 +673,20 @@ public class JsonFormatTest extends TestCase {
+ "}",
builder);
fail();
+
} catch (InvalidProtocolBufferException e) {
// Exception expected.
}
}
+ public void testMapEnumNullValueIsIgnored() throws Exception {
+ TestMap.Builder builder = TestMap.newBuilder();
+ mergeFromJsonIgnoringUnknownFields(
+ "{\n" + " \"int32ToEnumMap\": {\"1\": null}\n" + "}", builder);
+ TestMap map = builder.build();
+ assertEquals(0, map.getInt32ToEnumMapMap().size());
+ }
+
public void testParserAcceptNonQuotedObjectKey() throws Exception {
TestMap.Builder builder = TestMap.newBuilder();
mergeFromJson(
@@ -1174,6 +1187,35 @@ public class JsonFormatTest extends TestCase {
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
}
+ public void testParserIgnoringUnknownEnums() throws Exception {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ String json = "{\n" + " \"optionalNestedEnum\": \"XXX\"\n" + "}";
+ JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
+ assertEquals(0, builder.getOptionalNestedEnumValue());
+ }
+
+ public void testUnknownEnumMap() throws Exception {
+ TestMap.Builder builder = TestMap.newBuilder();
+ JsonFormat.parser()
+ .ignoringUnknownFields()
+ .merge("{\n" + " \"int32ToEnumMap\": {1: XXX, 2: FOO}" + "}", builder);
+
+ assertEquals(NestedEnum.FOO, builder.getInt32ToEnumMapMap().get(2));
+ assertEquals(1, builder.getInt32ToEnumMapMap().size());
+ }
+
+ public void testRepeatedUnknownEnum() throws Exception {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ JsonFormat.parser()
+ .ignoringUnknownFields()
+ .merge("{\n" + " \"repeatedNestedEnum\": [XXX, FOO, BAR, BAZ]" + "}", builder);
+
+ assertEquals(NestedEnum.FOO, builder.getRepeatedNestedEnum(0));
+ assertEquals(NestedEnum.BAR, builder.getRepeatedNestedEnum(1));
+ assertEquals(NestedEnum.BAZ, builder.getRepeatedNestedEnum(2));
+ assertEquals(3, builder.getRepeatedNestedEnumList().size());
+ }
+
public void testParserIntegerEnumValue() throws Exception {
TestAllTypes.Builder actualBuilder = TestAllTypes.newBuilder();
mergeFromJson("{\n" + " \"optionalNestedEnum\": 2\n" + "}", actualBuilder);
@@ -1188,10 +1230,14 @@ public class JsonFormatTest extends TestCase {
assertRoundTripEquals(message);
}
- public void testDefaultGsonDoesNotHtmlEscape() throws Exception {
- TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("=").build();
- assertEquals(
- "{\n" + " \"optionalString\": \"=\"" + "\n}", JsonFormat.printer().print(message));
+ // Regression test for b/73832901. Make sure html tags are escaped.
+ public void testHtmlEscape() throws Exception {
+ TestAllTypes message = TestAllTypes.newBuilder().setOptionalString("</script>").build();
+ assertEquals("{\n \"optionalString\": \"\\u003c/script\\u003e\"\n}", toJsonString(message));
+
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ JsonFormat.parser().merge(toJsonString(message), builder);
+ assertEquals(message.getOptionalString(), builder.getOptionalString());
}
public void testIncludingDefaultValueFields() throws Exception {
diff --git a/js/README.md b/js/README.md
index ef0d4b19..2c142222 100644
--- a/js/README.md
+++ b/js/README.md
@@ -1,7 +1,7 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf)
+[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fjavascript%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-javascript.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fjavascript%2Fcontinuous)
Copyright 2008 Google Inc.
@@ -25,7 +25,7 @@ To use Protocol Buffers with JavaScript, you need two main components:
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
- [on GitHub](https://github.com/google/protobuf/releases)
+ [on GitHub](https://github.com/protocolbuffers/protobuf/releases)
(look for the `protoc-*.zip` files under **Downloads**).
@@ -33,11 +33,11 @@ Setup
=====
First, obtain the Protocol Compiler. The easiest way is to download
-a pre-built binary from [https://github.com/google/protobuf/releases](https://github.com/google/protobuf/releases).
+a pre-built binary from [https://github.com/protocolbuffers/protobuf/releases](https://github.com/protocolbuffers/protobuf/releases).
If you want, you can compile `protoc` from source instead. To do this
follow the instructions in [the top-level
-README](https://github.com/google/protobuf/blob/master/src/README.md).
+README](https://github.com/protocolbuffers/protobuf/blob/master/src/README.md).
Once you have `protoc` compiled, you can run the tests by typing:
@@ -135,7 +135,7 @@ The syntax of the `--js_out` flag is:
Where `OPTIONS` are separated by commas. Options are either `opt=val` or
just `opt` (for options that don't take a value). The available options
are specified and documented in the `GeneratorOptions` struct in
-[src/google/protobuf/compiler/js/js_generator.h](https://github.com/google/protobuf/blob/master/src/google/protobuf/compiler/js/js_generator.h#L53).
+[src/google/protobuf/compiler/js/js_generator.h](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/compiler/js/js_generator.h#L53).
Some examples:
@@ -144,6 +144,7 @@ Some examples:
The `import_style` option is left to the default, which is `closure`.
- `--js_out=import_style=commonjs,binary:protos`: this contains the options
`import_style=commonjs` and `binary` and outputs to the directory `protos`.
+ `import_style=commonjs_strict` doesn't expose the output on the global scope.
API
===
diff --git a/js/binary/constants.js b/js/binary/constants.js
index 21c5889c..5c53a360 100644
--- a/js/binary/constants.js
+++ b/js/binary/constants.js
@@ -174,7 +174,7 @@ jspb.PrunerFunction;
/**
* A comparer function returns true if two protos are equal.
- * @typedef {!function(?jspb.ConstBinaryMessage,
+ * @typedef {function(?jspb.ConstBinaryMessage,
* ?jspb.ConstBinaryMessage):boolean}
*/
jspb.ComparerFunction;
diff --git a/js/binary/reader.js b/js/binary/reader.js
index 2dc3eb70..731587c7 100644
--- a/js/binary/reader.js
+++ b/js/binary/reader.js
@@ -290,7 +290,9 @@ jspb.BinaryReader.prototype.nextField = function() {
nextWireType != jspb.BinaryConstants.WireType.DELIMITED &&
nextWireType != jspb.BinaryConstants.WireType.START_GROUP &&
nextWireType != jspb.BinaryConstants.WireType.END_GROUP) {
- goog.asserts.fail('Invalid wire type');
+ goog.asserts.fail(
+ 'Invalid wire type: %s (at position %s)', nextWireType,
+ this.fieldCursor_);
this.error_ = true;
return false;
}
@@ -388,8 +390,7 @@ jspb.BinaryReader.prototype.skipFixed64Field = function() {
* Skips over the next group field in the binary stream.
*/
jspb.BinaryReader.prototype.skipGroup = function() {
- // Keep a stack of start-group tags that must be matched by end-group tags.
- var nestedGroups = [this.nextField_];
+ var previousField = this.nextField_;
do {
if (!this.nextField()) {
goog.asserts.fail('Unmatched start-group tag: stream EOF');
@@ -397,19 +398,17 @@ jspb.BinaryReader.prototype.skipGroup = function() {
return;
}
if (this.nextWireType_ ==
- jspb.BinaryConstants.WireType.START_GROUP) {
- // Nested group start.
- nestedGroups.push(this.nextField_);
- } else if (this.nextWireType_ ==
jspb.BinaryConstants.WireType.END_GROUP) {
// Group end: check that it matches top-of-stack.
- if (this.nextField_ != nestedGroups.pop()) {
+ if (this.nextField_ != previousField) {
goog.asserts.fail('Unmatched end-group tag');
this.error_ = true;
return;
}
+ return;
}
- } while (nestedGroups.length > 0);
+ this.skipField();
+ } while (true);
};
diff --git a/js/binary/reader_test.js b/js/binary/reader_test.js
index 95711385..eb2af0a9 100644
--- a/js/binary/reader_test.js
+++ b/js/binary/reader_test.js
@@ -679,9 +679,24 @@ describe('binaryReaderTest', function() {
writer.writeInt32(5, sentinel);
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
writer.writeGroup(5, dummyMessage, function() {
+ // Previously the skipGroup implementation was wrong, which only consume
+ // the decoder by nextField. This case is for making the previous
+ // implementation failed in skipGroup by an early end group tag.
+ // The reason is 44 = 5 * 8 + 4, this will be translated in to a field
+ // with number 5 and with type 4 (end group)
+ writer.writeInt64(44, 44);
+ // This will make previous implementation failed by invalid tag (7).
+ writer.writeInt64(42, 47);
writer.writeInt64(42, 42);
+ // This is for making the previous implementation failed by an invalid
+ // varint. The bytes have at least 9 consecutive minus byte, which will
+ // fail in this.nextField for previous implementation.
+ writer.writeBytes(43, [255, 255, 255, 255, 255, 255, 255, 255, 255, 255]);
writer.writeGroup(6, dummyMessage, function() {
writer.writeInt64(84, 42);
+ writer.writeInt64(84, 44);
+ writer.writeBytes(
+ 43, [255, 255, 255, 255, 255, 255, 255, 255, 255, 255]);
});
});
diff --git a/js/binary/utils.js b/js/binary/utils.js
index 55a9ccd4..173c416b 100644
--- a/js/binary/utils.js
+++ b/js/binary/utils.js
@@ -971,8 +971,9 @@ jspb.utils.byteSourceToUint8Array = function(data) {
return /** @type {!Uint8Array} */(new Uint8Array(data));
}
- if (data.constructor === Buffer) {
- return /** @type {!Uint8Array} */(new Uint8Array(data));
+ if (typeof Buffer != 'undefined' && data.constructor === Buffer) {
+ return /** @type {!Uint8Array} */ (
+ new Uint8Array(/** @type {?} */ (data)));
}
if (data.constructor === Array) {
diff --git a/js/commonjs/strict_test.js b/js/commonjs/strict_test.js
new file mode 100644
index 00000000..46458c10
--- /dev/null
+++ b/js/commonjs/strict_test.js
@@ -0,0 +1,67 @@
+// 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);
+
+var test9_pb = require('./test9_pb');
+var test10_pb = require('./test10_pb');
+
+describe('Strict test suite', function() {
+ it('testImportedMessage', function() {
+ var simple1 = new test9_pb.jspb.exttest.strict.nine.Simple9()
+ var simple2 = new test9_pb.jspb.exttest.strict.nine.Simple9()
+ assertObjectEquals(simple1.toObject(), simple2.toObject());
+ });
+
+ it('testGlobalScopePollution', function() {
+ assertObjectEquals(global.jspb.exttest, undefined);
+ });
+
+ describe('with imports', function() {
+ it('testImportedMessage', function() {
+ var simple1 = new test10_pb.jspb.exttest.strict.ten.Simple10()
+ var simple2 = new test10_pb.jspb.exttest.strict.ten.Simple10()
+ assertObjectEquals(simple1.toObject(), simple2.toObject());
+ });
+
+ it('testGlobalScopePollution', function() {
+ assertObjectEquals(global.jspb.exttest, undefined);
+ });
+ });
+});
diff --git a/js/gulpfile.js b/js/gulpfile.js
index fc9559f9..709c5cf9 100644
--- a/js/gulpfile.js
+++ b/js/gulpfile.js
@@ -41,6 +41,12 @@ var group2Protos = [
'commonjs/test7/test7.proto',
];
+var group3Protos = [
+ 'test9.proto',
+ 'test10.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) {
@@ -112,6 +118,15 @@ gulp.task('genproto_wellknowntypes', function (cb) {
cb(err);
});
});
+gulp.task('genproto_group3_commonjs_strict', function (cb) {
+ exec('mkdir -p commonjs_out && ' + protoc + ' --js_out=import_style=commonjs_strict,binary:commonjs_out -I ../src -I commonjs -I . ' + group3Protos.join(' '),
+ function (err, stdout, stderr) {
+ console.log(stdout);
+ console.log(stderr);
+ cb(err);
+ });
+});
+
function getClosureBuilderCommand(exportsFile, outputFile) {
return './node_modules/google-closure-library/closure/bin/build/closurebuilder.py ' +
@@ -159,7 +174,7 @@ gulp.task('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) {
+gulp.task('make_commonjs_out', ['dist', 'genproto_well_known_types_commonjs', 'genproto_group1_commonjs', 'genproto_group2_commonjs', 'genproto_commonjs_wellknowntypes', 'commonjs_asserts', 'commonjs_testdeps', 'genproto_group3_commonjs_strict'], 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 && ";
@@ -174,6 +189,7 @@ gulp.task('make_commonjs_out', ['dist', 'genproto_well_known_types_commonjs', 'g
exec(cmd +
'cp commonjs/jasmine.json commonjs_out/jasmine.json && ' +
'cp google-protobuf.js commonjs_out/test_node_modules && ' +
+ 'cp commonjs/strict_test.js commonjs_out/strict_test.js &&' +
'cp commonjs/import_test.js commonjs_out/import_test.js',
function (err, stdout, stderr) {
console.log(stdout);
diff --git a/js/map.js b/js/map.js
index 2fb14837..671bd516 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>>}
*/
@@ -165,9 +165,9 @@ jspb.Map.prototype.toObject = function(includeInstance, valueToObject) {
*
* @template K, V
* @param {!Array<!Array<!Object>>} entries
- * @param {!function(new:V,?=)} valueCtor
+ * @param {function(new:V,?=)} valueCtor
* The constructor for type V.
- * @param {!function(!Object):V} valueFromObject
+ * @param {function(!Object):V} valueFromObject
* The fromObject function for type V.
* @return {!jspb.Map<K, V>}
*/
@@ -410,9 +410,9 @@ jspb.Map.prototype.has = function(key) {
* number.
* @param {number} fieldNumber
* @param {!jspb.BinaryWriter} writer
- * @param {!function(this:jspb.BinaryWriter,number,K)} keyWriterFn
+ * @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,?=)|
+ * @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.
@@ -448,10 +448,10 @@ jspb.Map.prototype.serializeBinary = function(
* @template K, V
* @param {!jspb.Map} map
* @param {!jspb.BinaryReader} reader
- * @param {!function(this:jspb.BinaryReader):K} keyReaderFn
+ * @param {function(this:jspb.BinaryReader):K} keyReaderFn
* The method on BinaryReader that reads type K from the stream.
*
- * @param {!function(this:jspb.BinaryReader):V|
+ * @param {function(this:jspb.BinaryReader):V|
* function(this:jspb.BinaryReader,V,
* function(V,!jspb.BinaryReader))} valueReaderFn
* The method on BinaryReader that reads type V from the stream. May be
diff --git a/js/message.js b/js/message.js
index 86d18295..6a37745b 100644
--- a/js/message.js
+++ b/js/message.js
@@ -439,9 +439,19 @@ jspb.Message.isArray_ = function(o) {
* @private
*/
jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
- if (msg.array.length) {
- var foundIndex = msg.array.length - 1;
- var obj = msg.array[foundIndex];
+ // There are 3 variants that need to be dealt with which are the
+ // combination of whether there exists an extension object (EO) and
+ // whether there is a suggested pivot (SP).
+ //
+ // EO, ? : pivot is the index of the EO
+ // no-EO, no-SP: pivot is MAX_INT
+ // no-EO, SP : pivot is the max(lastindex + 1, SP)
+
+ var msgLength = msg.array.length;
+ var lastIndex = -1;
+ if (msgLength) {
+ lastIndex = msgLength - 1;
+ var obj = msg.array[lastIndex];
// Normal fields are never objects, so we can be sure that if we find an
// object here, then it's the extension object. However, we must ensure that
// the object is not an array, since arrays are valid field values.
@@ -449,14 +459,17 @@ jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
// in Safari on iOS 8. See the description of CL/86511464 for details.
if (obj && typeof obj == 'object' && !jspb.Message.isArray_(obj) &&
!(jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array)) {
- msg.pivot_ = jspb.Message.getFieldNumber_(msg, foundIndex);
+ msg.pivot_ = jspb.Message.getFieldNumber_(msg, lastIndex);
msg.extensionObject_ = obj;
return;
}
}
if (suggestedPivot > -1) {
- msg.pivot_ = suggestedPivot;
+ // If a extension object is not present, set the pivot value as being
+ // after the last value in the array to avoid overwriting values, etc.
+ msg.pivot_ = Math.max(
+ suggestedPivot, jspb.Message.getFieldNumber_(msg, lastIndex + 1));
// 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
@@ -923,17 +936,6 @@ jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
/**
- * Sets the value of a non-extension integer, handled as string, 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.setProto3StringIntField = 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.
@@ -993,12 +995,22 @@ jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
};
+/**
+ * Sets the value of a non-extension int field of a proto3 that has jstype set
+ * to String.
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {string} value New value
+ * @protected
+ */
+jspb.Message.setProto3StringIntField = 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
@@ -1007,7 +1019,7 @@ jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
*/
jspb.Message.setFieldIgnoringDefault_ = function(
msg, fieldNumber, value, defaultValue) {
- if (value != defaultValue) {
+ if (value !== defaultValue) {
jspb.Message.setField(msg, fieldNumber, value);
} else {
msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
@@ -1127,7 +1139,7 @@ jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
* @param {!jspb.Message} msg A jspb proto.
* @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
* @param {number} fieldNumber The field number.
- * @return {Array<!jspb.Message>} The repeated field as an array of protos.
+ * @return {!Array<!jspb.Message>} The repeated field as an array of protos.
* @protected
*/
jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
diff --git a/js/message_test.js b/js/message_test.js
index 1be41093..2bfec62b 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -73,6 +73,7 @@ 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.TestCloneExtension');
goog.require('proto.jspb.test.TestEndsWithBytes');
goog.require('proto.jspb.test.TestGroup');
goog.require('proto.jspb.test.TestGroup1');
diff --git a/js/package.json b/js/package.json
index c24d9510..8aaf0d43 100644
--- a/js/package.json
+++ b/js/package.json
@@ -19,8 +19,8 @@
},
"repository": {
"type": "git",
- "url": "https://github.com/google/protobuf/tree/master/js"
+ "url": "https://github.com/protocolbuffers/protobuf/tree/master/js"
},
"author": "Google Protocol Buffers Team",
- "license" : "BSD-3-Clause"
+ "license": "BSD-3-Clause"
}
diff --git a/js/test.proto b/js/test.proto
index 7c881c0d..3b538b52 100644
--- a/js/test.proto
+++ b/js/test.proto
@@ -165,6 +165,13 @@ message TestClone {
extensions 10 to max;
}
+message TestCloneExtension {
+ extend TestClone {
+ optional TestCloneExtension low_ext = 11;
+ }
+ optional int32 f = 1;
+}
+
message CloneExtension {
extend TestClone {
optional CloneExtension ext_field = 100;
diff --git a/js/test10.proto b/js/test10.proto
new file mode 100644
index 00000000..9fa5256c
--- /dev/null
+++ b/js/test10.proto
@@ -0,0 +1,39 @@
+// 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 jspb.exttest.strict.ten;
+
+import "test9.proto";
+
+message Simple10 {
+ jspb.exttest.strict.nine.Simple9 a = 1;
+}
diff --git a/js/test9.proto b/js/test9.proto
new file mode 100644
index 00000000..9f680852
--- /dev/null
+++ b/js/test9.proto
@@ -0,0 +1,39 @@
+// 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 jspb.exttest.strict.nine;
+
+message Simple9 {
+ required string a_string = 1;
+ repeated string a_repeated_string = 2;
+ optional bool a_boolean = 3;
+}
diff --git a/kokoro/linux/bazel/build.sh b/kokoro/linux/bazel/build.sh
index e0c1ee42..1769301d 100755
--- a/kokoro/linux/bazel/build.sh
+++ b/kokoro/linux/bazel/build.sh
@@ -1,6 +1,7 @@
#!/bin/bash
#
# Build file to set up and run tests
+set -ex
# Change to repo root
cd $(dirname $0)/../../..
diff --git a/kokoro/linux/benchmark/build.sh b/kokoro/linux/benchmark/build.sh
index 750c3e5c..527485c8 100755
--- a/kokoro/linux/benchmark/build.sh
+++ b/kokoro/linux/benchmark/build.sh
@@ -27,8 +27,8 @@ cd $oldpwd
./configure CXXFLAGS="-fPIC -O2"
make -j8
cd python
-python setup.py -q build --cpp_implementation
-pip install .
+python setup.py build --cpp_implementation
+pip install . --user
# build and run Python benchmark
@@ -41,10 +41,10 @@ echo "benchmarking pure python..."
./python-pure-python-benchmark --json --behavior_prefix="pure-python-benchmark" $datasets >> tmp/python_result.json
echo "," >> "tmp/python_result.json"
echo "benchmarking python cpp reflection..."
-env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" ./python-cpp-reflection-benchmark --json --behavior_prefix="cpp-reflection-benchmark" $datasets >> tmp/python_result.json
+env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" LD_LIBRARY_PATH="$oldpwd/src/.libs" ./python-cpp-reflection-benchmark --json --behavior_prefix="cpp-reflection-benchmark" $datasets >> tmp/python_result.json
echo "," >> "tmp/python_result.json"
echo "benchmarking python cpp generated code..."
-env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" ./python-cpp-generated-code-benchmark --json --behavior_prefix="cpp-generated-code-benchmark" $datasets >> tmp/python_result.json
+env LD_PRELOAD="$oldpwd/gperftools/.libs/libtcmalloc.so" LD_LIBRARY_PATH="$oldpwd/src/.libs" ./python-cpp-generated-code-benchmark --json --behavior_prefix="cpp-generated-code-benchmark" $datasets >> tmp/python_result.json
echo "]" >> "tmp/python_result.json"
cd $oldpwd
@@ -52,6 +52,11 @@ cd $oldpwd
./configure
make clean && make -j8
+# build Java protobuf
+cd java
+mvn package
+cd ..
+
# build CPP benchmark
cd benchmarks
mv tmp/python_result.json . && make clean && make -j8 cpp-benchmark && mv python_result.json tmp
@@ -63,8 +68,8 @@ cd $oldpwd
export PATH="`pwd`/src:$PATH"
export GOPATH="$HOME/gocode"
mkdir -p "$GOPATH/src/github.com/google"
-rm -f "$GOPATH/src/github.com/google/protobuf"
-ln -s "`pwd`" "$GOPATH/src/github.com/google/protobuf"
+rm -f "$GOPATH/src/github.com/protocolbuffers/protobuf"
+ln -s "`pwd`" "$GOPATH/src/github.com/protocolbuffers/protobuf"
export PATH="$GOPATH/bin:$PATH"
go get github.com/golang/protobuf/protoc-gen-go
@@ -81,7 +86,7 @@ echo "benchmarking java..."
# upload result to bq
make python_add_init
-python util/run_and_upload.py -cpp="../tmp/cpp_result.json" -java="../tmp/java_result.json" \
+env LD_LIBRARY_PATH="$oldpwd/src/.libs" python -m util.result_uploader -cpp="../tmp/cpp_result.json" -java="../tmp/java_result.json" \
-python="../tmp/python_result.json" -go="../tmp/go_result.txt"
cd $oldpwd
diff --git a/kokoro/linux/build_and_run_docker.sh b/kokoro/linux/build_and_run_docker.sh
index f9c60710..b81a3684 100755
--- a/kokoro/linux/build_and_run_docker.sh
+++ b/kokoro/linux/build_and_run_docker.sh
@@ -8,7 +8,6 @@
# OUTPUT_DIR - Directory that will be copied from inside docker after finishing.
# $@ - Extra args to pass to docker run
-
set -ex
cd $(dirname $0)/../..
@@ -39,7 +38,6 @@ docker run \
-e KOKORO_BUILD_ID=$KOKORO_BUILD_ID \
-e EXTERNAL_GIT_ROOT="/var/local/kokoro/protobuf" \
-e TEST_SET="$TEST_SET" \
- -e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
-v "$git_root:/var/local/kokoro/protobuf:ro" \
-v $CCACHE_DIR:$CCACHE_DIR \
-w /var/local/git/protobuf \
@@ -47,16 +45,9 @@ docker run \
$DOCKER_IMAGE_NAME \
bash -l "/var/local/kokoro/protobuf/$DOCKER_RUN_SCRIPT" || FAILED="true"
-# Copy output artifacts
-if [ "$OUTPUT_DIR" != "" ]
-then
- docker cp "$CONTAINER_NAME:/var/local/git/protobuf/$OUTPUT_DIR" "${git_root}/kokoro" || FAILED="true"
-fi
-
# remove the container, possibly killing it first
docker rm -f $CONTAINER_NAME || true
-if [ "$FAILED" != "" ]
-then
+[ -z "$FAILED" ] || {
exit 1
-fi
+}
diff --git a/kokoro/linux/pull_request_in_docker.sh b/kokoro/linux/pull_request_in_docker.sh
index e28ef958..a048c470 100755
--- a/kokoro/linux/pull_request_in_docker.sh
+++ b/kokoro/linux/pull_request_in_docker.sh
@@ -22,52 +22,4 @@ cd protobuf
# Initialize any submodules:
git submodule update --init --recursive
-# Set up the directory where our test output is going to go.
-OUTPUT_DIR=`mktemp -d`
-LOG_OUTPUT_DIR=$OUTPUT_DIR/logs
-mkdir -p $LOG_OUTPUT_DIR/1/cpp
-
-################################################################################
-# cpp build needs to run first, non-parallelized, so that protoc is available
-# for other builds.
-
-# Output filenames to follow the overall scheme used by parallel, ie:
-# $DIR/logs/1/cpp/stdout
-# $DIR/logs/1/cpp/stderr
-# $DIR/logs/1/csharp/stdout
-# $DIR/logs/1/csharp/stderr
-# $DIR/logs/1/java_jdk7/stdout
-# $DIR/logs/1/java_jdk7/stderr
-CPP_STDOUT=$LOG_OUTPUT_DIR/1/cpp/stdout
-CPP_STDERR=$LOG_OUTPUT_DIR/1/cpp/stderr
-
-# Time the C++ build, so we can put this info in the test output.
-# It's important that we get /usr/bin/time (which supports -f and -o) and not
-# the bash builtin "time" which doesn't.
-TIME_CMD="/usr/bin/time -f %e -o $LOG_OUTPUT_DIR/1/cpp/build_time"
-
-$TIME_CMD $TEST_SCRIPT cpp > >(tee $CPP_STDOUT) 2> >(tee $CPP_STDERR >&2)
-
-# Other tests are run in parallel. TEST_SET is defined in
-# buildcmds/pull_request{_32}.sh
-
-parallel --results $LOG_OUTPUT_DIR --joblog $OUTPUT_DIR/joblog $TEST_SCRIPT ::: \
- $TEST_SET \
- || FAILED="true" # Process test results even if tests fail.
-
-cat $OUTPUT_DIR/joblog
-
-# The directory that is copied from Docker back into the Kokoro workspace.
-COPY_FROM_DOCKER=/var/local/git/protobuf/testoutput
-mkdir -p $COPY_FROM_DOCKER
-TESTOUTPUT_XML_FILE=$COPY_FROM_DOCKER/sponge_log.xml
-
-# Process all the output files from "parallel" and package them into a single
-# .xml file with detailed, broken-down test output.
-python $MY_DIR/make_test_output.py $OUTPUT_DIR > $TESTOUTPUT_XML_FILE
-
-ls -l $TESTOUTPUT_XML_FILE
-
-if [ "$FAILED" == "true" ]; then
- exit 1
-fi
+$TEST_SCRIPT $TEST_SET
diff --git a/kokoro/macos/jruby/build.sh b/kokoro/macos/jruby/build.sh
deleted file mode 100755
index c82eaebf..00000000
--- a/kokoro/macos/jruby/build.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/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
deleted file mode 100644
index f1310fd3..00000000
--- a/kokoro/macos/jruby/continuous.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-# 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
deleted file mode 100644
index f1310fd3..00000000
--- a/kokoro/macos/jruby/presubmit.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-# 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/release/collect_all_artifacts.cfg b/kokoro/release/collect_all_artifacts.cfg
new file mode 100644
index 00000000..3da1a7c4
--- /dev/null
+++ b/kokoro/release/collect_all_artifacts.cfg
@@ -0,0 +1,7 @@
+build_file: "protobuf/kokoro/release/collect_all_artifacts.sh"
+
+action {
+ define_artifacts {
+ regex: "github/protobuf/artifacts/**"
+ }
+}
diff --git a/kokoro/release/collect_all_artifacts.sh b/kokoro/release/collect_all_artifacts.sh
new file mode 100755
index 00000000..0023937d
--- /dev/null
+++ b/kokoro/release/collect_all_artifacts.sh
@@ -0,0 +1,62 @@
+#!/bin/bash
+
+set -ex
+
+# Change to repo root.
+cd $(dirname $0)/../..
+
+# Initialize any submodules.
+git submodule update --init --recursive
+
+# The directory with all resulting artifacts
+mkdir -p artifacts
+
+# Artifacts from all predecessor jobs get copied to this directory by kokoro
+INPUT_ARTIFACTS_DIR="${KOKORO_GFILE_DIR}/github/protobuf"
+
+# TODO(jtattermusch): remove listing the files, but for now it make it easier
+# to iterate on the script.
+ls -R ${INPUT_ARTIFACTS_DIR}
+
+# ====================================
+# Copy to expose all the artifacts from the predecessor jobs to the output
+# TODO(jtattermusch): the directory layout of the artifact builds is pretty messy,
+# so will be the output artifacts of this job.
+cp -r ${INPUT_ARTIFACTS_DIR}/* artifacts
+
+# ====================================
+# Build Google.Protobuf.Tools C# nuget
+# The reason it's being done in this script is that we need access to protoc binaries
+# built on multiple platform (the build is performed by the "build artifact" step)
+# and adding and extra chained build just for building the Google.Protobuf.Tools
+# nuget seems like an overkill.
+cd csharp
+mkdir -p protoc/windows_x86
+mkdir -p protoc/windows_x64
+cp ${INPUT_ARTIFACTS_DIR}/build32/Release/protoc.exe protoc/windows_x86/protoc.exe
+cp ${INPUT_ARTIFACTS_DIR}/build64/Release/protoc.exe protoc/windows_x64/protoc.exe
+
+mkdir -p protoc/linux_x86
+mkdir -p protoc/linux_x64
+# Because of maven unrelated reasonse the linux protoc binaries have a dummy .exe extension.
+# For the Google.Protobuf.Tools nuget, we don't want that expection, so we just remove it.
+cp ${INPUT_ARTIFACTS_DIR}/protoc-artifacts/target/linux/x86_32/protoc.exe protoc/linux_x86/protoc
+cp ${INPUT_ARTIFACTS_DIR}/protoc-artifacts/target/linux/x86_64/protoc.exe protoc/linux_x64/protoc
+
+mkdir -p protoc/macosx_x86
+mkdir -p protoc/macosx_x64
+cp ${INPUT_ARTIFACTS_DIR}/build32/src/protoc protoc/macosx_x86/protoc
+cp ${INPUT_ARTIFACTS_DIR}/build64/src/protoc protoc/macosx_x64/protoc
+
+# Install nuget (will also install mono)
+# TODO(jtattermusch): use "mono:5.14" docker image instead so we don't have to apt-get install
+sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
+sudo apt install apt-transport-https
+echo "deb https://download.mono-project.com/repo/ubuntu stable-trusty main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list
+sudo apt update
+sudo apt-get install -y nuget
+
+nuget pack Google.Protobuf.Tools.nuspec
+
+# Copy the nupkg to the output artifacts
+cp Google.Protobuf.Tools.*.nupkg ../artifacts
diff --git a/kokoro/release/protoc/linux/build.sh b/kokoro/release/protoc/linux/build.sh
index 6c7049d7..f0cde494 100755
--- a/kokoro/release/protoc/linux/build.sh
+++ b/kokoro/release/protoc/linux/build.sh
@@ -11,6 +11,16 @@ git submodule update --init --recursive
# Generate the configure script.
./autogen.sh
+# Cross-build for aarch64 and ppc64le. Note: we do these builds first to avoid
+# file permission issues. The Docker builds will create directories owned by
+# root, which causes problems if we try to add new artifacts to those
+# directories afterward.
+sudo apt install -y g++-aarch64-linux-gnu
+protoc-artifacts/build-protoc.sh linux aarch_64 protoc
+
+sudo apt install -y g++-powerpc64le-linux-gnu
+protoc-artifacts/build-protoc.sh linux ppcle_64 protoc
+
# Use docker image to build linux artifacts.
DOCKER_IMAGE_NAME=protobuf/protoc_$(sha1sum protoc-artifacts/Dockerfile | cut -f1 -d " ")
docker pull $DOCKER_IMAGE_NAME
@@ -28,9 +38,3 @@ docker run -v $(pwd):/var/local/protobuf --rm $DOCKER_IMAGE_NAME \
echo "Failed to build protoc for linux + x86_32."
exit 1
}
-
-# Cross-build for some architectures.
-# TODO(xiaofeng): It currently fails with "machine `aarch64' not recognized"
-# error.
-# sudo apt install -y g++-aarch64-linux-gnu
-# protoc-artifacts/build-protoc.sh linux aarch_64 protoc
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m
index dd05ddb4..57d04dde 100644
--- a/objectivec/GPBCodedInputStream.m
+++ b/objectivec/GPBCodedInputStream.m
@@ -46,9 +46,9 @@ NSString *const GPBCodedInputStreamErrorDomain =
GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain);
// Matching:
-// https://github.com/google/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62
+// https://github.com/protocolbuffers/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
+// https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/io/coded_stream.cc#L86
// int CodedInputStream::default_recursion_limit_ = 100;
static const NSUInteger kDefaultRecursionLimit = 100;
diff --git a/objectivec/GPBDescriptor.h b/objectivec/GPBDescriptor.h
index 651f4de0..292bce13 100644
--- a/objectivec/GPBDescriptor.h
+++ b/objectivec/GPBDescriptor.h
@@ -223,9 +223,12 @@ typedef NS_ENUM(uint8_t, GPBFieldType) {
/**
* Returns the enum value name for the given raw enum.
*
+ * Note that there can be more than one name corresponding to a given value
+ * if the allow_alias option is used.
+ *
* @param number The raw enum value.
*
- * @return The name of the enum value passed, or nil if not valid.
+ * @return The first name that matches the enum value passed, or nil if not valid.
**/
- (nullable NSString *)enumNameForValue:(int32_t)number;
@@ -244,7 +247,7 @@ typedef NS_ENUM(uint8_t, GPBFieldType) {
*
* @param number The raw enum value.
*
- * @return The text format name for the raw enum value, or nil if not valid.
+ * @return The first text format name which matches the enum value, or nil if not valid.
**/
- (nullable NSString *)textFormatNameForValue:(int32_t)number;
@@ -258,6 +261,33 @@ typedef NS_ENUM(uint8_t, GPBFieldType) {
**/
- (BOOL)getValue:(nullable int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName;
+/**
+ * Gets the number of defined enum names.
+ *
+ * @return Count of the number of enum names, including any aliases.
+ */
+@property(nonatomic, readonly) uint32_t enumNameCount;
+
+/**
+ * Gets the enum name corresponding to the given index.
+ *
+ * @param index Index into the available names. The defined range is from 0
+ * to self.enumNameCount - 1.
+ *
+ * @returns The enum name at the given index, or nil if the index is out of range.
+ */
+- (nullable NSString *)getEnumNameForIndex:(uint32_t)index;
+
+/**
+ * Gets the enum text format name corresponding to the given index.
+ *
+ * @param index Index into the available names. The defined range is from 0
+ * to self.enumNameCount - 1.
+ *
+ * @returns The text format name at the given index, or nil if the index is out of range.
+ */
+- (nullable NSString *)getEnumTextFormatNameForIndex:(uint32_t)index;
+
@end
/**
diff --git a/objectivec/GPBDescriptor.m b/objectivec/GPBDescriptor.m
index 4b39c63b..ad46ef4f 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -830,13 +830,9 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
}
- (NSString *)enumNameForValue:(int32_t)number {
- if (nameOffsets_ == NULL) [self calcValueNameOffsets];
-
for (uint32_t i = 0; i < valueCount_; ++i) {
if (values_[i] == number) {
- const char *valueName = valueNames_ + nameOffsets_[i];
- NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
- return fullName;
+ return [self getEnumNameForIndex:i];
}
}
return nil;
@@ -886,8 +882,6 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
}
- (NSString *)textFormatNameForValue:(int32_t)number {
- if (nameOffsets_ == NULL) [self calcValueNameOffsets];
-
// Find the EnumValue descriptor and its index.
BOOL foundIt = NO;
uint32_t valueDescriptorIndex;
@@ -902,16 +896,39 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
if (!foundIt) {
return nil;
}
+ return [self getEnumTextFormatNameForIndex:valueDescriptorIndex];
+}
+
+- (uint32_t)enumNameCount {
+ return valueCount_;
+}
+
+- (NSString *)getEnumNameForIndex:(uint32_t)index {
+ if (nameOffsets_ == NULL) [self calcValueNameOffsets];
+ if (index >= valueCount_) {
+ return nil;
+ }
+ const char *valueName = valueNames_ + nameOffsets_[index];
+ NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName];
+ return fullName;
+}
+
+- (NSString *)getEnumTextFormatNameForIndex:(uint32_t)index {
+ if (nameOffsets_ == NULL) [self calcValueNameOffsets];
+
+ if (index >= valueCount_) {
+ return nil;
+ }
NSString *result = nil;
// Naming adds an underscore between enum name and value name, skip that also.
- const char *valueName = valueNames_ + nameOffsets_[valueDescriptorIndex];
+ const char *valueName = valueNames_ + nameOffsets_[index];
NSString *shortName = @(valueName);
// See if it is in the map of special format handling.
if (extraTextFormatInfo_) {
result = GPBDecodeTextFormatName(extraTextFormatInfo_,
- (int32_t)valueDescriptorIndex, shortName);
+ (int32_t)index, shortName);
}
// Logic here needs to match what objectivec_enum.cc does in the proto
// compiler.
diff --git a/objectivec/GPBUnknownField.m b/objectivec/GPBUnknownField.m
index 9d5c97f3..7fa8cade 100644
--- a/objectivec/GPBUnknownField.m
+++ b/objectivec/GPBUnknownField.m
@@ -32,6 +32,7 @@
#import "GPBArray.h"
#import "GPBCodedOutputStream_PackagePrivate.h"
+#import "GPBUnknownFieldSet.h"
@implementation GPBUnknownField {
@protected
diff --git a/objectivec/README.md b/objectivec/README.md
index a02df33f..528f5472 100644
--- a/objectivec/README.md
+++ b/objectivec/README.md
@@ -1,7 +1,7 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf)
+[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_cocoapods_integration.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_cocoapods_integration%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_debug.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_debug%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_ios_release.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_ios_release%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-objectivec_osx.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fobjectivec_osx%2Fcontinuous)
Copyright 2008 Google Inc.
@@ -20,9 +20,10 @@ The Objective C implementation requires:
Installation
------------
-The full distribution pulled from github includes the sources for both the
-compiler (protoc) and the runtime (this directory). To build the compiler
-and run the runtime tests, you can use:
+The distribution pulled from github includes the sources for both the
+compiler (protoc) and the runtime (this directory). After cloning the distribution
+and needed submodules ([see the src directory's README](../src/README.md)),
+to build the compiler and run the runtime tests, you can use:
$ objectivec/DevTools/full_mac_build.sh
diff --git a/objectivec/Tests/GPBDescriptorTests.m b/objectivec/Tests/GPBDescriptorTests.m
index 199ea655..d47cc30f 100644
--- a/objectivec/Tests/GPBDescriptorTests.m
+++ b/objectivec/Tests/GPBDescriptorTests.m
@@ -190,6 +190,63 @@
XCTAssertFalse([descriptor getValue:&value forEnumTextFormatName:@"Unknown"]);
}
+- (void)testEnumDescriptorIntrospection {
+ GPBEnumDescriptor *descriptor = TestAllTypes_NestedEnum_EnumDescriptor();
+
+ XCTAssertEqual(descriptor.enumNameCount, 4U);
+ XCTAssertEqualObjects([descriptor getEnumNameForIndex:0],
+ @"TestAllTypes_NestedEnum_Foo");
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:0], @"FOO");
+ XCTAssertEqualObjects([descriptor getEnumNameForIndex:1],
+ @"TestAllTypes_NestedEnum_Bar");
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:1], @"BAR");
+ XCTAssertEqualObjects([descriptor getEnumNameForIndex:2],
+ @"TestAllTypes_NestedEnum_Baz");
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:2], @"BAZ");
+ XCTAssertEqualObjects([descriptor getEnumNameForIndex:3],
+ @"TestAllTypes_NestedEnum_Neg");
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:3], @"NEG");
+}
+
+- (void)testEnumDescriptorIntrospectionWithAlias {
+ GPBEnumDescriptor *descriptor = TestEnumWithDupValue_EnumDescriptor();
+ NSString *enumName;
+ int32_t value;
+
+ XCTAssertEqual(descriptor.enumNameCount, 5U);
+
+ enumName = [descriptor getEnumNameForIndex:0];
+ XCTAssertEqualObjects(enumName, @"TestEnumWithDupValue_Foo1");
+ XCTAssertTrue([descriptor getValue:&value forEnumName:enumName]);
+ XCTAssertEqual(value, 1);
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:0], @"FOO1");
+
+ enumName = [descriptor getEnumNameForIndex:1];
+ XCTAssertEqualObjects(enumName, @"TestEnumWithDupValue_Bar1");
+ XCTAssertTrue([descriptor getValue:&value forEnumName:enumName]);
+ XCTAssertEqual(value, 2);
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:1], @"BAR1");
+
+ enumName = [descriptor getEnumNameForIndex:2];
+ XCTAssertEqualObjects(enumName, @"TestEnumWithDupValue_Baz");
+ XCTAssertTrue([descriptor getValue:&value forEnumName:enumName]);
+ XCTAssertEqual(value, 3);
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:2], @"BAZ");
+
+ enumName = [descriptor getEnumNameForIndex:3];
+ XCTAssertEqualObjects(enumName, @"TestEnumWithDupValue_Foo2");
+ XCTAssertTrue([descriptor getValue:&value forEnumName:enumName]);
+ XCTAssertEqual(value, 1);
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:3], @"FOO2");
+
+ enumName = [descriptor getEnumNameForIndex:4];
+ XCTAssertEqualObjects(enumName, @"TestEnumWithDupValue_Bar2");
+ XCTAssertTrue([descriptor getValue:&value forEnumName:enumName]);
+ XCTAssertEqual(value, 2);
+ XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:4], @"BAR2");
+
+}
+
- (void)testEnumValueValidator {
GPBDescriptor *descriptor = [TestAllTypes descriptor];
GPBFieldDescriptor *fieldDescriptor =
diff --git a/objectivec/Tests/GPBMessageTests.m b/objectivec/Tests/GPBMessageTests.m
index a3149096..8ebbe6de 100644
--- a/objectivec/Tests/GPBMessageTests.m
+++ b/objectivec/Tests/GPBMessageTests.m
@@ -1981,7 +1981,7 @@
}
- (void)testOneBasedEnumHolder {
- // Test case for https://github.com/google/protobuf/issues/1453
+ // Test case for https://github.com/protocolbuffers/protobuf/issues/1453
// Message with no explicit defaults, but a non zero default for an enum.
MessageWithOneBasedEnum *enumMsg = [MessageWithOneBasedEnum message];
XCTAssertEqual(enumMsg.enumField, MessageWithOneBasedEnum_OneBasedEnum_One);
diff --git a/objectivec/Tests/GPBTestUtilities.m b/objectivec/Tests/GPBTestUtilities.m
index ebccaac9..0362bdde 100644
--- a/objectivec/Tests/GPBTestUtilities.m
+++ b/objectivec/Tests/GPBTestUtilities.m
@@ -85,7 +85,7 @@ const uint32_t kGPBDefaultRepeatCount = 2;
NSLog(@"Wrote data file to %@", path);
#else
// Kill off the unused variable warning.
- dataToWrite = dataToWrite;
+ (void)dataToWrite;
#endif
return data;
}
diff --git a/objectivec/Tests/unittest_objc.proto b/objectivec/Tests/unittest_objc.proto
index b0eb4723..2202e6ca 100644
--- a/objectivec/Tests/unittest_objc.proto
+++ b/objectivec/Tests/unittest_objc.proto
@@ -433,7 +433,7 @@ message EnumTestMsg {
repeated MyEnum mumble = 4;
}
-// Test case for https://github.com/google/protobuf/issues/1453
+// Test case for https://github.com/protocolbuffers/protobuf/issues/1453
// Message with no explicit defaults, but a non zero default for an enum.
message MessageWithOneBasedEnum {
enum OneBasedEnum {
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index ad261898..2091d72d 100644
--- a/objectivec/google/protobuf/Any.pbobjc.h
+++ b/objectivec/google/protobuf/Any.pbobjc.h
@@ -140,7 +140,8 @@ typedef GPB_ENUM(GPBAny_FieldNumber) {
/**
* A URL/resource name that uniquely identifies the type of the serialized
- * protocol buffer message. The last segment of the URL's path must represent
+ * protocol buffer message. This string must contain at least
+ * one "/" character. 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).
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h
index 73296d57..72cac9aa 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.h
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.h
@@ -123,57 +123,49 @@ typedef GPB_ENUM(GPBFieldMask_FieldNumber) {
* 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 repeated field is specified for an update operation, new values will
+ * be appended to the existing repeated field in the target resource. 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:
+ * update operation, then new value will be merged into the existing sub-message
+ * in the target resource.
+ *
+ * For example, given the target message:
*
* f {
* b {
- * d : 1
- * x : 2
+ * d: 1
+ * x: 2
* }
- * c : 1
+ * c: [1]
* }
*
* And an update message:
*
* f {
* b {
- * d : 10
+ * d: 10
* }
+ * c: [2]
* }
*
* then if the field mask is:
*
- * paths: "f.b"
+ * paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
- * d : 10
+ * d: 10
+ * x: 2
* }
- * c : 1
+ * c: [1, 2]
* }
*
- * However, if the update mask was:
- *
- * paths: "f.b.d"
- *
- * then the result would be:
- *
- * f {
- * b {
- * d : 10
- * x : 2
- * }
- * c : 1
- * }
+ * An implementation may provide options to override this default behavior for
+ * repeated and message fields.
*
* 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.
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index 2c4b8b20..dc4cef75 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.h
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.h
@@ -132,7 +132,7 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
* 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--
+ * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
* ) to obtain a formatter capable of generating timestamps in this format.
**/
@interface GPBTimestamp : GPBMessage
diff --git a/php/README.md b/php/README.md
index da7884ea..e307768d 100644
--- a/php/README.md
+++ b/php/README.md
@@ -17,7 +17,7 @@ generation functionality.
To use PHP runtime library requires:
- C extension: PHP 5.5, 5.6, or 7.
-- PHP package: PHP 5.5, 5.6 or 7.
+- [PHP package](http://php.net/downloads.php): PHP 5.5, 5.6 or 7.
## Installation
@@ -36,7 +36,7 @@ To install the c extension, the following tools are needed:
On Ubuntu, you can install them with:
```
-sudo apt-get install php-pear php5-dev autoconf automake libtool make gcc
+sudo apt-get install -y php-pear php5-dev autoconf automake libtool make gcc
```
On other platforms, please use the corresponding package managing tool to
install them before proceeding.
diff --git a/php/composer.json b/php/composer.json
index 34e0447c..20f6a45e 100644
--- a/php/composer.json
+++ b/php/composer.json
@@ -9,13 +9,20 @@
"php": ">=5.5.0"
},
"require-dev": {
- "phpunit/phpunit": ">=4.8.0"
+ "phpunit/phpunit": "^5|^4.8.0"
},
"autoload": {
"psr-4": {
"Google\\Protobuf\\": "src/Google/Protobuf",
- "GPBMetadata\\Google\\Protobuf\\": "src/GPBMetadata/Google/Protobuf",
+ "GPBMetadata\\Google\\Protobuf\\": "src/GPBMetadata/Google/Protobuf"
+ }
+ },
+ "autoload-dev": {
+ "psr-4": {
"": "tests/generated"
}
+ },
+ "scripts": {
+ "test": "(cd tests && rm -rf generated && mkdir -p generated && ../../src/protoc --php_out=generated proto/empty/echo.proto 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) && (cd ../src && ./protoc --php_out=../php/tests/generated -I../php/tests -I. ../php/tests/proto/test_import_descriptor_proto.proto) && vendor/bin/phpunit"
}
}
diff --git a/php/ext/google/protobuf/encode_decode.c b/php/ext/google/protobuf/encode_decode.c
index de13dfa8..899b99f0 100644
--- a/php/ext/google/protobuf/encode_decode.c
+++ b/php/ext/google/protobuf/encode_decode.c
@@ -1587,8 +1587,11 @@ PHP_METHOD(Message, mergeFromJsonString) {
char *data = NULL;
PHP_PROTO_SIZE data_len;
+ zend_bool ignore_json_unknown = false;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
+ if (zend_parse_parameters(
+ ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &data, &data_len,
+ &ignore_json_unknown) ==
FAILURE) {
return;
}
@@ -1607,7 +1610,7 @@ PHP_METHOD(Message, mergeFromJsonString) {
stackenv_init(&se, "Error occurred during parsing: %s");
upb_sink_reset(&sink, get_fill_handlers(desc), msg);
- parser = upb_json_parser_create(&se.env, method, &sink);
+ parser = upb_json_parser_create(&se.env, method, &sink, ignore_json_unknown);
upb_bufsrc_putbuf(data, data_len, upb_json_parser_input(parser));
stackenv_uninit(&se);
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index 76b97eef..0efe090d 100644
--- a/php/ext/google/protobuf/message.c
+++ b/php/ext/google/protobuf/message.c
@@ -30,6 +30,7 @@
#include <php.h>
#include <stdlib.h>
+#include <inttypes.h>
#include "protobuf.h"
#include "utf8.h"
@@ -1251,28 +1252,62 @@ PHP_METHOD(Timestamp, fromDateTime) {
return;
}
- // Get timestamp from Datetime object.
- zval retval;
- zval function_name;
- int64_t timestamp;
+ int64_t timestamp_seconds;
+ {
+ zval retval;
+ zval function_name;
#if PHP_MAJOR_VERSION < 7
- INIT_ZVAL(retval);
- INIT_ZVAL(function_name);
+ INIT_ZVAL(retval);
+ INIT_ZVAL(function_name);
#endif
- PHP_PROTO_ZVAL_STRING(&function_name, "date_timestamp_get", 1);
+ PHP_PROTO_ZVAL_STRING(&function_name, "date_timestamp_get", 1);
- if (call_user_function(EG(function_table), NULL, &function_name, &retval, 1,
- ZVAL_PTR_TO_CACHED_PTR(datetime) TSRMLS_CC) == FAILURE) {
- zend_error(E_ERROR, "Cannot get timestamp from DateTime.");
- return;
+ if (call_user_function(EG(function_table), NULL, &function_name, &retval, 1,
+ ZVAL_PTR_TO_CACHED_PTR(datetime) TSRMLS_CC) == FAILURE) {
+ zend_error(E_ERROR, "Cannot get timestamp from DateTime.");
+ return;
+ }
+
+ protobuf_convert_to_int64(&retval, &timestamp_seconds);
+
+ zval_dtor(&retval);
+ zval_dtor(&function_name);
}
- protobuf_convert_to_int64(&retval, &timestamp);
+ int64_t timestamp_micros;
+ {
+ zval retval;
+ zval function_name;
+ zval format_string;
- zval_dtor(&retval);
- zval_dtor(&function_name);
+#if PHP_MAJOR_VERSION < 7
+ INIT_ZVAL(retval);
+ INIT_ZVAL(function_name);
+ INIT_ZVAL(format_string);
+#endif
+
+ PHP_PROTO_ZVAL_STRING(&function_name, "date_format", 1);
+ PHP_PROTO_ZVAL_STRING(&format_string, "u", 1);
+
+ CACHED_VALUE params[2] = {
+ ZVAL_PTR_TO_CACHED_VALUE(datetime),
+ ZVAL_TO_CACHED_VALUE(format_string),
+ };
+
+ if (call_user_function(EG(function_table), NULL, &function_name, &retval,
+ ARRAY_SIZE(params), params TSRMLS_CC) == FAILURE) {
+ zend_error(E_ERROR, "Cannot format DateTime.");
+ return;
+ }
+
+ protobuf_convert_to_int64(&retval, &timestamp_micros);
+
+ zval_dtor(&retval);
+ zval_dtor(&function_name);
+ zval_dtor(&format_string);
+ }
// Set seconds
MessageHeader* self = UNBOX(MessageHeader, getThis());
@@ -1280,13 +1315,13 @@ PHP_METHOD(Timestamp, fromDateTime) {
upb_msgdef_ntofz(self->descriptor->msgdef, "seconds");
void* storage = message_data(self);
void* memory = slot_memory(self->descriptor->layout, storage, field);
- *(int64_t*)memory = timestamp;
+ *(int64_t*)memory = timestamp_seconds;
// 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;
+ *(int32_t*)memory = timestamp_micros * 1000;
RETURN_NULL();
}
@@ -1305,38 +1340,41 @@ PHP_METHOD(Timestamp, toDateTime) {
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);
+ // Get formatted time string.
+ char formatted_time[32];
+ snprintf(formatted_time, sizeof(formatted_time), "%" PRId64 ".%06" PRId32,
+ seconds, nanos / 1000);
// Create Datetime object.
zval datetime;
- zval formated_time_php;
zval function_name;
- int64_t timestamp = 0;
+ zval format_string;
+ zval formatted_time_php;
#if PHP_MAJOR_VERSION < 7
INIT_ZVAL(function_name);
- INIT_ZVAL(formated_time_php);
+ INIT_ZVAL(format_string);
+ INIT_ZVAL(formatted_time_php);
#endif
- PHP_PROTO_ZVAL_STRING(&function_name, "date_create", 1);
- PHP_PROTO_ZVAL_STRING(&formated_time_php, formated_time, 1);
+ PHP_PROTO_ZVAL_STRING(&function_name, "date_create_from_format", 1);
+ PHP_PROTO_ZVAL_STRING(&format_string, "U.u", 1);
+ PHP_PROTO_ZVAL_STRING(&formatted_time_php, formatted_time, 1);
- CACHED_VALUE params[1] = {ZVAL_TO_CACHED_VALUE(formated_time_php)};
+ CACHED_VALUE params[2] = {
+ ZVAL_TO_CACHED_VALUE(format_string),
+ ZVAL_TO_CACHED_VALUE(formatted_time_php),
+ };
- if (call_user_function(EG(function_table), NULL,
- &function_name, &datetime, 1,
- params TSRMLS_CC) == FAILURE) {
+ if (call_user_function(EG(function_table), NULL, &function_name, &datetime,
+ ARRAY_SIZE(params), params TSRMLS_CC) == FAILURE) {
zend_error(E_ERROR, "Cannot create DateTime.");
return;
}
- zval_dtor(&formated_time_php);
zval_dtor(&function_name);
+ zval_dtor(&format_string);
+ zval_dtor(&formatted_time_php);
#if PHP_MAJOR_VERSION < 7
zval* datetime_ptr = &datetime;
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h
index 48072a4f..a84feec6 100644
--- a/php/ext/google/protobuf/protobuf.h
+++ b/php/ext/google/protobuf/protobuf.h
@@ -42,6 +42,10 @@
#define MAX_LENGTH_OF_INT64 20
#define SIZEOF_INT64 8
+/* From Chromium. */
+#define ARRAY_SIZE(x) \
+ ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
+
// -----------------------------------------------------------------------------
// PHP7 Wrappers
// ----------------------------------------------------------------------------
@@ -134,7 +138,8 @@
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;
+ LOWWERNAME##_type->create_object = message_create; \
+ zend_do_inheritance(LOWWERNAME##_type, message_type TSRMLS_CC);
#define PHP_PROTO_INIT_SUBMSGCLASS_END \
}
@@ -400,7 +405,7 @@ static inline int php_proto_zend_hash_get_current_data_ex(HashTable* ht,
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;
+ zend_do_inheritance(LOWWERNAME##_type, message_type TSRMLS_CC);
#define PHP_PROTO_INIT_SUBMSGCLASS_END \
}
diff --git a/php/ext/google/protobuf/upb.c b/php/ext/google/protobuf/upb.c
index e01f3bfd..90c52aa8 100644
--- a/php/ext/google/protobuf/upb.c
+++ b/php/ext/google/protobuf/upb.c
@@ -14280,6 +14280,39 @@ done:
#define UPB_JSON_MAX_DEPTH 64
+static const char *kDoubleValueFullMessageName = "google.protobuf.DoubleValue";
+static const char *kFloatValueFullMessageName = "google.protobuf.FloatValue";
+static const char *kInt64ValueFullMessageName = "google.protobuf.Int64Value";
+static const char *kUInt64ValueFullMessageName = "google.protobuf.UInt64Value";
+static const char *kInt32ValueFullMessageName = "google.protobuf.Int32Value";
+static const char *kUInt32ValueFullMessageName = "google.protobuf.UInt32Value";
+static const char *kBoolValueFullMessageName = "google.protobuf.BoolValue";
+static const char *kStringValueFullMessageName = "google.protobuf.StringValue";
+static const char *kBytesValueFullMessageName = "google.protobuf.BytesValue";
+
+/* Forward declare */
+static bool is_top_level(upb_json_parser *p);
+
+static bool is_number_wrapper_object(upb_json_parser *p);
+static bool does_number_wrapper_start(upb_json_parser *p);
+static bool does_number_wrapper_end(upb_json_parser *p);
+
+static bool is_string_wrapper_object(upb_json_parser *p);
+static bool does_string_wrapper_start(upb_json_parser *p);
+static bool does_string_wrapper_end(upb_json_parser *p);
+
+static bool is_boolean_wrapper_object(upb_json_parser *p);
+static bool does_boolean_wrapper_start(upb_json_parser *p);
+static bool does_boolean_wrapper_end(upb_json_parser *p);
+
+static void start_wrapper_object(upb_json_parser *p);
+static void end_wrapper_object(upb_json_parser *p);
+
+static bool start_subobject(upb_json_parser *p);
+static void end_subobject(upb_json_parser *p);
+
+static const char eof_ch = 'e';
+
typedef struct {
upb_sink sink;
@@ -14344,6 +14377,9 @@ struct upb_json_parser {
/* Intermediate result of parsing a unicode escape sequence. */
uint32_t digit;
+
+ /* Whether to proceed if unknown field is met. */
+ bool ignore_json_unknown;
};
struct upb_json_parsermethod {
@@ -14852,21 +14888,54 @@ static bool end_text(upb_json_parser *p, const char *ptr) {
return capture_end(p, ptr);
}
-static void start_number(upb_json_parser *p, const char *ptr) {
+static bool start_number(upb_json_parser *p, const char *ptr) {
+ if (is_top_level(p)) {
+ if (!is_number_wrapper_object(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ } else if (does_number_wrapper_start(p)) {
+ if (!start_subobject(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ }
+
multipart_startaccum(p);
capture_begin(p, ptr);
+ return true;
}
static bool parse_number(upb_json_parser *p, bool is_quoted);
-static bool end_number(upb_json_parser *p, const char *ptr) {
+static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
if (!capture_end(p, ptr)) {
return false;
}
+ if (p->top->f == NULL) {
+ multipart_end(p);
+ return true;
+ }
+
return parse_number(p, false);
}
+static bool end_number(upb_json_parser *p, const char *ptr) {
+ if (!end_number_nontop(p, ptr)) {
+ return false;
+ }
+
+ if (does_number_wrapper_end(p)) {
+ end_wrapper_object(p);
+ if (!is_top_level(p)) {
+ end_subobject(p);
+ }
+ }
+
+ return true;
+}
+
/* |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,
@@ -15016,6 +15085,10 @@ static bool parse_number(upb_json_parser *p, bool is_quoted) {
static bool parser_putbool(upb_json_parser *p, bool val) {
bool ok;
+ if (p->top->f == NULL) {
+ return true;
+ }
+
if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
upb_status_seterrf(&p->status,
"Boolean value specified for non-bool field: %s",
@@ -15030,8 +15103,50 @@ static bool parser_putbool(upb_json_parser *p, bool val) {
return true;
}
+static bool end_bool(upb_json_parser *p, bool val) {
+ if (is_top_level(p)) {
+ if (!is_boolean_wrapper_object(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ } else if (does_boolean_wrapper_start(p)) {
+ if (!start_subobject(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ }
+
+ if (!parser_putbool(p, val)) {
+ return false;
+ }
+
+ if (does_boolean_wrapper_end(p)) {
+ end_wrapper_object(p);
+ if (!is_top_level(p)) {
+ end_subobject(p);
+ }
+ }
+
+ return true;
+}
+
static bool start_stringval(upb_json_parser *p) {
- UPB_ASSERT(p->top->f);
+ if (is_top_level(p)) {
+ if (!is_string_wrapper_object(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ } else if (does_string_wrapper_start(p)) {
+ if (!start_subobject(p)) {
+ return false;
+ }
+ start_wrapper_object(p);
+ }
+
+ if (p->top->f == NULL) {
+ multipart_startaccum(p);
+ return true;
+ }
if (upb_fielddef_isstring(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -15079,9 +15194,14 @@ static bool start_stringval(upb_json_parser *p) {
}
}
-static bool end_stringval(upb_json_parser *p) {
+static bool end_stringval_nontop(upb_json_parser *p) {
bool ok = true;
+ if (p->top->f == NULL) {
+ multipart_end(p);
+ return true;
+ }
+
switch (upb_fielddef_type(p->top->f)) {
case UPB_TYPE_BYTES:
if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
@@ -15141,6 +15261,21 @@ static bool end_stringval(upb_json_parser *p) {
return ok;
}
+static bool end_stringval(upb_json_parser *p) {
+ if (!end_stringval_nontop(p)) {
+ return false;
+ }
+
+ if (does_string_wrapper_end(p)) {
+ end_wrapper_object(p);
+ if (!is_top_level(p)) {
+ end_subobject(p);
+ }
+ }
+
+ return true;
+}
+
static void start_member(upb_json_parser *p) {
UPB_ASSERT(!p->top->f);
multipart_startaccum(p);
@@ -15273,6 +15408,10 @@ static bool handle_mapentry(upb_json_parser *p) {
static bool end_membername(upb_json_parser *p) {
UPB_ASSERT(!p->top->f);
+ if (!p->top->m) {
+ return true;
+ }
+
if (p->top->is_map) {
return handle_mapentry(p);
} else {
@@ -15285,9 +15424,10 @@ static bool end_membername(upb_json_parser *p) {
multipart_end(p);
return true;
+ } else if (p->ignore_json_unknown) {
+ multipart_end(p);
+ return true;
} else {
- /* TODO(haberman): Ignore unknown fields if requested/configured to do
- * so. */
upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
upb_env_reporterror(p->env, &p->status);
return false;
@@ -15319,7 +15459,22 @@ static void end_member(upb_json_parser *p) {
}
static bool start_subobject(upb_json_parser *p) {
- UPB_ASSERT(p->top->f);
+ if (is_top_level(p)) {
+ return true;
+ }
+
+ if (p->top->f == NULL) {
+ upb_jsonparser_frame *inner;
+ if (!check_stack(p)) return false;
+
+ inner = p->top + 1;
+ inner->m = NULL;
+ inner->f = NULL;
+ inner->is_map = false;
+ inner->is_mapentry = false;
+ p->top = inner;
+ return true;
+ }
if (upb_fielddef_ismap(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -15371,6 +15526,10 @@ static bool start_subobject(upb_json_parser *p) {
}
static void end_subobject(upb_json_parser *p) {
+ if (is_top_level(p)) {
+ return;
+ }
+
if (p->top->is_map) {
upb_selector_t sel;
p->top--;
@@ -15378,9 +15537,12 @@ static void end_subobject(upb_json_parser *p) {
upb_sink_endseq(&p->top->sink, sel);
} else {
upb_selector_t sel;
+ bool is_unknown = p->top->m == NULL;
p->top--;
- sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
- upb_sink_endsubmsg(&p->top->sink, sel);
+ if (!is_unknown) {
+ sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
+ upb_sink_endsubmsg(&p->top->sink, sel);
+ }
}
}
@@ -15440,6 +15602,118 @@ static void end_object(upb_json_parser *p) {
}
}
+static bool is_double_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kDoubleValueFullMessageName) == 0;
+}
+
+static bool is_float_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kFloatValueFullMessageName) == 0;
+}
+
+static bool is_int64_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kInt64ValueFullMessageName) == 0;
+}
+
+static bool is_uint64_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kUInt64ValueFullMessageName) == 0;
+}
+
+static bool is_int32_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kInt32ValueFullMessageName) == 0;
+}
+
+static bool is_uint32_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kUInt32ValueFullMessageName) == 0;
+}
+
+static bool is_bool_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kBoolValueFullMessageName) == 0;
+}
+
+static bool is_string_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kStringValueFullMessageName) == 0;
+}
+
+static bool is_bytes_value(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), kBytesValueFullMessageName) == 0;
+}
+
+static bool is_number_wrapper(const upb_msgdef *m) {
+ return is_double_value(m) ||
+ is_float_value(m) ||
+ is_int64_value(m) ||
+ is_uint64_value(m) ||
+ is_int32_value(m) ||
+ is_uint32_value(m);
+}
+
+static bool is_string_wrapper(const upb_msgdef *m) {
+ return is_string_value(m) ||
+ is_bytes_value(m);
+}
+
+static void start_wrapper_object(upb_json_parser *p) {
+ const char *membername = "value";
+
+ start_object(p);
+
+ /* Set up context for parsing value */
+ start_member(p);
+ capture_begin(p, membername);
+ capture_end(p, membername + 5);
+ end_membername(p);
+}
+
+static void end_wrapper_object(upb_json_parser *p) {
+ end_member(p);
+ end_object(p);
+}
+
+static bool is_top_level(upb_json_parser *p) {
+ return p->top == p->stack && p->top->f == NULL;
+}
+
+static bool does_number_wrapper_start(upb_json_parser *p) {
+ return p->top->f != NULL &&
+ upb_fielddef_issubmsg(p->top->f) &&
+ is_number_wrapper(upb_fielddef_msgsubdef(p->top->f));
+}
+
+static bool does_number_wrapper_end(upb_json_parser *p) {
+ return p->top->m != NULL && is_number_wrapper(p->top->m);
+}
+
+static bool is_number_wrapper_object(upb_json_parser *p) {
+ return p->top->m != NULL && is_number_wrapper(p->top->m);
+}
+
+static bool does_string_wrapper_start(upb_json_parser *p) {
+ return p->top->f != NULL &&
+ upb_fielddef_issubmsg(p->top->f) &&
+ is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
+}
+
+static bool does_string_wrapper_end(upb_json_parser *p) {
+ return p->top->m != NULL && is_string_wrapper(p->top->m);
+}
+
+static bool is_string_wrapper_object(upb_json_parser *p) {
+ return p->top->m != NULL && is_string_wrapper(p->top->m);
+}
+
+static bool does_boolean_wrapper_start(upb_json_parser *p) {
+ return p->top->f != NULL &&
+ upb_fielddef_issubmsg(p->top->f) &&
+ is_bool_value(upb_fielddef_msgsubdef(p->top->f));
+}
+
+static bool does_boolean_wrapper_end(upb_json_parser *p) {
+ return p->top->m != NULL && is_bool_value(p->top->m);
+}
+
+static bool is_boolean_wrapper_object(upb_json_parser *p) {
+ return p->top->m != NULL && is_bool_value(p->top->m);
+}
#define CHECK_RETURN_TOP(x) if (!(x)) goto error
@@ -15462,160 +15736,204 @@ static void end_object(upb_json_parser *p) {
* final state once, when the closing '"' is seen. */
-#line 1310 "upb/json/parser.rl"
+#line 1589 "upb/json/parser.rl"
-#line 1222 "upb/json/parser.c"
+#line 1496 "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,
- 10, 1, 12, 1, 13, 1, 14, 1,
- 15, 1, 16, 1, 17, 1, 21, 1,
- 25, 1, 27, 2, 3, 8, 2, 4,
- 5, 2, 6, 2, 2, 6, 8, 2,
- 11, 9, 2, 13, 15, 2, 14, 15,
- 2, 18, 1, 2, 19, 27, 2, 20,
- 9, 2, 22, 27, 2, 23, 27, 2,
- 24, 27, 2, 26, 27, 3, 14, 11,
- 9
+ 0, 1, 0, 1, 1, 1, 3, 1,
+ 4, 1, 6, 1, 7, 1, 8, 1,
+ 9, 1, 11, 1, 13, 1, 14, 1,
+ 15, 1, 16, 1, 17, 1, 18, 1,
+ 20, 1, 22, 1, 23, 1, 24, 1,
+ 25, 1, 26, 1, 27, 1, 28, 2,
+ 4, 9, 2, 5, 6, 2, 7, 3,
+ 2, 7, 9, 2, 12, 10, 2, 14,
+ 16, 2, 15, 16, 2, 19, 2, 2,
+ 20, 28, 2, 21, 10, 2, 23, 28,
+ 2, 24, 28, 2, 25, 28, 2, 27,
+ 28, 3, 15, 12, 10
};
static const unsigned char _json_key_offsets[] = {
- 0, 0, 4, 9, 14, 15, 19, 24,
- 29, 34, 38, 42, 45, 48, 50, 54,
- 58, 60, 62, 67, 69, 71, 80, 86,
- 92, 98, 104, 106, 115, 116, 116, 116,
- 121, 126, 131, 132, 133, 134, 135, 135,
- 136, 137, 138, 138, 139, 140, 141, 141,
- 146, 151, 152, 156, 161, 166, 171, 175,
- 175, 178, 178, 178
+ 0, 0, 12, 13, 18, 23, 28, 29,
+ 30, 31, 32, 33, 34, 35, 36, 37,
+ 38, 43, 48, 49, 53, 58, 63, 68,
+ 72, 76, 79, 82, 84, 88, 92, 94,
+ 96, 101, 103, 105, 114, 120, 126, 132,
+ 138, 140, 149, 150, 150, 150, 155, 160,
+ 165, 166, 167, 168, 169, 169, 170, 171,
+ 172, 172, 173, 174, 175, 175, 180, 185,
+ 186, 190, 195, 200, 205, 209, 209, 212,
+ 215, 218, 221, 224, 227, 227, 227
};
static const char _json_trans_keys[] = {
- 32, 123, 9, 13, 32, 34, 125, 9,
- 13, 32, 34, 125, 9, 13, 34, 32,
- 58, 9, 13, 32, 93, 125, 9, 13,
- 32, 44, 125, 9, 13, 32, 44, 125,
- 9, 13, 32, 34, 9, 13, 45, 48,
- 49, 57, 48, 49, 57, 46, 69, 101,
- 48, 57, 69, 101, 48, 57, 43, 45,
- 48, 57, 48, 57, 48, 57, 46, 69,
- 101, 48, 57, 34, 92, 34, 92, 34,
- 47, 92, 98, 102, 110, 114, 116, 117,
+ 32, 34, 45, 91, 102, 110, 116, 123,
+ 9, 13, 48, 57, 34, 32, 93, 125,
+ 9, 13, 32, 44, 93, 9, 13, 32,
+ 93, 125, 9, 13, 97, 108, 115, 101,
+ 117, 108, 108, 114, 117, 101, 32, 34,
+ 125, 9, 13, 32, 34, 125, 9, 13,
+ 34, 32, 58, 9, 13, 32, 93, 125,
+ 9, 13, 32, 44, 125, 9, 13, 32,
+ 44, 125, 9, 13, 32, 34, 9, 13,
+ 45, 48, 49, 57, 48, 49, 57, 46,
+ 69, 101, 48, 57, 69, 101, 48, 57,
+ 43, 45, 48, 57, 48, 57, 48, 57,
+ 46, 69, 101, 48, 57, 34, 92, 34,
+ 92, 34, 47, 92, 98, 102, 110, 114,
+ 116, 117, 48, 57, 65, 70, 97, 102,
48, 57, 65, 70, 97, 102, 48, 57,
65, 70, 97, 102, 48, 57, 65, 70,
- 97, 102, 48, 57, 65, 70, 97, 102,
- 34, 92, 34, 45, 91, 102, 110, 116,
- 123, 48, 57, 34, 32, 93, 125, 9,
- 13, 32, 44, 93, 9, 13, 32, 93,
- 125, 9, 13, 97, 108, 115, 101, 117,
- 108, 108, 114, 117, 101, 32, 34, 125,
- 9, 13, 32, 34, 125, 9, 13, 34,
- 32, 58, 9, 13, 32, 93, 125, 9,
- 13, 32, 44, 125, 9, 13, 32, 44,
- 125, 9, 13, 32, 34, 9, 13, 32,
- 9, 13, 0
+ 97, 102, 34, 92, 34, 45, 91, 102,
+ 110, 116, 123, 48, 57, 34, 32, 93,
+ 125, 9, 13, 32, 44, 93, 9, 13,
+ 32, 93, 125, 9, 13, 97, 108, 115,
+ 101, 117, 108, 108, 114, 117, 101, 32,
+ 34, 125, 9, 13, 32, 34, 125, 9,
+ 13, 34, 32, 58, 9, 13, 32, 93,
+ 125, 9, 13, 32, 44, 125, 9, 13,
+ 32, 44, 125, 9, 13, 32, 34, 9,
+ 13, 32, 9, 13, 32, 9, 13, 32,
+ 9, 13, 32, 9, 13, 32, 9, 13,
+ 32, 9, 13, 0
};
static const char _json_single_lengths[] = {
- 0, 2, 3, 3, 1, 2, 3, 3,
- 3, 2, 2, 1, 3, 0, 2, 2,
- 0, 0, 3, 2, 2, 9, 0, 0,
- 0, 0, 2, 7, 1, 0, 0, 3,
- 3, 3, 1, 1, 1, 1, 0, 1,
- 1, 1, 0, 1, 1, 1, 0, 3,
- 3, 1, 2, 3, 3, 3, 2, 0,
- 1, 0, 0, 0
+ 0, 8, 1, 3, 3, 3, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1,
+ 3, 3, 1, 2, 3, 3, 3, 2,
+ 2, 1, 3, 0, 2, 2, 0, 0,
+ 3, 2, 2, 9, 0, 0, 0, 0,
+ 2, 7, 1, 0, 0, 3, 3, 3,
+ 1, 1, 1, 1, 0, 1, 1, 1,
+ 0, 1, 1, 1, 0, 3, 3, 1,
+ 2, 3, 3, 3, 2, 0, 1, 1,
+ 1, 1, 1, 1, 0, 0, 0
};
static const char _json_range_lengths[] = {
- 0, 1, 1, 1, 0, 1, 1, 1,
- 1, 1, 1, 1, 0, 1, 1, 1,
- 1, 1, 1, 0, 0, 0, 3, 3,
- 3, 3, 0, 1, 0, 0, 0, 1,
- 1, 1, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 1,
- 1, 0, 1, 1, 1, 1, 1, 0,
- 1, 0, 0, 0
+ 0, 2, 0, 1, 1, 1, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 0, 1, 1, 1, 1, 1,
+ 1, 1, 0, 1, 1, 1, 1, 1,
+ 1, 0, 0, 0, 3, 3, 3, 3,
+ 0, 1, 0, 0, 0, 1, 1, 1,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 1, 1, 0,
+ 1, 1, 1, 1, 1, 0, 1, 1,
+ 1, 1, 1, 1, 0, 0, 0
};
static const short _json_index_offsets[] = {
- 0, 0, 4, 9, 14, 16, 20, 25,
- 30, 35, 39, 43, 46, 50, 52, 56,
- 60, 62, 64, 69, 72, 75, 85, 89,
- 93, 97, 101, 104, 113, 115, 116, 117,
- 122, 127, 132, 134, 136, 138, 140, 141,
- 143, 145, 147, 148, 150, 152, 154, 155,
- 160, 165, 167, 171, 176, 181, 186, 190,
- 191, 194, 195, 196
+ 0, 0, 11, 13, 18, 23, 28, 30,
+ 32, 34, 36, 38, 40, 42, 44, 46,
+ 48, 53, 58, 60, 64, 69, 74, 79,
+ 83, 87, 90, 94, 96, 100, 104, 106,
+ 108, 113, 116, 119, 129, 133, 137, 141,
+ 145, 148, 157, 159, 160, 161, 166, 171,
+ 176, 178, 180, 182, 184, 185, 187, 189,
+ 191, 192, 194, 196, 198, 199, 204, 209,
+ 211, 215, 220, 225, 230, 234, 235, 238,
+ 241, 244, 247, 250, 253, 254, 255
};
static const char _json_indicies[] = {
- 0, 2, 0, 1, 3, 4, 5, 3,
- 1, 6, 7, 8, 6, 1, 9, 1,
- 10, 11, 10, 1, 11, 1, 1, 11,
- 12, 13, 14, 15, 13, 1, 16, 17,
- 8, 16, 1, 17, 7, 17, 1, 18,
- 19, 20, 1, 19, 20, 1, 22, 23,
- 23, 21, 24, 1, 23, 23, 24, 21,
- 25, 25, 26, 1, 26, 1, 26, 21,
- 22, 23, 23, 20, 21, 28, 29, 27,
- 31, 32, 30, 33, 33, 33, 33, 33,
- 33, 33, 33, 34, 1, 35, 35, 35,
- 1, 36, 36, 36, 1, 37, 37, 37,
- 1, 38, 38, 38, 1, 40, 41, 39,
- 42, 43, 44, 45, 46, 47, 48, 43,
- 1, 49, 1, 50, 51, 53, 54, 1,
- 53, 52, 55, 56, 54, 55, 1, 56,
- 1, 1, 56, 52, 57, 1, 58, 1,
- 59, 1, 60, 1, 61, 62, 1, 63,
- 1, 64, 1, 65, 66, 1, 67, 1,
- 68, 1, 69, 70, 71, 72, 70, 1,
- 73, 74, 75, 73, 1, 76, 1, 77,
- 78, 77, 1, 78, 1, 1, 78, 79,
- 80, 81, 82, 80, 1, 83, 84, 75,
- 83, 1, 84, 74, 84, 1, 85, 86,
- 86, 1, 1, 1, 1, 0
+ 0, 2, 3, 4, 5, 6, 7, 8,
+ 0, 3, 1, 9, 1, 11, 12, 1,
+ 11, 10, 13, 14, 12, 13, 1, 14,
+ 1, 1, 14, 10, 15, 1, 16, 1,
+ 17, 1, 18, 1, 19, 1, 20, 1,
+ 21, 1, 22, 1, 23, 1, 24, 1,
+ 25, 26, 27, 25, 1, 28, 29, 30,
+ 28, 1, 31, 1, 32, 33, 32, 1,
+ 33, 1, 1, 33, 34, 35, 36, 37,
+ 35, 1, 38, 39, 30, 38, 1, 39,
+ 29, 39, 1, 40, 41, 42, 1, 41,
+ 42, 1, 44, 45, 45, 43, 46, 1,
+ 45, 45, 46, 43, 47, 47, 48, 1,
+ 48, 1, 48, 43, 44, 45, 45, 42,
+ 43, 50, 51, 49, 53, 54, 52, 55,
+ 55, 55, 55, 55, 55, 55, 55, 56,
+ 1, 57, 57, 57, 1, 58, 58, 58,
+ 1, 59, 59, 59, 1, 60, 60, 60,
+ 1, 62, 63, 61, 64, 65, 66, 67,
+ 68, 69, 70, 65, 1, 71, 1, 72,
+ 73, 75, 76, 1, 75, 74, 77, 78,
+ 76, 77, 1, 78, 1, 1, 78, 74,
+ 79, 1, 80, 1, 81, 1, 82, 1,
+ 83, 84, 1, 85, 1, 86, 1, 87,
+ 88, 1, 89, 1, 90, 1, 91, 92,
+ 93, 94, 92, 1, 95, 96, 97, 95,
+ 1, 98, 1, 99, 100, 99, 1, 100,
+ 1, 1, 100, 101, 102, 103, 104, 102,
+ 1, 105, 106, 97, 105, 1, 106, 96,
+ 106, 1, 107, 108, 108, 1, 109, 109,
+ 1, 110, 110, 1, 111, 111, 1, 112,
+ 112, 1, 113, 113, 1, 1, 1, 1,
+ 0
};
static const char _json_trans_targs[] = {
- 1, 0, 2, 3, 4, 56, 3, 4,
- 56, 5, 5, 6, 7, 8, 9, 56,
- 8, 9, 11, 12, 18, 57, 13, 15,
- 14, 16, 17, 20, 58, 21, 20, 58,
- 21, 19, 22, 23, 24, 25, 26, 20,
- 58, 21, 28, 30, 31, 34, 39, 43,
- 47, 29, 59, 59, 32, 31, 29, 32,
- 33, 35, 36, 37, 38, 59, 40, 41,
- 42, 59, 44, 45, 46, 59, 48, 49,
- 55, 48, 49, 55, 50, 50, 51, 52,
- 53, 54, 55, 53, 54, 59, 56
+ 1, 0, 2, 71, 3, 6, 10, 13,
+ 16, 70, 4, 3, 70, 4, 5, 7,
+ 8, 9, 72, 11, 12, 73, 14, 15,
+ 74, 17, 18, 75, 17, 18, 75, 19,
+ 19, 20, 21, 22, 23, 75, 22, 23,
+ 25, 26, 32, 76, 27, 29, 28, 30,
+ 31, 34, 77, 35, 34, 77, 35, 33,
+ 36, 37, 38, 39, 40, 34, 77, 35,
+ 42, 44, 45, 48, 53, 57, 61, 43,
+ 78, 78, 46, 45, 43, 46, 47, 49,
+ 50, 51, 52, 78, 54, 55, 56, 78,
+ 58, 59, 60, 78, 62, 63, 69, 62,
+ 63, 69, 64, 64, 65, 66, 67, 68,
+ 69, 67, 68, 78, 70, 70, 70, 70,
+ 70, 70
};
static const char _json_trans_actions[] = {
- 0, 0, 0, 21, 77, 53, 0, 47,
- 23, 17, 0, 0, 15, 19, 19, 50,
- 0, 0, 0, 0, 0, 1, 0, 0,
- 0, 0, 0, 3, 13, 0, 0, 35,
- 5, 11, 0, 38, 7, 7, 7, 41,
- 44, 9, 62, 56, 25, 0, 0, 0,
- 31, 29, 33, 59, 15, 0, 27, 0,
- 0, 0, 0, 0, 0, 68, 0, 0,
- 0, 71, 0, 0, 0, 65, 21, 77,
- 53, 0, 47, 23, 17, 0, 0, 15,
- 19, 19, 50, 0, 0, 74, 0
+ 0, 0, 74, 68, 27, 0, 0, 0,
+ 41, 33, 17, 0, 29, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 23, 89, 65, 0, 59, 25, 19,
+ 0, 0, 17, 21, 21, 62, 0, 0,
+ 0, 0, 0, 3, 0, 0, 0, 0,
+ 0, 5, 15, 0, 0, 47, 7, 13,
+ 0, 50, 9, 9, 9, 53, 56, 11,
+ 74, 68, 27, 0, 0, 0, 41, 33,
+ 45, 71, 17, 0, 29, 0, 0, 0,
+ 0, 0, 0, 80, 0, 0, 0, 83,
+ 0, 0, 0, 77, 23, 89, 65, 0,
+ 59, 25, 19, 0, 0, 17, 21, 21,
+ 62, 0, 0, 86, 0, 31, 37, 39,
+ 35, 43
+};
+
+static const char _json_eof_actions[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 1, 0, 1, 0, 0, 1,
+ 1, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 31,
+ 37, 39, 35, 43, 0, 0, 0
};
static const int json_start = 1;
-static const int json_en_number_machine = 10;
-static const int json_en_string_machine = 19;
-static const int json_en_value_machine = 27;
+static const int json_en_number_machine = 24;
+static const int json_en_string_machine = 33;
+static const int json_en_value_machine = 41;
static const int json_en_main = 1;
-#line 1313 "upb/json/parser.rl"
+#line 1592 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -15628,6 +15946,7 @@ size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const char *p = buf;
const char *pe = buf + size;
+ const char *eof = &eof_ch;
parser->handle = handle;
@@ -15637,7 +15956,7 @@ size_t parse(void *closure, const void *hd, const char *buf, size_t size,
capture_resume(parser, buf);
-#line 1393 "upb/json/parser.c"
+#line 1712 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -15711,119 +16030,119 @@ _match:
{
switch ( *_acts++ )
{
- case 0:
-#line 1225 "upb/json/parser.rl"
- { p--; {cs = stack[--top]; goto _again;} }
- break;
case 1:
-#line 1226 "upb/json/parser.rl"
- { p--; {stack[top++] = cs; cs = 10; goto _again;} }
+#line 1503 "upb/json/parser.rl"
+ { p--; {cs = stack[--top]; goto _again;} }
break;
case 2:
-#line 1230 "upb/json/parser.rl"
- { start_text(parser, p); }
+#line 1505 "upb/json/parser.rl"
+ { p--; {stack[top++] = cs; cs = 24; goto _again;} }
break;
case 3:
-#line 1231 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(end_text(parser, p)); }
+#line 1509 "upb/json/parser.rl"
+ { start_text(parser, p); }
break;
case 4:
-#line 1237 "upb/json/parser.rl"
- { start_hex(parser); }
+#line 1510 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 5:
-#line 1238 "upb/json/parser.rl"
- { hexdigit(parser, p); }
+#line 1516 "upb/json/parser.rl"
+ { start_hex(parser); }
break;
case 6:
-#line 1239 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(end_hex(parser)); }
+#line 1517 "upb/json/parser.rl"
+ { hexdigit(parser, p); }
break;
case 7:
-#line 1245 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(escape(parser, p)); }
+#line 1518 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 8:
-#line 1251 "upb/json/parser.rl"
- { p--; {cs = stack[--top]; goto _again;} }
+#line 1524 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 9:
-#line 1254 "upb/json/parser.rl"
- { {stack[top++] = cs; cs = 19; goto _again;} }
+#line 1530 "upb/json/parser.rl"
+ { p--; {cs = stack[--top]; goto _again;} }
break;
case 10:
-#line 1256 "upb/json/parser.rl"
- { p--; {stack[top++] = cs; cs = 27; goto _again;} }
+#line 1533 "upb/json/parser.rl"
+ { {stack[top++] = cs; cs = 33; goto _again;} }
break;
case 11:
-#line 1261 "upb/json/parser.rl"
- { start_member(parser); }
+#line 1535 "upb/json/parser.rl"
+ { p--; {stack[top++] = cs; cs = 41; goto _again;} }
break;
case 12:
-#line 1262 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(end_membername(parser)); }
+#line 1540 "upb/json/parser.rl"
+ { start_member(parser); }
break;
case 13:
-#line 1265 "upb/json/parser.rl"
- { end_member(parser); }
+#line 1541 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 14:
-#line 1271 "upb/json/parser.rl"
- { start_object(parser); }
+#line 1544 "upb/json/parser.rl"
+ { end_member(parser); }
break;
case 15:
-#line 1274 "upb/json/parser.rl"
- { end_object(parser); }
+#line 1550 "upb/json/parser.rl"
+ { start_object(parser); }
break;
case 16:
-#line 1280 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(start_array(parser)); }
+#line 1553 "upb/json/parser.rl"
+ { end_object(parser); }
break;
case 17:
-#line 1284 "upb/json/parser.rl"
- { end_array(parser); }
+#line 1559 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(start_array(parser)); }
break;
case 18:
-#line 1289 "upb/json/parser.rl"
- { start_number(parser, p); }
+#line 1563 "upb/json/parser.rl"
+ { end_array(parser); }
break;
case 19:
-#line 1290 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(end_number(parser, p)); }
+#line 1568 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(start_number(parser, p)); }
break;
case 20:
-#line 1292 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(start_stringval(parser)); }
+#line 1569 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 21:
-#line 1293 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(end_stringval(parser)); }
+#line 1571 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 22:
-#line 1295 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(parser_putbool(parser, true)); }
+#line 1572 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 23:
-#line 1297 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(parser_putbool(parser, false)); }
+#line 1574 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_bool(parser, true)); }
break;
case 24:
-#line 1299 "upb/json/parser.rl"
- { /* null value */ }
+#line 1576 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_bool(parser, false)); }
break;
case 25:
-#line 1301 "upb/json/parser.rl"
- { CHECK_RETURN_TOP(start_subobject(parser)); }
+#line 1578 "upb/json/parser.rl"
+ { /* null value */ }
break;
case 26:
-#line 1302 "upb/json/parser.rl"
- { end_subobject(parser); }
+#line 1580 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(start_subobject(parser)); }
break;
case 27:
-#line 1307 "upb/json/parser.rl"
+#line 1581 "upb/json/parser.rl"
+ { end_subobject(parser); }
+ break;
+ case 28:
+#line 1586 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-#line 1579 "upb/json/parser.c"
+#line 1898 "upb/json/parser.c"
}
}
@@ -15833,10 +16152,47 @@ _again:
if ( ++p != pe )
goto _resume;
_test_eof: {}
+ if ( p == eof )
+ {
+ const char *__acts = _json_actions + _json_eof_actions[cs];
+ unsigned int __nacts = (unsigned int) *__acts++;
+ while ( __nacts-- > 0 ) {
+ switch ( *__acts++ ) {
+ case 0:
+#line 1499 "upb/json/parser.rl"
+ {
+ p--; {cs = stack[--top]; goto _again;}
+ }
+ break;
+ case 20:
+#line 1569 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_number(parser, p)); }
+ break;
+ case 23:
+#line 1574 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_bool(parser, true)); }
+ break;
+ case 24:
+#line 1576 "upb/json/parser.rl"
+ { CHECK_RETURN_TOP(end_bool(parser, false)); }
+ break;
+ case 25:
+#line 1578 "upb/json/parser.rl"
+ { /* null value */ }
+ break;
+ case 27:
+#line 1581 "upb/json/parser.rl"
+ { end_subobject(parser); }
+ break;
+#line 1940 "upb/json/parser.c"
+ }
+ }
+ }
+
_out: {}
}
-#line 1334 "upb/json/parser.rl"
+#line 1614 "upb/json/parser.rl"
if (p != pe) {
upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
@@ -15854,8 +16210,7 @@ error:
}
bool end(void *closure, const void *hd) {
- UPB_UNUSED(closure);
- UPB_UNUSED(hd);
+ upb_json_parser *parser = closure;
/* Prevent compile warning on unused static constants. */
UPB_UNUSED(json_start);
@@ -15863,7 +16218,14 @@ bool end(void *closure, const void *hd) {
UPB_UNUSED(json_en_string_machine);
UPB_UNUSED(json_en_value_machine);
UPB_UNUSED(json_en_main);
- return true;
+
+ parse(parser, hd, &eof_ch, 0, NULL);
+
+ return parser->current_state >=
+#line 1978 "upb/json/parser.c"
+70
+#line 1642 "upb/json/parser.rl"
+;
}
static void json_parser_reset(upb_json_parser *p) {
@@ -15877,13 +16239,13 @@ static void json_parser_reset(upb_json_parser *p) {
/* Emit Ragel initialization of the parser. */
-#line 1633 "upb/json/parser.c"
+#line 1995 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-#line 1374 "upb/json/parser.rl"
+#line 1656 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -15970,7 +16332,8 @@ static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
upb_json_parser *upb_json_parser_create(upb_env *env,
const upb_json_parsermethod *method,
- upb_sink *output) {
+ upb_sink *output,
+ bool ignore_json_unknown) {
#ifndef NDEBUG
const size_t size_before = upb_env_bytesallocated(env);
#endif
@@ -15989,6 +16352,8 @@ upb_json_parser *upb_json_parser_create(upb_env *env,
p->top->m = upb_handlers_msgdef(output->handlers);
set_name_table(p, p->top);
+ p->ignore_json_unknown = ignore_json_unknown;
+
/* If this fails, uncomment and increase the value in parser.h. */
/* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
diff --git a/php/ext/google/protobuf/upb.h b/php/ext/google/protobuf/upb.h
index a263db30..180f4715 100644
--- a/php/ext/google/protobuf/upb.h
+++ b/php/ext/google/protobuf/upb.h
@@ -9457,7 +9457,7 @@ UPB_DECLARE_DERIVED_TYPE(upb::json::ParserMethod, upb::RefCounted,
class upb::json::Parser {
public:
static Parser* Create(Environment* env, const ParserMethod* method,
- Sink* output);
+ Sink* output, bool ignore_json_unknown);
BytesSink* input();
@@ -9491,7 +9491,8 @@ UPB_BEGIN_EXTERN_C
upb_json_parser* upb_json_parser_create(upb_env* e,
const upb_json_parsermethod* m,
- upb_sink* output);
+ upb_sink* output,
+ bool ignore_json_unknown);
upb_bytessink *upb_json_parser_input(upb_json_parser *p);
upb_json_parsermethod* upb_json_parsermethod_new(const upb_msgdef* md,
@@ -9511,8 +9512,8 @@ UPB_END_EXTERN_C
namespace upb {
namespace json {
inline Parser* Parser::Create(Environment* env, const ParserMethod* method,
- Sink* output) {
- return upb_json_parser_create(env, method, output);
+ Sink* output, bool ignore_json_unknown) {
+ return upb_json_parser_create(env, method, output, ignore_json_unknown);
}
inline BytesSink* Parser::input() {
return upb_json_parser_input(this);
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
new file mode 100644
index 00000000..c928fbe5
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto_ExtensionRange.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\DescriptorProto\ExtensionRange instead.
+ * @deprecated
+ */
+ class DescriptorProto_ExtensionRange {}
+}
+class_exists(DescriptorProto\ExtensionRange::class);
+@trigger_error('Google\Protobuf\Internal\DescriptorProto_ExtensionRange is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\DescriptorProto\ExtensionRange instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php b/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
new file mode 100644
index 00000000..e49e945f
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/DescriptorProto_ReservedRange.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\DescriptorProto\ReservedRange instead.
+ * @deprecated
+ */
+ class DescriptorProto_ReservedRange {}
+}
+class_exists(DescriptorProto\ReservedRange::class);
+@trigger_error('Google\Protobuf\Internal\DescriptorProto_ReservedRange is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\DescriptorProto\ReservedRange instead', E_USER_DEPRECATED);
+
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..b1b59ed9
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto_EnumReservedRange.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange instead.
+ * @deprecated
+ */
+ class EnumDescriptorProto_EnumReservedRange {}
+}
+class_exists(EnumDescriptorProto\EnumReservedRange::class);
+@trigger_error('Google\Protobuf\Internal\EnumDescriptorProto_EnumReservedRange is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
new file mode 100644
index 00000000..218a846e
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Label.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\FieldDescriptorProto\Label instead.
+ * @deprecated
+ */
+ class FieldDescriptorProto_Label {}
+}
+class_exists(FieldDescriptorProto\Label::class);
+@trigger_error('Google\Protobuf\Internal\FieldDescriptorProto_Label is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\FieldDescriptorProto\Label instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
new file mode 100644
index 00000000..fd8d449a
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FieldDescriptorProto_Type.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\FieldDescriptorProto\Type instead.
+ * @deprecated
+ */
+ class FieldDescriptorProto_Type {}
+}
+class_exists(FieldDescriptorProto\Type::class);
+@trigger_error('Google\Protobuf\Internal\FieldDescriptorProto_Type is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\FieldDescriptorProto\Type instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_CType.php b/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
new file mode 100644
index 00000000..4d18783e
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FieldOptions_CType.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\FieldOptions\CType instead.
+ * @deprecated
+ */
+ class FieldOptions_CType {}
+}
+class_exists(FieldOptions\CType::class);
+@trigger_error('Google\Protobuf\Internal\FieldOptions_CType is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\FieldOptions\CType instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php b/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
new file mode 100644
index 00000000..9db07822
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FieldOptions_JSType.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\FieldOptions\JSType instead.
+ * @deprecated
+ */
+ class FieldOptions_JSType {}
+}
+class_exists(FieldOptions\JSType::class);
+@trigger_error('Google\Protobuf\Internal\FieldOptions_JSType is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\FieldOptions\JSType instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php b/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
new file mode 100644
index 00000000..8926e63b
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/FileOptions_OptimizeMode.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\FileOptions\OptimizeMode instead.
+ * @deprecated
+ */
+ class FileOptions_OptimizeMode {}
+}
+class_exists(FileOptions\OptimizeMode::class);
+@trigger_error('Google\Protobuf\Internal\FileOptions_OptimizeMode is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\FileOptions\OptimizeMode instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/GPBJsonWire.php b/php/src/Google/Protobuf/Internal/GPBJsonWire.php
index 9ae57ab3..43f4745d 100644
--- a/php/src/Google/Protobuf/Internal/GPBJsonWire.php
+++ b/php/src/Google/Protobuf/Internal/GPBJsonWire.php
@@ -226,7 +226,7 @@ class GPBJsonWire
$output->writeRaw("\"", 1);
break;
case GPBType::STRING:
- $value = json_encode($value);
+ $value = json_encode($value, JSON_UNESCAPED_UNICODE);
$output->writeRaw($value, strlen($value));
break;
// case GPBType::GROUP:
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
new file mode 100644
index 00000000..e36f1e57
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo_Annotation.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\GeneratedCodeInfo\Annotation instead.
+ * @deprecated
+ */
+ class GeneratedCodeInfo_Annotation {}
+}
+class_exists(GeneratedCodeInfo\Annotation::class);
+@trigger_error('Google\Protobuf\Internal\GeneratedCodeInfo_Annotation is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\GeneratedCodeInfo\Annotation instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
index 73ac375e..8ff141ca 100644
--- a/php/src/Google/Protobuf/Internal/Message.php
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -1563,7 +1563,7 @@ class Message
}
break;
case GPBType::STRING:
- $value = json_encode($value);
+ $value = json_encode($value, JSON_UNESCAPED_UNICODE);
$size += strlen($value);
break;
case GPBType::BYTES:
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php b/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
new file mode 100644
index 00000000..a2913114
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/MethodOptions_IdempotencyLevel.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\MethodOptions\IdempotencyLevel instead.
+ * @deprecated
+ */
+ class MethodOptions_IdempotencyLevel {}
+}
+class_exists(MethodOptions\IdempotencyLevel::class);
+@trigger_error('Google\Protobuf\Internal\MethodOptions_IdempotencyLevel is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\MethodOptions\IdempotencyLevel instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
new file mode 100644
index 00000000..1346492d
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo_Location.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\SourceCodeInfo\Location instead.
+ * @deprecated
+ */
+ class SourceCodeInfo_Location {}
+}
+class_exists(SourceCodeInfo\Location::class);
+@trigger_error('Google\Protobuf\Internal\SourceCodeInfo_Location is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\SourceCodeInfo\Location instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php b/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
new file mode 100644
index 00000000..9750eb01
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/UninterpretedOption_NamePart.php
@@ -0,0 +1,16 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+if (false) {
+ /**
+ * This class is deprecated. Use Google\Protobuf\Internal\UninterpretedOption\NamePart instead.
+ * @deprecated
+ */
+ class UninterpretedOption_NamePart {}
+}
+class_exists(UninterpretedOption\NamePart::class);
+@trigger_error('Google\Protobuf\Internal\UninterpretedOption_NamePart is deprecated and will be removed in the next major release. Use Google\Protobuf\Internal\UninterpretedOption\NamePart instead', E_USER_DEPRECATED);
+
diff --git a/php/src/Google/Protobuf/Timestamp.php b/php/src/Google/Protobuf/Timestamp.php
index e21f3231..6d26f6c5 100644
--- a/php/src/Google/Protobuf/Timestamp.php
+++ b/php/src/Google/Protobuf/Timestamp.php
@@ -55,7 +55,9 @@ use Google\Protobuf\Internal\GPBUtil;
* {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.
+ * is required. A proto3 JSON serializer should always use UTC (as indicated by
+ * "Z") when printing the Timestamp type and a proto3 JSON parser should be
+ * able to accept both UTC and other timezones (as indicated by an offset).
* 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
@@ -64,8 +66,8 @@ use Google\Protobuf\Internal\GPBUtil;
* 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.
+ * 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>
*/
@@ -180,18 +182,19 @@ class Timestamp extends \Google\Protobuf\Internal\Message
*/
public function fromDateTime(\DateTime $datetime)
{
- $this->seconds = $datetime->format('U');
- $this->nanos = 0;
+ $this->seconds = $datetime->getTimestamp();
+ $this->nanos = 1000 * $datetime->format('u');
}
/**
- * Converts Timestamp to PHP DateTime. Nano second is ignored.
+ * Converts Timestamp to PHP DateTime.
*
* @return \DateTime $datetime
*/
public function toDateTime()
{
- return \DateTime::createFromFormat('U', $this->seconds);
+ $time = sprintf('%s.%06d', $this->seconds, $this->nanos / 1000);
+ return \DateTime::createFromFormat('U.u', $time);
}
}
diff --git a/php/tests/compatibility_test.sh b/php/tests/compatibility_test.sh
index b377d85c..dc8de5dc 100755
--- a/php/tests/compatibility_test.sh
+++ b/php/tests/compatibility_test.sh
@@ -92,7 +92,7 @@ echo "Running compatibility tests between $VERSION_NUMBER and $OLD_VERSION"
# Download old test.
rm -rf protobuf
-git clone https://github.com/google/protobuf.git
+git clone https://github.com/protocolbuffers/protobuf.git
pushd protobuf
git checkout v$OLD_VERSION
popd
@@ -124,6 +124,7 @@ sed -i.bak '/php_implementation_test.php/d' phpunit.xml
sed -i.bak '/generated_phpdoc_test.php/d' phpunit.xml
sed -i.bak 's/generated_phpdoc_test.php//g' tests/test.sh
sed -i.bak '/memory_leak_test.php/d' tests/test.sh
+sed -i.bak '/^ public function testTimestamp()$/,/^ }$/d' tests/well_known_test.php
for t in "${tests[@]}"
do
remove_error_test tests/$t
diff --git a/php/tests/encode_decode_test.php b/php/tests/encode_decode_test.php
index d36b883e..870dacab 100644
--- a/php/tests/encode_decode_test.php
+++ b/php/tests/encode_decode_test.php
@@ -11,9 +11,90 @@ use Foo\TestMessage\Sub;
use Foo\TestPackedMessage;
use Foo\TestRandomFieldOrder;
use Foo\TestUnpackedMessage;
+use Google\Protobuf\DoubleValue;
+use Google\Protobuf\FloatValue;
+use Google\Protobuf\Int32Value;
+use Google\Protobuf\UInt32Value;
+use Google\Protobuf\Int64Value;
+use Google\Protobuf\UInt64Value;
+use Google\Protobuf\BoolValue;
+use Google\Protobuf\StringValue;
+use Google\Protobuf\BytesValue;
class EncodeDecodeTest extends TestBase
{
+ public function testDecodeJsonSimple()
+ {
+ $m = new TestMessage();
+ $m->mergeFromJsonString("{\"optionalInt32\":1}");
+ }
+
+ public function testDecodeTopLevelBoolValue()
+ {
+ $m = new BoolValue();
+
+ $m->mergeFromJsonString("true");
+ $this->assertEquals(true, $m->getValue());
+
+ $m->mergeFromJsonString("false");
+ $this->assertEquals(false, $m->getValue());
+ }
+
+ public function testDecodeTopLevelDoubleValue()
+ {
+ $m = new DoubleValue();
+ $m->mergeFromJsonString("1.5");
+ $this->assertEquals(1.5, $m->getValue());
+ }
+
+ public function testDecodeTopLevelFloatValue()
+ {
+ $m = new FloatValue();
+ $m->mergeFromJsonString("1.5");
+ $this->assertEquals(1.5, $m->getValue());
+ }
+
+ public function testDecodeTopLevelInt32Value()
+ {
+ $m = new Int32Value();
+ $m->mergeFromJsonString("1");
+ $this->assertEquals(1, $m->getValue());
+ }
+
+ public function testDecodeTopLevelUInt32Value()
+ {
+ $m = new UInt32Value();
+ $m->mergeFromJsonString("1");
+ $this->assertEquals(1, $m->getValue());
+ }
+
+ public function testDecodeTopLevelInt64Value()
+ {
+ $m = new Int64Value();
+ $m->mergeFromJsonString("1");
+ $this->assertEquals(1, $m->getValue());
+ }
+
+ public function testDecodeTopLevelUInt64Value()
+ {
+ $m = new UInt64Value();
+ $m->mergeFromJsonString("1");
+ $this->assertEquals(1, $m->getValue());
+ }
+
+ public function testDecodeTopLevelStringValue()
+ {
+ $m = new StringValue();
+ $m->mergeFromJsonString("\"a\"");
+ $this->assertSame("a", $m->getValue());
+ }
+
+ public function testDecodeTopLevelBytesValue()
+ {
+ $m = new BytesValue();
+ $m->mergeFromJsonString("\"YQ==\"");
+ $this->assertSame("a", $m->getValue());
+ }
public function testEncode()
{
diff --git a/php/tests/memory_leak_test.php b/php/tests/memory_leak_test.php
index 4e3874b7..f3bcb963 100644
--- a/php/tests/memory_leak_test.php
+++ b/php/tests/memory_leak_test.php
@@ -152,7 +152,7 @@ date_default_timezone_set('UTC');
$from = new DateTime('2011-01-01T15:03:01.012345UTC');
$timestamp->fromDateTime($from);
assert($from->format('U') == $timestamp->getSeconds());
-assert(0 == $timestamp->getNanos());
+assert(1000 * $from->format('u') == $timestamp->getNanos());
$to = $timestamp->toDateTime();
assert(\DateTime::class == get_class($to));
diff --git a/php/tests/undefined_test.php b/php/tests/undefined_test.php
index f8444571..935d8be7 100644
--- a/php/tests/undefined_test.php
+++ b/php/tests/undefined_test.php
@@ -909,7 +909,7 @@ class UndefinedTest extends PHPUnit_Framework_TestCase
/**
* @expectedException PHPUnit_Framework_Error
*/
- public function testMessageSetNullFail()
+ public function testMessageSetNullFailMap()
{
$arr =
new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
diff --git a/php/tests/well_known_test.php b/php/tests/well_known_test.php
index 1e8c4f42..6a788df2 100644
--- a/php/tests/well_known_test.php
+++ b/php/tests/well_known_test.php
@@ -42,6 +42,7 @@ class WellKnownTest extends TestBase {
public function testEmpty()
{
$msg = new GPBEmpty();
+ $this->assertTrue($msg instanceof \Google\Protobuf\Internal\Message);
}
public function testImportDescriptorProto()
@@ -312,11 +313,12 @@ class WellKnownTest extends TestBase {
$from = new DateTime('2011-01-01T15:03:01.012345UTC');
$timestamp->fromDateTime($from);
$this->assertEquals($from->format('U'), $timestamp->getSeconds());
- $this->assertSame(0, $timestamp->getNanos());
+ $this->assertEquals(1000 * $from->format('u'), $timestamp->getNanos());
$to = $timestamp->toDateTime();
$this->assertSame(\DateTime::class, get_class($to));
$this->assertSame($from->format('U'), $to->format('U'));
+ $this->assertSame($from->format('u'), $to->format('u'));
}
public function testType()
diff --git a/protobuf.bzl b/protobuf.bzl
index 78f19c62..ae391aa6 100644
--- a/protobuf.bzl
+++ b/protobuf.bzl
@@ -1,3 +1,5 @@
+load("@bazel_skylib//:lib.bzl", "versions")
+
def _GetPath(ctx, path):
if ctx.label.workspace_root:
return ctx.label.workspace_root + '/' + path
@@ -72,7 +74,7 @@ def _proto_gen_impl(ctx):
deps = []
deps += ctx.files.srcs
source_dir = _SourceDir(ctx)
- gen_dir = _GenDir(ctx)
+ gen_dir = _GenDir(ctx).rstrip('/')
if source_dir:
import_flags = ["-I" + source_dir, "-I" + gen_dir]
else:
@@ -82,37 +84,83 @@ def _proto_gen_impl(ctx):
import_flags += dep.proto.import_flags
deps += dep.proto.deps
- args = []
- if ctx.attr.gen_cc:
- args += ["--cpp_out=" + gen_dir]
- if ctx.attr.gen_py:
- args += ["--python_out=" + gen_dir]
-
- inputs = srcs + deps
- if ctx.executable.plugin:
- plugin = ctx.executable.plugin
- lang = ctx.attr.plugin_language
- if not lang and plugin.basename.startswith('protoc-gen-'):
- lang = plugin.basename[len('protoc-gen-'):]
- if not lang:
- fail("cannot infer the target language of plugin", "plugin_language")
-
- outdir = gen_dir
- if ctx.attr.plugin_options:
- outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir
- args += ["--plugin=protoc-gen-%s=%s" % (lang, plugin.path)]
- args += ["--%s_out=%s" % (lang, outdir)]
- inputs += [plugin]
-
- if args:
- ctx.action(
- inputs=inputs,
- outputs=ctx.outputs.outs,
- arguments=args + import_flags + [s.path for s in srcs],
- executable=ctx.executable.protoc,
- mnemonic="ProtoCompile",
- use_default_shell_env=True,
- )
+ if not ctx.attr.gen_cc and not ctx.attr.gen_py and not ctx.executable.plugin:
+ return struct(
+ proto=struct(
+ srcs=srcs,
+ import_flags=import_flags,
+ deps=deps,
+ ),
+ )
+
+ for src in srcs:
+ args = []
+
+ in_gen_dir = src.root.path == gen_dir
+ if in_gen_dir:
+ import_flags_real = []
+ for f in depset(import_flags):
+ path = f.replace('-I', '')
+ import_flags_real.append('-I$(realpath -s %s)' % path)
+
+ outs = []
+ use_grpc_plugin = (ctx.attr.plugin_language == "grpc" and ctx.attr.plugin)
+ path_tpl = "$(realpath %s)" if in_gen_dir else "%s"
+ if ctx.attr.gen_cc:
+ args += [("--cpp_out=" + path_tpl) % gen_dir]
+ outs.extend(_CcOuts([src.basename], use_grpc_plugin=use_grpc_plugin))
+ if ctx.attr.gen_py:
+ args += [("--python_out=" + path_tpl) % gen_dir]
+ outs.extend(_PyOuts([src.basename], use_grpc_plugin=use_grpc_plugin))
+
+ outs = [ctx.actions.declare_file(out, sibling=src) for out in outs]
+ inputs = [src] + deps
+ if ctx.executable.plugin:
+ plugin = ctx.executable.plugin
+ lang = ctx.attr.plugin_language
+ if not lang and plugin.basename.startswith('protoc-gen-'):
+ lang = plugin.basename[len('protoc-gen-'):]
+ if not lang:
+ fail("cannot infer the target language of plugin", "plugin_language")
+
+ outdir = "." if in_gen_dir else gen_dir
+
+ if ctx.attr.plugin_options:
+ outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir
+ args += [("--plugin=protoc-gen-%s=" + path_tpl) % (lang, plugin.path)]
+ args += ["--%s_out=%s" % (lang, outdir)]
+ inputs += [plugin]
+
+ if not in_gen_dir:
+ ctx.action(
+ inputs=inputs,
+ outputs=outs,
+ arguments=args + import_flags + [src.path],
+ executable=ctx.executable.protoc,
+ mnemonic="ProtoCompile",
+ use_default_shell_env=True,
+ )
+ else:
+ for out in outs:
+ orig_command = " ".join(
+ ["$(realpath %s)" % ctx.executable.protoc.path] + args +
+ import_flags_real + ["-I.", src.basename])
+ command = ";".join([
+ 'CMD="%s"' % orig_command,
+ "cd %s" % src.dirname,
+ "${CMD}",
+ "cd -",
+ ])
+ generated_out = '/'.join([gen_dir, out.basename])
+ if generated_out != out.path:
+ command += ";mv %s %s" % (generated_out, out.path)
+ ctx.action(
+ inputs=inputs + [ctx.executable.protoc],
+ outputs=[out],
+ command=command,
+ mnemonic="ProtoCompile",
+ use_default_shell_env=True,
+ )
return struct(
proto=struct(
@@ -130,7 +178,7 @@ proto_gen = rule(
"protoc": attr.label(
cfg = "host",
executable = True,
- single_file = True,
+ allow_single_file = True,
mandatory = True,
),
"plugin": attr.label(
@@ -266,8 +314,8 @@ def internal_gen_well_known_protos_java(srcs):
Args:
srcs: the well known protos
"""
- root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root
- pkg = PACKAGE_NAME + "/" if PACKAGE_NAME else ""
+ root = Label("%s//protobuf_java" % (native.repository_name())).workspace_root
+ pkg = native.package_name() + "/" if native.package_name() else ""
if root == "":
include = " -I%ssrc " % pkg
else:
@@ -411,7 +459,4 @@ def check_protobuf_required_bazel_version():
This ensures bazel supports our approach to proto_library() depending on a
copied filegroup. (Fixed in bazel 0.5.4)
"""
- expected = apple_common.dotted_version("0.5.4")
- current = apple_common.dotted_version(native.bazel_version)
- if current.compare_to(expected) < 0:
- fail("Bazel must be newer than 0.5.4")
+ versions.check(minimum_bazel_version = "0.5.4")
diff --git a/protoc-artifacts/README.md b/protoc-artifacts/README.md
index 9b148891..d60defb8 100644
--- a/protoc-artifacts/README.md
+++ b/protoc-artifacts/README.md
@@ -90,7 +90,7 @@ To checkout protobuf (run within the container):
```
$ # Replace v3.5.1 with the version you want
-$ wget -O - https://github.com/google/protobuf/archive/v3.5.1.tar.gz | tar xvzp
+$ wget -O - https://github.com/protocolbuffers/protobuf/archive/v3.5.1.tar.gz | tar xvzp
```
### Windows build
@@ -119,7 +119,9 @@ target directory layout:
protoc.exe
+ x86_32
protoc.exe
- + macos
+ + aarch_64
+ protoc.exe
+ + osx
+ x86_64
protoc.exe
+ x86_32
@@ -137,7 +139,7 @@ Use the following command to deploy artifacts for the host platform to a
staging repository.
```
-$ mvn clean deploy -P release
+$ mvn deploy -P release
```
It creates a new staging repository. Go to
@@ -152,10 +154,10 @@ and upload these zip packages to the download section of the github
release. For example:
```
-$ ./build-zip.sh 3.6.0
+$ ./build-zip.sh protoc 3.6.0
```
-The above command will create 5 zip files:
+The above command will create 7 zip files:
```
dist/protoc-3.6.0-win32.zip
@@ -163,6 +165,7 @@ dist/protoc-3.6.0-osx-x86_32.zip
dist/protoc-3.6.0-osx-x86_64.zip
dist/protoc-3.6.0-linux-x86_32.zip
dist/protoc-3.6.0-linux-x86_64.zip
+dist/protoc-3.6.0-linux-aarch_64.zip
dist/protoc-3.6.0-linux-ppcle_64.zip
```
diff --git a/protoc-artifacts/build-zip.sh b/protoc-artifacts/build-zip.sh
index 26b6cc93..1f0186f8 100755
--- a/protoc-artifacts/build-zip.sh
+++ b/protoc-artifacts/build-zip.sh
@@ -82,7 +82,7 @@ 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
+ https://github.com/protocolbuffers/protobuf
EOF
mkdir -p dist
diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml
index 55d9e91a..3f858908 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -27,9 +27,9 @@
</license>
</licenses>
<scm>
- <url>https://github.com/google/protobuf</url>
+ <url>https://github.com/protocolbuffers/protobuf</url>
<connection>
- scm:git:https://github.com/google/protobuf.git
+ scm:git:https://github.com/protocolbuffers/protobuf.git
</connection>
</scm>
<build>
diff --git a/python/README.md b/python/README.md
index 4c194297..3eb78e56 100644
--- a/python/README.md
+++ b/python/README.md
@@ -1,7 +1,7 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf)
+[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_compatibility.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_compatibility%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fpython_cpp%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-python_cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fpython_cpp%2Fcontinuous)
Copyright 2008 Google Inc.
@@ -30,7 +30,7 @@ join the Protocol Buffers discussion list and let us know!
Installation
============
-1) Make sure you have Python 2.6 or newer. If in doubt, run:
+1) Make sure you have Python 2.7 or newer. If in doubt, run:
$ python -V
diff --git a/python/compatibility_tests/v2.5.0/setup.py b/python/compatibility_tests/v2.5.0/setup.py
index b41d54d4..bf675367 100755
--- a/python/compatibility_tests/v2.5.0/setup.py
+++ b/python/compatibility_tests/v2.5.0/setup.py
@@ -59,7 +59,7 @@ if __name__ == '__main__':
setup(
name='protobuf',
description='Protocol Buffers',
- download_url='https://github.com/google/protobuf/releases',
+ download_url='https://github.com/protocolbuffers/protobuf/releases',
long_description="Protocol Buffers are Google's data interchange format",
url='https://developers.google.com/protocol-buffers/',
maintainer='protobuf@googlegroups.com',
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
index 8267cd2c..bc53e256 100755
--- 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
@@ -410,7 +410,8 @@ class TextFormatTest(unittest.TestCase):
text = 'optional_nested_enum: BARR'
self.assertRaisesWithMessage(
text_format.ParseError,
- ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
+ ('1:23 : \'optional_nested_enum: BARR\': '
+ 'Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
'has no value named BARR.'),
text_format.Merge, text, message)
@@ -418,7 +419,8 @@ class TextFormatTest(unittest.TestCase):
text = 'optional_nested_enum: 100'
self.assertRaisesWithMessage(
text_format.ParseError,
- ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
+ ('1:23 : \'optional_nested_enum: 100\': '
+ 'Enum type "protobuf_unittest.TestAllTypes.NestedEnum" '
'has no value with number 100.'),
text_format.Merge, text, message)
@@ -427,7 +429,8 @@ class TextFormatTest(unittest.TestCase):
text = 'optional_int32: bork'
self.assertRaisesWithMessage(
text_format.ParseError,
- ('1:17 : Couldn\'t parse integer: bork'),
+ ('1:17 : \'optional_int32: bork\': '
+ 'Couldn\'t parse integer: bork'),
text_format.Merge, text, message)
def testMergeStringFieldUnescape(self):
diff --git a/python/google/protobuf/descriptor_database.py b/python/google/protobuf/descriptor_database.py
index 8b7715cd..5453f50c 100644
--- a/python/google/protobuf/descriptor_database.py
+++ b/python/google/protobuf/descriptor_database.py
@@ -76,6 +76,9 @@ class DescriptorDatabase(object):
self._AddSymbol(name, file_desc_proto)
for enum in file_desc_proto.enum_type:
self._AddSymbol(('.'.join((package, enum.name))), file_desc_proto)
+ for enum_value in enum.value:
+ self._file_desc_protos_by_symbol[
+ '.'.join((package, enum_value.name))] = file_desc_proto
for extension in file_desc_proto.extension:
self._AddSymbol(('.'.join((package, extension.name))), file_desc_proto)
for service in file_desc_proto.service:
@@ -131,7 +134,19 @@ class DescriptorDatabase(object):
# 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]
+ try:
+ return self._file_desc_protos_by_symbol[top_level]
+ except KeyError:
+ # Raise the original symbol as a KeyError for better diagnostics.
+ raise KeyError(symbol)
+
+ def FindFileContainingExtension(self, extendee_name, extension_number):
+ # TODO(jieluo): implement this API.
+ return None
+
+ def FindAllExtensionNumbers(self, extendee_name):
+ # TODO(jieluo): implement this API.
+ return []
def _AddSymbol(self, name, file_desc_proto):
if name in self._file_desc_protos_by_symbol:
diff --git a/python/google/protobuf/descriptor_pool.py b/python/google/protobuf/descriptor_pool.py
index 8983f76f..42f7bcb5 100644
--- a/python/google/protobuf/descriptor_pool.py
+++ b/python/google/protobuf/descriptor_pool.py
@@ -131,33 +131,46 @@ class DescriptorPool(object):
# TODO(jieluo): Remove _file_desc_by_toplevel_extension after
# maybe year 2020 for compatibility issue (with 3.4.1 only).
self._file_desc_by_toplevel_extension = {}
+ self._top_enum_values = {}
# We store extensions in two two-level mappings: The first key is the
# descriptor of the message being extended, the second key is the extension
# full name or its tag number.
self._extensions_by_name = collections.defaultdict(dict)
self._extensions_by_number = collections.defaultdict(dict)
- def _CheckConflictRegister(self, desc):
+ def _CheckConflictRegister(self, desc, desc_name, file_name):
"""Check if the descriptor name conflicts with another of the same name.
Args:
- desc: Descriptor of a message, enum, service or extension.
+ desc: Descriptor of a message, enum, service, extension or enum value.
+ desc_name: the full name of desc.
+ file_name: The file name of descriptor.
"""
- desc_name = desc.full_name
for register, descriptor_type in [
(self._descriptors, descriptor.Descriptor),
(self._enum_descriptors, descriptor.EnumDescriptor),
(self._service_descriptors, descriptor.ServiceDescriptor),
- (self._toplevel_extensions, descriptor.FieldDescriptor)]:
+ (self._toplevel_extensions, descriptor.FieldDescriptor),
+ (self._top_enum_values, descriptor.EnumValueDescriptor)]:
if desc_name in register:
- file_name = register[desc_name].file.name
+ old_desc = register[desc_name]
+ if isinstance(old_desc, descriptor.EnumValueDescriptor):
+ old_file = old_desc.type.file.name
+ else:
+ old_file = old_desc.file.name
+
if not isinstance(desc, descriptor_type) or (
- file_name != desc.file.name):
- warn_msg = ('Conflict register for file "' + desc.file.name +
+ old_file != file_name):
+ warn_msg = ('Conflict register for file "' + file_name +
'": ' + desc_name +
' is already defined in file "' +
- file_name + '"')
+ old_file + '"')
+ if isinstance(desc, descriptor.EnumValueDescriptor):
+ warn_msg += ('\nNote: enum values appear as '
+ 'siblings of the enum type instead of '
+ 'children of it.')
warnings.warn(warn_msg, RuntimeWarning)
+
return
def Add(self, file_desc_proto):
@@ -196,7 +209,7 @@ class DescriptorPool(object):
if not isinstance(desc, descriptor.Descriptor):
raise TypeError('Expected instance of descriptor.Descriptor.')
- self._CheckConflictRegister(desc)
+ self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._descriptors[desc.full_name] = desc
self._AddFileDescriptor(desc.file)
@@ -213,8 +226,26 @@ class DescriptorPool(object):
if not isinstance(enum_desc, descriptor.EnumDescriptor):
raise TypeError('Expected instance of descriptor.EnumDescriptor.')
- self._CheckConflictRegister(enum_desc)
+ file_name = enum_desc.file.name
+ self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name)
self._enum_descriptors[enum_desc.full_name] = enum_desc
+
+ # Top enum values need to be indexed.
+ # Count the number of dots to see whether the enum is toplevel or nested
+ # in a message. We cannot use enum_desc.containing_type at this stage.
+ if enum_desc.file.package:
+ top_level = (enum_desc.full_name.count('.')
+ - enum_desc.file.package.count('.') == 1)
+ else:
+ top_level = enum_desc.full_name.count('.') == 0
+ if top_level:
+ file_name = enum_desc.file.name
+ package = enum_desc.file.package
+ for enum_value in enum_desc.values:
+ full_name = _NormalizeFullyQualifiedName(
+ '.'.join((package, enum_value.name)))
+ self._CheckConflictRegister(enum_value, full_name, file_name)
+ self._top_enum_values[full_name] = enum_value
self._AddFileDescriptor(enum_desc.file)
def AddServiceDescriptor(self, service_desc):
@@ -227,7 +258,8 @@ class DescriptorPool(object):
if not isinstance(service_desc, descriptor.ServiceDescriptor):
raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
- self._CheckConflictRegister(service_desc)
+ self._CheckConflictRegister(service_desc, service_desc.full_name,
+ service_desc.file.name)
self._service_descriptors[service_desc.full_name] = service_desc
def AddExtensionDescriptor(self, extension):
@@ -247,7 +279,6 @@ class DescriptorPool(object):
raise TypeError('Expected an extension descriptor.')
if extension.extension_scope is None:
- self._CheckConflictRegister(extension)
self._toplevel_extensions[extension.full_name] = extension
try:
@@ -349,6 +380,30 @@ class DescriptorPool(object):
symbol = _NormalizeFullyQualifiedName(symbol)
try:
+ return self._InternalFindFileContainingSymbol(symbol)
+ except KeyError:
+ pass
+
+ try:
+ # Try fallback database. Build and find again if possible.
+ self._FindFileContainingSymbolInDb(symbol)
+ return self._InternalFindFileContainingSymbol(symbol)
+ except KeyError:
+ raise KeyError('Cannot find a file containing %s' % symbol)
+
+ def _InternalFindFileContainingSymbol(self, symbol):
+ """Gets the already built FileDescriptor 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 pool.
+ """
+ try:
return self._descriptors[symbol].file
except KeyError:
pass
@@ -364,7 +419,7 @@ class DescriptorPool(object):
pass
try:
- return self._FindFileContainingSymbolInDb(symbol)
+ return self._top_enum_values[symbol].type.file
except KeyError:
pass
@@ -373,13 +428,15 @@ class DescriptorPool(object):
except KeyError:
pass
- # Try nested extensions inside a message.
- message_name, _, extension_name = symbol.rpartition('.')
+ # Try fields, enum values and nested extensions inside a message.
+ top_name, _, sub_name = symbol.rpartition('.')
try:
- message = self.FindMessageTypeByName(message_name)
- assert message.extensions_by_name[extension_name]
+ message = self.FindMessageTypeByName(top_name)
+ assert (sub_name in message.extensions_by_name or
+ sub_name in message.fields_by_name or
+ sub_name in message.enum_values_by_name)
return message.file
- except KeyError:
+ except (KeyError, AssertionError):
raise KeyError('Cannot find a file containing %s' % symbol)
def FindMessageTypeByName(self, full_name):
@@ -499,7 +556,11 @@ class DescriptorPool(object):
KeyError: when no extension with the given number is known for the
specified message.
"""
- return self._extensions_by_number[message_descriptor][number]
+ try:
+ return self._extensions_by_number[message_descriptor][number]
+ except KeyError:
+ self._TryLoadExtensionFromDB(message_descriptor, number)
+ return self._extensions_by_number[message_descriptor][number]
def FindAllExtensions(self, message_descriptor):
"""Gets all the known extension of a given message.
@@ -513,8 +574,57 @@ class DescriptorPool(object):
Returns:
A list of FieldDescriptor describing the extensions.
"""
+ # Fallback to descriptor db if FindAllExtensionNumbers is provided.
+ if self._descriptor_db and hasattr(
+ self._descriptor_db, 'FindAllExtensionNumbers'):
+ full_name = message_descriptor.full_name
+ all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name)
+ for number in all_numbers:
+ if number in self._extensions_by_number[message_descriptor]:
+ continue
+ self._TryLoadExtensionFromDB(message_descriptor, number)
+
return list(self._extensions_by_number[message_descriptor].values())
+ def _TryLoadExtensionFromDB(self, message_descriptor, number):
+ """Try to Load extensions from decriptor db.
+
+ Args:
+ message_descriptor: descriptor of the extended message.
+ number: the extension number that needs to be loaded.
+ """
+ if not self._descriptor_db:
+ return
+ # Only supported when FindFileContainingExtension is provided.
+ if not hasattr(
+ self._descriptor_db, 'FindFileContainingExtension'):
+ return
+
+ full_name = message_descriptor.full_name
+ file_proto = self._descriptor_db.FindFileContainingExtension(
+ full_name, number)
+
+ if file_proto is None:
+ return
+
+ try:
+ file_desc = self._ConvertFileProtoToFileDescriptor(file_proto)
+ for extension in file_desc.extensions_by_name.values():
+ self._extensions_by_number[extension.containing_type][
+ extension.number] = extension
+ self._extensions_by_name[extension.containing_type][
+ extension.full_name] = extension
+ for message_type in file_desc.message_types_by_name.values():
+ for extension in message_type.extensions:
+ self._extensions_by_number[extension.containing_type][
+ extension.number] = extension
+ self._extensions_by_name[extension.containing_type][
+ extension.full_name] = extension
+ except:
+ warn_msg = ('Unable to load proto file %s for extension number %d.' %
+ (file_proto.name, number))
+ warnings.warn(warn_msg, RuntimeWarning)
+
def FindServiceByName(self, full_name):
"""Loads the named service descriptor from the pool.
@@ -532,6 +642,23 @@ class DescriptorPool(object):
self._FindFileContainingSymbolInDb(full_name)
return self._service_descriptors[full_name]
+ def FindMethodByName(self, full_name):
+ """Loads the named service method descriptor from the pool.
+
+ Args:
+ full_name: The full name of the method descriptor to load.
+
+ Returns:
+ The method descriptor for the service method.
+
+ Raises:
+ KeyError: if the method cannot be found in the pool.
+ """
+ full_name = _NormalizeFullyQualifiedName(full_name)
+ service_name, _, method_name = full_name.rpartition('.')
+ service_descriptor = self.FindServiceByName(service_name)
+ return service_descriptor.methods_by_name[method_name]
+
def _FindFileContainingSymbolInDb(self, symbol):
"""Finds the file in descriptor DB containing the specified symbol.
@@ -567,7 +694,6 @@ class DescriptorPool(object):
Returns:
A FileDescriptor matching the passed in proto.
"""
-
if file_proto.name not in self._file_descriptors:
built_deps = list(self._GetDeps(file_proto.dependency))
direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
@@ -604,7 +730,7 @@ class DescriptorPool(object):
for enum_type in file_proto.enum_type:
file_descriptor.enum_types_by_name[enum_type.name] = (
self._ConvertEnumDescriptor(enum_type, file_proto.package,
- file_descriptor, None, scope))
+ file_descriptor, None, scope, True))
for index, extension_proto in enumerate(file_proto.extension):
extension_desc = self._MakeFieldDescriptor(
@@ -616,6 +742,8 @@ class DescriptorPool(object):
file_descriptor.package, scope)
file_descriptor.extensions_by_name[extension_desc.name] = (
extension_desc)
+ self._file_desc_by_toplevel_extension[extension_desc.full_name] = (
+ file_descriptor)
for desc_proto in file_proto.message_type:
self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
@@ -673,7 +801,8 @@ class DescriptorPool(object):
nested, desc_name, file_desc, scope, syntax)
for nested in desc_proto.nested_type]
enums = [
- self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)
+ self._ConvertEnumDescriptor(enum, desc_name, file_desc, None,
+ scope, False)
for enum in desc_proto.enum_type]
fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc)
for index, field in enumerate(desc_proto.field)]
@@ -718,12 +847,12 @@ class DescriptorPool(object):
fields[field_index].containing_oneof = oneofs[oneof_index]
scope[_PrefixWithDot(desc_name)] = desc
- self._CheckConflictRegister(desc)
+ self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._descriptors[desc_name] = desc
return desc
def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
- containing_type=None, scope=None):
+ containing_type=None, scope=None, top_level=False):
"""Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
Args:
@@ -732,6 +861,8 @@ class DescriptorPool(object):
file_desc: The file containing the enum descriptor.
containing_type: The type containing this enum.
scope: Scope containing available types.
+ top_level: If True, the enum is a top level symbol. If False, the enum
+ is defined inside a message.
Returns:
The added descriptor
@@ -757,8 +888,17 @@ class DescriptorPool(object):
containing_type=containing_type,
options=_OptionsOrNone(enum_proto))
scope['.%s' % enum_name] = desc
- self._CheckConflictRegister(desc)
+ self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._enum_descriptors[enum_name] = desc
+
+ # Add top level enum values.
+ if top_level:
+ for value in values:
+ full_name = _NormalizeFullyQualifiedName(
+ '.'.join((package, value.name)))
+ self._CheckConflictRegister(value, full_name, file_name)
+ self._top_enum_values[full_name] = value
+
return desc
def _MakeFieldDescriptor(self, field_proto, message_name, index,
@@ -885,6 +1025,8 @@ class DescriptorPool(object):
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = text_encoding.CUnescape(
field_proto.default_value)
+ elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
+ field_desc.default_value = None
else:
# All other types are of the "int" type.
field_desc.default_value = int(field_proto.default_value)
@@ -901,6 +1043,8 @@ class DescriptorPool(object):
field_desc.default_value = field_desc.enum_type.values[0].number
elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
field_desc.default_value = b''
+ elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
+ field_desc.default_value = None
else:
# All other types are of the "int" type.
field_desc.default_value = 0
@@ -954,7 +1098,7 @@ class DescriptorPool(object):
methods=methods,
options=_OptionsOrNone(service_proto),
file=file_desc)
- self._CheckConflictRegister(desc)
+ self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
self._service_descriptors[service_name] = desc
return desc
diff --git a/python/google/protobuf/internal/__init__.py b/python/google/protobuf/internal/__init__.py
index e69de29b..7d2e571a 100755
--- a/python/google/protobuf/internal/__init__.py
+++ b/python/google/protobuf/internal/__init__.py
@@ -0,0 +1,30 @@
+# 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.
+
diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py
index ab9e7812..23cc2c0a 100755
--- a/python/google/protobuf/internal/api_implementation.py
+++ b/python/google/protobuf/internal/api_implementation.py
@@ -145,29 +145,3 @@ def 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 c6a3692a..182cac99 100755
--- a/python/google/protobuf/internal/containers.py
+++ b/python/google/protobuf/internal/containers.py
@@ -628,3 +628,130 @@ class MessageMap(MutableMapping):
def GetEntryClass(self):
return self._entry_descriptor._concrete_class
+
+
+class _UnknownField(object):
+
+ """A parsed unknown field."""
+
+ # Disallows assignment to other attributes.
+ __slots__ = ['_field_number', '_wire_type', '_data']
+
+ def __init__(self, field_number, wire_type, data):
+ self._field_number = field_number
+ self._wire_type = wire_type
+ self._data = data
+ return
+
+ def __lt__(self, other):
+ # pylint: disable=protected-access
+ return self._field_number < other._field_number
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ # pylint: disable=protected-access
+ return (self._field_number == other._field_number and
+ self._wire_type == other._wire_type and
+ self._data == other._data)
+
+
+class UnknownFieldRef(object):
+
+ def __init__(self, parent, index):
+ self._parent = parent
+ self._index = index
+ return
+
+ def _check_valid(self):
+ if not self._parent:
+ raise ValueError('UnknownField does not exist. '
+ 'The parent message might be cleared.')
+ if self._index >= len(self._parent):
+ raise ValueError('UnknownField does not exist. '
+ 'The parent message might be cleared.')
+
+ @property
+ def field_number(self):
+ self._check_valid()
+ # pylint: disable=protected-access
+ return self._parent._internal_get(self._index)._field_number
+
+ @property
+ def wire_type(self):
+ self._check_valid()
+ # pylint: disable=protected-access
+ return self._parent._internal_get(self._index)._wire_type
+
+ @property
+ def data(self):
+ self._check_valid()
+ # pylint: disable=protected-access
+ return self._parent._internal_get(self._index)._data
+
+
+class UnknownFieldSet(object):
+
+ """UnknownField container"""
+
+ # Disallows assignment to other attributes.
+ __slots__ = ['_values']
+
+ def __init__(self):
+ self._values = []
+
+ def __getitem__(self, index):
+ if self._values is None:
+ raise ValueError('UnknownFields does not exist. '
+ 'The parent message might be cleared.')
+ size = len(self._values)
+ if index < 0:
+ index += size
+ if index < 0 or index >= size:
+ raise IndexError('index %d out of range'.index)
+
+ return UnknownFieldRef(self, index)
+
+ def _internal_get(self, index):
+ return self._values[index]
+
+ def __len__(self):
+ if self._values is None:
+ raise ValueError('UnknownFields does not exist. '
+ 'The parent message might be cleared.')
+ return len(self._values)
+
+ def _add(self, field_number, wire_type, data):
+ unknown_field = _UnknownField(field_number, wire_type, data)
+ self._values.append(unknown_field)
+ return unknown_field
+
+ def __iter__(self):
+ for i in range(len(self)):
+ yield UnknownFieldRef(self, i)
+
+ def _extend(self, other):
+ if other is None:
+ return
+ # pylint: disable=protected-access
+ self._values.extend(other._values)
+
+ def __eq__(self, other):
+ if self is other:
+ return True
+ # Sort unknown fields because their order shouldn't
+ # affect equality test.
+ values = list(self._values)
+ if other is None:
+ return not values
+ values.sort()
+ # pylint: disable=protected-access
+ other_values = sorted(other._values)
+ return values == other_values
+
+ def _clear(self):
+ for value in self._values:
+ # pylint: disable=protected-access
+ if isinstance(value._data, UnknownFieldSet):
+ value._data._clear() # pylint: disable=protected-access
+ self._values = None
diff --git a/python/google/protobuf/internal/decoder.py b/python/google/protobuf/internal/decoder.py
index 52b64915..5a540184 100755
--- a/python/google/protobuf/internal/decoder.py
+++ b/python/google/protobuf/internal/decoder.py
@@ -81,12 +81,17 @@ we repeatedly read a tag, look up the corresponding decoder, and invoke it.
__author__ = 'kenton@google.com (Kenton Varda)'
import struct
-
+import sys
import six
+_UCS2_MAXUNICODE = 65535
if six.PY3:
long = int
+else:
+ import re # pylint: disable=g-import-not-at-top
+ _SURROGATE_PATTERN = re.compile(six.u(r'[\ud800-\udfff]'))
+from google.protobuf.internal import containers
from google.protobuf.internal import encoder
from google.protobuf.internal import wire_format
from google.protobuf import message
@@ -167,7 +172,7 @@ _DecodeSignedVarint32 = _SignedVarintDecoder(32, int)
def ReadTag(buffer, pos):
- """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
+ """Read a tag from the memoryview, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
@@ -175,13 +180,21 @@ def ReadTag(buffer, pos):
for work that is done in C (searching for a byte string in a hash table).
In a low-level language it would be much cheaper to decode the varint and
use that, but not in Python.
- """
+ Args:
+ buffer: memoryview object of the encoded bytes
+ pos: int of the current position to start from
+
+ Returns:
+ Tuple[bytes, int] of the tag data and new position.
+ """
start = pos
while six.indexbytes(buffer, pos) & 0x80:
pos += 1
pos += 1
- return (six.binary_type(buffer[start:pos]), pos)
+
+ tag_bytes = buffer[start:pos].tobytes()
+ return tag_bytes, pos
# --------------------------------------------------------------------
@@ -295,10 +308,20 @@ def _FloatDecoder():
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
+ """Decode serialized float to a float and new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes
+ pos: int, position in the memory view to start at.
+
+ Returns:
+ Tuple[float, int] of the deserialized float value and new position
+ in the serialized data.
+ """
# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-9 represent the exponent, and bits 10-32 are the significand.
new_pos = pos + 4
- float_bytes = buffer[pos:new_pos]
+ float_bytes = buffer[pos:new_pos].tobytes()
# If this value has all its exponent bits set, then it's non-finite.
# In Python 2.4, struct.unpack will convert it to a finite 64-bit value.
@@ -329,10 +352,20 @@ def _DoubleDecoder():
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
+ """Decode serialized double to a double and new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes.
+ pos: int, position in the memory view to start at.
+
+ Returns:
+ Tuple[float, int] of the decoded double value and new position
+ in the serialized data.
+ """
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exponent, and bits 13-64 are the significand.
new_pos = pos + 8
- double_bytes = buffer[pos:new_pos]
+ double_bytes = buffer[pos:new_pos].tobytes()
# If this value has all its exponent bits set and at least one significand
# bit set, it's not a number. In Python 2.4, struct.unpack will treat it
@@ -355,6 +388,18 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
if is_packed:
local_DecodeVarint = _DecodeVarint
def DecodePackedField(buffer, pos, end, message, field_dict):
+ """Decode serialized packed enum to its value and a new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes.
+ pos: int, position in the memory view to start at.
+ end: int, end position of serialized data
+ message: Message object to store unknown fields in
+ field_dict: Map[Descriptor, Any] to store decoded values in.
+
+ Returns:
+ int, new position in serialized data.
+ """
value = field_dict.get(key)
if value is None:
value = field_dict.setdefault(key, new_default(message))
@@ -365,6 +410,7 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
while pos < endpoint:
value_start_pos = pos
(element, pos) = _DecodeSignedVarint32(buffer, pos)
+ # pylint: disable=protected-access
if element in enum_type.values_by_number:
value.append(element)
else:
@@ -372,8 +418,10 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
message._unknown_fields = []
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_VARINT)
+
message._unknown_fields.append(
- (tag_bytes, buffer[value_start_pos:pos]))
+ (tag_bytes, buffer[value_start_pos:pos].tobytes()))
+ # pylint: enable=protected-access
if pos > endpoint:
if element in enum_type.values_by_number:
del value[-1] # Discard corrupt value.
@@ -386,18 +434,32 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT)
tag_len = len(tag_bytes)
def DecodeRepeatedField(buffer, pos, end, message, field_dict):
+ """Decode serialized repeated enum to its value and a new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes.
+ pos: int, position in the memory view to start at.
+ end: int, end position of serialized data
+ message: Message object to store unknown fields in
+ field_dict: Map[Descriptor, Any] to store decoded values in.
+
+ Returns:
+ int, new position in serialized data.
+ """
value = field_dict.get(key)
if value is None:
value = field_dict.setdefault(key, new_default(message))
while 1:
(element, new_pos) = _DecodeSignedVarint32(buffer, pos)
+ # pylint: disable=protected-access
if element in enum_type.values_by_number:
value.append(element)
else:
if not message._unknown_fields:
message._unknown_fields = []
message._unknown_fields.append(
- (tag_bytes, buffer[pos:new_pos]))
+ (tag_bytes, buffer[pos:new_pos].tobytes()))
+ # pylint: enable=protected-access
# Predict that the next tag is another copy of the same repeated
# field.
pos = new_pos + tag_len
@@ -409,10 +471,23 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
return DecodeRepeatedField
else:
def DecodeField(buffer, pos, end, message, field_dict):
+ """Decode serialized repeated enum to its value and a new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes.
+ pos: int, position in the memory view to start at.
+ end: int, end position of serialized data
+ message: Message object to store unknown fields in
+ field_dict: Map[Descriptor, Any] to store decoded values in.
+
+ Returns:
+ int, new position in serialized data.
+ """
value_start_pos = pos
(enum_value, pos) = _DecodeSignedVarint32(buffer, pos)
if pos > end:
raise _DecodeError('Truncated message.')
+ # pylint: disable=protected-access
if enum_value in enum_type.values_by_number:
field_dict[key] = enum_value
else:
@@ -421,7 +496,8 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default):
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_VARINT)
message._unknown_fields.append(
- (tag_bytes, buffer[value_start_pos:pos]))
+ (tag_bytes, buffer[value_start_pos:pos].tobytes()))
+ # pylint: enable=protected-access
return pos
return DecodeField
@@ -458,20 +534,34 @@ BoolDecoder = _ModifiedDecoder(
wire_format.WIRETYPE_VARINT, _DecodeVarint, bool)
-def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
+def StringDecoder(field_number, is_repeated, is_packed, key, new_default,
+ is_strict_utf8=False):
"""Returns a decoder for a string field."""
local_DecodeVarint = _DecodeVarint
local_unicode = six.text_type
- def _ConvertToUnicode(byte_str):
+ def _ConvertToUnicode(memview):
+ """Convert byte to unicode."""
+ byte_str = memview.tobytes()
try:
- return local_unicode(byte_str, 'utf-8')
+ value = local_unicode(byte_str, 'utf-8')
except UnicodeDecodeError as e:
# add more information to the error message and re-raise it.
e.reason = '%s in field: %s' % (e, key.full_name)
raise
+ if is_strict_utf8 and six.PY2 and sys.maxunicode > _UCS2_MAXUNICODE:
+ # Only do the check for python2 ucs4 when is_strict_utf8 enabled
+ if _SURROGATE_PATTERN.search(value):
+ reason = ('String field %s contains invalid UTF-8 data when parsing'
+ 'a protocol buffer: surrogates not allowed. Use'
+ 'the bytes type if you intend to send raw bytes.') % (
+ key.full_name)
+ raise message.DecodeError(reason)
+
+ return value
+
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
@@ -523,7 +613,7 @@ def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
new_pos = pos + size
if new_pos > end:
raise _DecodeError('Truncated string.')
- value.append(buffer[pos:new_pos])
+ value.append(buffer[pos:new_pos].tobytes())
# Predict that the next tag is another copy of the same repeated field.
pos = new_pos + tag_len
if buffer[new_pos:pos] != tag_bytes or new_pos == end:
@@ -536,7 +626,7 @@ def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
new_pos = pos + size
if new_pos > end:
raise _DecodeError('Truncated string.')
- field_dict[key] = buffer[pos:new_pos]
+ field_dict[key] = buffer[pos:new_pos].tobytes()
return new_pos
return DecodeField
@@ -665,6 +755,18 @@ def MessageSetItemDecoder(descriptor):
local_SkipField = SkipField
def DecodeItem(buffer, pos, end, message, field_dict):
+ """Decode serialized message set to its value and new position.
+
+ Args:
+ buffer: memoryview of the serialized bytes.
+ pos: int, position in the memory view to start at.
+ end: int, end position of serialized data
+ message: Message object to store unknown fields in
+ field_dict: Map[Descriptor, Any] to store decoded values in.
+
+ Returns:
+ int, new position in serialized data.
+ """
message_set_item_start = pos
type_id = -1
message_start = -1
@@ -695,6 +797,7 @@ def MessageSetItemDecoder(descriptor):
raise _DecodeError('MessageSet item missing message.')
extension = message.Extensions._FindExtensionByNumber(type_id)
+ # pylint: disable=protected-access
if extension is not None:
value = field_dict.get(extension)
if value is None:
@@ -707,8 +810,9 @@ def MessageSetItemDecoder(descriptor):
else:
if not message._unknown_fields:
message._unknown_fields = []
- message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,
- buffer[message_set_item_start:pos]))
+ message._unknown_fields.append(
+ (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes()))
+ # pylint: enable=protected-access
return pos
@@ -767,7 +871,7 @@ def _SkipVarint(buffer, pos, end):
# Previously ord(buffer[pos]) raised IndexError when pos is out of range.
# With this code, ord(b'') raises TypeError. Both are handled in
# python_message.py to generate a 'Truncated message' error.
- while ord(buffer[pos:pos+1]) & 0x80:
+ while ord(buffer[pos:pos+1].tobytes()) & 0x80:
pos += 1
pos += 1
if pos > end:
@@ -782,6 +886,13 @@ def _SkipFixed64(buffer, pos, end):
raise _DecodeError('Truncated message.')
return pos
+
+def _DecodeFixed64(buffer, pos):
+ """Decode a fixed64."""
+ new_pos = pos + 8
+ return (struct.unpack('<Q', buffer[pos:new_pos])[0], new_pos)
+
+
def _SkipLengthDelimited(buffer, pos, end):
"""Skip a length-delimited value. Returns the new position."""
@@ -791,6 +902,7 @@ def _SkipLengthDelimited(buffer, pos, end):
raise _DecodeError('Truncated message.')
return pos
+
def _SkipGroup(buffer, pos, end):
"""Skip sub-group. Returns the new position."""
@@ -801,11 +913,53 @@ def _SkipGroup(buffer, pos, end):
return pos
pos = new_pos
+
+def _DecodeGroup(buffer, pos):
+ """Decode group. Returns the UnknownFieldSet and new position."""
+
+ unknown_field_set = containers.UnknownFieldSet()
+ while 1:
+ (tag_bytes, pos) = ReadTag(buffer, pos)
+ (tag, _) = _DecodeVarint(tag_bytes, 0)
+ field_number, wire_type = wire_format.UnpackTag(tag)
+ if wire_type == wire_format.WIRETYPE_END_GROUP:
+ break
+ (data, pos) = _DecodeUnknownField(buffer, pos, wire_type)
+ # pylint: disable=protected-access
+ unknown_field_set._add(field_number, wire_type, data)
+
+ return (unknown_field_set, pos)
+
+
+def _DecodeUnknownField(buffer, pos, wire_type):
+ """Decode a unknown field. Returns the UnknownField and new position."""
+
+ if wire_type == wire_format.WIRETYPE_VARINT:
+ (data, pos) = _DecodeVarint(buffer, pos)
+ elif wire_type == wire_format.WIRETYPE_FIXED64:
+ (data, pos) = _DecodeFixed64(buffer, pos)
+ elif wire_type == wire_format.WIRETYPE_FIXED32:
+ (data, pos) = _DecodeFixed32(buffer, pos)
+ elif wire_type == wire_format.WIRETYPE_LENGTH_DELIMITED:
+ (size, pos) = _DecodeVarint(buffer, pos)
+ data = buffer[pos:pos+size]
+ pos += size
+ elif wire_type == wire_format.WIRETYPE_START_GROUP:
+ (data, pos) = _DecodeGroup(buffer, pos)
+ elif wire_type == wire_format.WIRETYPE_END_GROUP:
+ return (0, -1)
+ else:
+ raise _DecodeError('Wrong wire type in tag.')
+
+ return (data, pos)
+
+
def _EndGroup(buffer, pos, end):
"""Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
return -1
+
def _SkipFixed32(buffer, pos, end):
"""Skip a fixed32 value. Returns the new position."""
@@ -814,6 +968,14 @@ def _SkipFixed32(buffer, pos, end):
raise _DecodeError('Truncated message.')
return pos
+
+def _DecodeFixed32(buffer, pos):
+ """Decode a fixed32."""
+
+ new_pos = pos + 4
+ return (struct.unpack('<I', buffer[pos:new_pos])[0], new_pos)
+
+
def _RaiseInvalidWireType(buffer, pos, end):
"""Skip function for unknown wire types. Raises an exception."""
diff --git a/python/google/protobuf/internal/descriptor_database_test.py b/python/google/protobuf/internal/descriptor_database_test.py
index f97477b3..da5dbd92 100644
--- a/python/google/protobuf/internal/descriptor_database_test.py
+++ b/python/google/protobuf/internal/descriptor_database_test.py
@@ -43,6 +43,7 @@ import warnings
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import factory_test2_pb2
+from google.protobuf.internal import no_package_pb2
from google.protobuf import descriptor_database
@@ -52,7 +53,10 @@ class DescriptorDatabaseTest(unittest.TestCase):
db = descriptor_database.DescriptorDatabase()
file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb)
+ file_desc_proto2 = descriptor_pb2.FileDescriptorProto.FromString(
+ no_package_pb2.DESCRIPTOR.serialized_pb)
db.Add(file_desc_proto)
+ db.Add(file_desc_proto2)
self.assertEqual(file_desc_proto, db.FindFileByName(
'google/protobuf/internal/factory_test2.proto'))
@@ -76,6 +80,10 @@ class DescriptorDatabaseTest(unittest.TestCase):
# Can find enum value.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Enum.FACTORY_2_VALUE_0'))
+ self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.FACTORY_2_VALUE_0'))
+ self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol(
+ '.NO_PACKAGE_VALUE_0'))
# Can find top level extension.
self.assertEqual(file_desc_proto, db.FindFileContainingSymbol(
'google.protobuf.python.internal.another_field'))
@@ -95,9 +103,8 @@ class DescriptorDatabaseTest(unittest.TestCase):
self.assertEqual(file_desc_proto2, db.FindFileContainingSymbol(
'protobuf_unittest.TestAllTypes.none_field'))
- self.assertRaises(KeyError,
- db.FindFileContainingSymbol,
- 'protobuf_unittest.NoneMessage')
+ with self.assertRaisesRegexp(KeyError, r'\'protobuf_unittest\.NoneMessage\''):
+ db.FindFileContainingSymbol('protobuf_unittest.NoneMessage')
def testConflictRegister(self):
db = descriptor_database.DescriptorDatabase()
diff --git a/python/google/protobuf/internal/descriptor_pool_test.py b/python/google/protobuf/internal/descriptor_pool_test.py
index 2cbf7813..1b72b0b9 100644
--- a/python/google/protobuf/internal/descriptor_pool_test.py
+++ b/python/google/protobuf/internal/descriptor_pool_test.py
@@ -36,7 +36,6 @@ __author__ = 'matthewtoia@google.com (Matt Toia)'
import copy
import os
-import sys
import warnings
try:
@@ -55,6 +54,7 @@ from google.protobuf.internal import factory_test1_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf.internal import file_options_test_pb2
from google.protobuf.internal import more_messages_pb2
+from google.protobuf.internal import no_package_pb2
from google.protobuf import descriptor
from google.protobuf import descriptor_database
from google.protobuf import descriptor_pool
@@ -120,7 +120,6 @@ class DescriptorPoolTestBase(object):
self.assertIsInstance(file_desc5, descriptor.FileDescriptor)
self.assertEqual('google/protobuf/unittest.proto',
file_desc5.name)
-
# Tests the generated pool.
assert descriptor_pool.Default().FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Message.one_more_field')
@@ -129,6 +128,32 @@ class DescriptorPoolTestBase(object):
assert descriptor_pool.Default().FindFileContainingSymbol(
'protobuf_unittest.TestService')
+ # Can find field.
+ file_desc6 = self.pool.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.Factory1Message.list_value')
+ self.assertIsInstance(file_desc6, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/internal/factory_test1.proto',
+ file_desc6.name)
+
+ # Can find top level Enum value.
+ file_desc7 = self.pool.FindFileContainingSymbol(
+ 'google.protobuf.python.internal.FACTORY_1_VALUE_0')
+ self.assertIsInstance(file_desc7, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/internal/factory_test1.proto',
+ file_desc7.name)
+
+ # Can find nested Enum value.
+ file_desc8 = self.pool.FindFileContainingSymbol(
+ 'protobuf_unittest.TestAllTypes.FOO')
+ self.assertIsInstance(file_desc8, descriptor.FileDescriptor)
+ self.assertEqual('google/protobuf/unittest.proto',
+ file_desc8.name)
+
+ # TODO(jieluo): Add tests for no package when b/13860351 is fixed.
+
+ self.assertRaises(KeyError, self.pool.FindFileContainingSymbol,
+ 'google.protobuf.python.internal.Factory1Message.none_field')
+
def testFindFileContainingSymbolFailure(self):
with self.assertRaises(KeyError):
self.pool.FindFileContainingSymbol('Does not exist')
@@ -217,11 +242,10 @@ class DescriptorPoolTestBase(object):
def testFindTypeErrors(self):
self.assertRaises(TypeError, self.pool.FindExtensionByNumber, '')
+ self.assertRaises(KeyError, self.pool.FindMethodByName, '')
# 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
@@ -231,6 +255,7 @@ class DescriptorPoolTestBase(object):
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.FindMethodByName, 0)
self.assertRaises(error_type, self.pool.FindFileContainingSymbol, 0)
if api_implementation.Type() == 'python':
error_type = KeyError
@@ -275,11 +300,6 @@ class DescriptorPoolTestBase(object):
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')
@@ -290,11 +310,6 @@ class DescriptorPoolTestBase(object):
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')
@@ -302,11 +317,6 @@ class DescriptorPoolTestBase(object):
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')
@@ -382,6 +392,11 @@ class DescriptorPoolTestBase(object):
with self.assertRaises(KeyError):
self.pool.FindServiceByName('Does not exist')
+ method = self.pool.FindMethodByName('protobuf_unittest.TestService.Foo')
+ self.assertIs(method.containing_service, service)
+ with self.assertRaises(KeyError):
+ self.pool.FindMethodByName('protobuf_unittest.TestService.Doesnotexist')
+
def testUserDefinedDB(self):
db = descriptor_database.DescriptorDatabase()
self.pool = descriptor_pool.DescriptorPool(db)
@@ -601,6 +616,8 @@ class CreateDescriptorPoolTest(DescriptorPoolTestBase, unittest.TestCase):
unittest_import_pb2.DESCRIPTOR.serialized_pb))
self.pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
unittest_pb2.DESCRIPTOR.serialized_pb))
+ self.pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ no_package_pb2.DESCRIPTOR.serialized_pb))
class SecondaryDescriptorFromDescriptorDB(DescriptorPoolTestBase,
@@ -620,6 +637,8 @@ class SecondaryDescriptorFromDescriptorDB(DescriptorPoolTestBase,
unittest_import_pb2.DESCRIPTOR.serialized_pb))
db.Add(descriptor_pb2.FileDescriptorProto.FromString(
unittest_pb2.DESCRIPTOR.serialized_pb))
+ db.Add(descriptor_pb2.FileDescriptorProto.FromString(
+ no_package_pb2.DESCRIPTOR.serialized_pb))
self.pool = descriptor_pool.DescriptorPool(descriptor_db=db)
@@ -746,11 +765,7 @@ class MessageField(object):
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')
+ test.assertEqual(field_desc.default_value, None)
class StringField(object):
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py
index 02a43d15..af6bece1 100755
--- a/python/google/protobuf/internal/descriptor_test.py
+++ b/python/google/protobuf/internal/descriptor_test.py
@@ -452,6 +452,17 @@ class DescriptorTest(unittest.TestCase):
self.assertEqual('attribute is not writable: has_options',
str(e.exception))
+ def testDefault(self):
+ message_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
+ field = message_descriptor.fields_by_name['repeated_int32']
+ self.assertEqual(field.default_value, [])
+ field = message_descriptor.fields_by_name['repeated_nested_message']
+ self.assertEqual(field.default_value, [])
+ field = message_descriptor.fields_by_name['optionalgroup']
+ self.assertEqual(field.default_value, None)
+ field = message_descriptor.fields_by_name['optional_nested_message']
+ self.assertEqual(field.default_value, None)
+
class NewDescriptorTest(DescriptorTest):
"""Redo the same tests as above, but with a separate DescriptorPool."""
diff --git a/python/google/protobuf/internal/factory_test1.proto b/python/google/protobuf/internal/factory_test1.proto
index d2fbbeec..f5bd0383 100644
--- a/python/google/protobuf/internal/factory_test1.proto
+++ b/python/google/protobuf/internal/factory_test1.proto
@@ -56,3 +56,17 @@ message Factory1Message {
extensions 1000 to max;
}
+
+message Factory1MethodRequest {
+ optional string argument = 1;
+}
+
+message Factory1MethodResponse {
+ optional string result = 1;
+}
+
+service Factory1Service {
+ // Dummy method for this dummy service.
+ rpc Factory1Method(Factory1MethodRequest) returns (Factory1MethodResponse) {
+ }
+}
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
index d891dce1..7f649406 100644
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -791,9 +791,6 @@ class JsonFormatTest(JsonFormatBase):
json_format.Parse(text, parsed_message, ignore_unknown_fields=True)
def testDuplicateField(self):
- # Duplicate key check is not supported for python2.6
- if sys.version_info < (2, 7):
- return
self.CheckError('{"int32Value": 1,\n"int32Value":2}',
'Failed to load JSON: duplicate key int32Value.')
diff --git a/python/google/protobuf/internal/message_factory_test.py b/python/google/protobuf/internal/message_factory_test.py
index 6df52ed2..b97e3f65 100644
--- a/python/google/protobuf/internal/message_factory_test.py
+++ b/python/google/protobuf/internal/message_factory_test.py
@@ -142,10 +142,8 @@ class MessageFactoryTest(unittest.TestCase):
self.assertEqual('test2', msg1.Extensions[ext2])
self.assertEqual(None,
msg1.Extensions._FindExtensionByNumber(12321))
+ self.assertRaises(TypeError, len, msg1.Extensions)
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,
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py
index 61a56a67..4dd1104a 100755
--- a/python/google/protobuf/internal/message_test.py
+++ b/python/google/protobuf/internal/message_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.
@@ -49,6 +50,7 @@ import copy
import math
import operator
import pickle
+import pydoc
import six
import sys
import warnings
@@ -72,12 +74,14 @@ 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 more_extensions_pb2
from google.protobuf.internal import packed_field_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import testing_refleaks
from google.protobuf import message
from google.protobuf.internal import _parameterized
+UCS2_MAXUNICODE = 65535
if six.PY3:
long = int
@@ -415,6 +419,37 @@ class MessageTest(BaseTestCase):
empty.ParseFromString(populated.SerializeToString())
self.assertEqual(str(empty), '')
+ def testMergeFromRepeatedField(self, message_module):
+ msg = message_module.TestAllTypes()
+ msg.repeated_int32.append(1)
+ msg.repeated_int32.append(3)
+ msg.repeated_nested_message.add(bb=1)
+ msg.repeated_nested_message.add(bb=2)
+ other_msg = message_module.TestAllTypes()
+ other_msg.repeated_nested_message.add(bb=3)
+ other_msg.repeated_nested_message.add(bb=4)
+ other_msg.repeated_int32.append(5)
+ other_msg.repeated_int32.append(7)
+
+ msg.repeated_int32.MergeFrom(other_msg.repeated_int32)
+ self.assertEqual(4, len(msg.repeated_int32))
+
+ msg.repeated_nested_message.MergeFrom(other_msg.repeated_nested_message)
+ self.assertEqual([1, 2, 3, 4],
+ [m.bb for m in msg.repeated_nested_message])
+
+ def testAddWrongRepeatedNestedField(self, message_module):
+ msg = message_module.TestAllTypes()
+ try:
+ msg.repeated_nested_message.add('wrong')
+ except TypeError:
+ pass
+ try:
+ msg.repeated_nested_message.add(value_field='wrong')
+ except ValueError:
+ pass
+ self.assertEqual(len(msg.repeated_nested_message), 0)
+
def testRepeatedNestedFieldIteration(self, message_module):
msg = message_module.TestAllTypes()
msg.repeated_nested_message.add(bb=1)
@@ -645,6 +680,82 @@ class MessageTest(BaseTestCase):
m.payload.repeated_int32.extend([])
self.assertTrue(m.HasField('payload'))
+ def testMergeFrom(self, message_module):
+ m1 = message_module.TestAllTypes()
+ m2 = message_module.TestAllTypes()
+ # Cpp extension will lazily create a sub message which is immutable.
+ self.assertEqual(0, m1.optional_nested_message.bb)
+ m2.optional_nested_message.bb = 1
+ # Make sure cmessage pointing to a mutable message after merge instead of
+ # the lazily created message.
+ m1.MergeFrom(m2)
+ self.assertEqual(1, m1.optional_nested_message.bb)
+
+ # Test more nested sub message.
+ msg1 = message_module.NestedTestAllTypes()
+ msg2 = message_module.NestedTestAllTypes()
+ self.assertEqual(0, msg1.child.payload.optional_nested_message.bb)
+ msg2.child.payload.optional_nested_message.bb = 1
+ msg1.MergeFrom(msg2)
+ self.assertEqual(1, msg1.child.payload.optional_nested_message.bb)
+
+ # Test repeated field.
+ self.assertEqual(msg1.payload.repeated_nested_message,
+ msg1.payload.repeated_nested_message)
+ msg2.payload.repeated_nested_message.add().bb = 1
+ msg1.MergeFrom(msg2)
+ self.assertEqual(1, len(msg1.payload.repeated_nested_message))
+ self.assertEqual(1, msg1.payload.repeated_nested_message[0].bb)
+
+ def testMergeFromString(self, message_module):
+ m1 = message_module.TestAllTypes()
+ m2 = message_module.TestAllTypes()
+ # Cpp extension will lazily create a sub message which is immutable.
+ self.assertEqual(0, m1.optional_nested_message.bb)
+ m2.optional_nested_message.bb = 1
+ # Make sure cmessage pointing to a mutable message after merge instead of
+ # the lazily created message.
+ m1.MergeFromString(m2.SerializeToString())
+ self.assertEqual(1, m1.optional_nested_message.bb)
+
+ @unittest.skipIf(six.PY2, 'memoryview objects are not supported on py2')
+ def testMergeFromStringUsingMemoryViewWorksInPy3(self, message_module):
+ m2 = message_module.TestAllTypes()
+ m2.optional_string = 'scalar string'
+ m2.repeated_string.append('repeated string')
+ m2.optional_bytes = b'scalar bytes'
+ m2.repeated_bytes.append(b'repeated bytes')
+
+ serialized = m2.SerializeToString()
+ memview = memoryview(serialized)
+ m1 = message_module.TestAllTypes.FromString(memview)
+
+ self.assertEqual(m1.optional_bytes, b'scalar bytes')
+ self.assertEqual(m1.repeated_bytes, [b'repeated bytes'])
+ self.assertEqual(m1.optional_string, 'scalar string')
+ self.assertEqual(m1.repeated_string, ['repeated string'])
+ # Make sure that the memoryview was correctly converted to bytes, and
+ # that a sub-sliced memoryview is not being used.
+ self.assertIsInstance(m1.optional_bytes, bytes)
+ self.assertIsInstance(m1.repeated_bytes[0], bytes)
+ self.assertIsInstance(m1.optional_string, six.text_type)
+ self.assertIsInstance(m1.repeated_string[0], six.text_type)
+
+ @unittest.skipIf(six.PY3, 'memoryview is supported by py3')
+ def testMergeFromStringUsingMemoryViewIsPy2Error(self, message_module):
+ memview = memoryview(b'')
+ with self.assertRaises(TypeError):
+ message_module.TestAllTypes.FromString(memview)
+
+ def testMergeFromEmpty(self, message_module):
+ m1 = message_module.TestAllTypes()
+ # Cpp extension will lazily create a sub message which is immutable.
+ self.assertEqual(0, m1.optional_nested_message.bb)
+ self.assertFalse(m1.HasField('optional_nested_message'))
+ # Make sure the sub message is still immutable after merge from empty.
+ m1.MergeFromString(b'') # field state should not change
+ self.assertFalse(m1.HasField('optional_nested_message'))
+
def ensureNestedMessageExists(self, msg, attribute):
"""Make sure that a nested message object exists.
@@ -1067,14 +1178,8 @@ class MessageTest(BaseTestCase):
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 = []
+ with self.assertRaises(AttributeError):
+ m.repeated_int32 = []
# Class to test proto2-only features (required, extensions, etc.)
@@ -1112,13 +1217,13 @@ class Proto2Test(BaseTestCase):
message.optional_bool = True
message.optional_nested_message.bb = 15
- self.assertTrue(message.HasField("optional_int32"))
+ self.assertTrue(message.HasField(u"optional_int32"))
self.assertTrue(message.HasField("optional_bool"))
self.assertTrue(message.HasField("optional_nested_message"))
# Clearing the fields unsets them and resets their value to default.
message.ClearField("optional_int32")
- message.ClearField("optional_bool")
+ message.ClearField(u"optional_bool")
message.ClearField("optional_nested_message")
self.assertFalse(message.HasField("optional_int32"))
@@ -1169,6 +1274,21 @@ class Proto2Test(BaseTestCase):
msg = unittest_pb2.TestAllTypes()
self.assertRaises(AttributeError, getattr, msg, 'Extensions')
+ def testMergeFromExtensions(self):
+ msg1 = more_extensions_pb2.TopLevelMessage()
+ msg2 = more_extensions_pb2.TopLevelMessage()
+ # Cpp extension will lazily create a sub message which is immutable.
+ self.assertEqual(0, msg1.submessage.Extensions[
+ more_extensions_pb2.optional_int_extension])
+ self.assertFalse(msg1.HasField('submessage'))
+ msg2.submessage.Extensions[
+ more_extensions_pb2.optional_int_extension] = 123
+ # Make sure cmessage and extensions pointing to a mutable message
+ # after merge instead of the lazily created message.
+ msg1.MergeFrom(msg2)
+ self.assertEqual(123, msg1.submessage.Extensions[
+ more_extensions_pb2.optional_int_extension])
+
def testGoldenExtensions(self):
golden_data = test_util.GoldenFileData('golden_message')
golden_message = unittest_pb2.TestAllExtensions()
@@ -1315,6 +1435,25 @@ class Proto2Test(BaseTestCase):
with self.assertRaises(ValueError):
unittest_pb2.TestAllTypes(repeated_nested_enum='FOO')
+ def testPythonicInitWithDict(self):
+ # Both string/unicode field name keys should work.
+ kwargs = {
+ 'optional_int32': 100,
+ u'optional_fixed32': 200,
+ }
+ msg = unittest_pb2.TestAllTypes(**kwargs)
+ self.assertEqual(100, msg.optional_int32)
+ self.assertEqual(200, msg.optional_fixed32)
+
+
+ def test_documentation(self):
+ # Also used by the interactive help() function.
+ doc = pydoc.html.document(unittest_pb2.TestAllTypes, 'message')
+ self.assertIn('class TestAllTypes', doc)
+ self.assertIn('SerializePartialToString', doc)
+ self.assertIn('repeated_float', doc)
+ base = unittest_pb2.TestAllTypes.__bases__[0]
+ self.assertRaises(AttributeError, getattr, base, '_extensions_by_name')
# Class to test proto3-only features/behavior (updated field presence & enums)
@@ -1539,10 +1678,8 @@ class Proto3Test(BaseTestCase):
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))
+ self.assertEqual('{-123: -456}',
+ str(msg2.map_int32_int32))
def testMapEntryAlwaysSerialized(self):
msg = map_unittest_pb2.TestMap()
@@ -1603,11 +1740,10 @@ 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))
+ msg2.map_int32_foreign_message[123].c = 1
# 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)))
+ self.assertIn(str(msg2.map_int32_foreign_message),
+ ('{-456: , 123: c: 1\n}', '{123: c: 1\n, -456: }'))
def testNestedMessageMapItemDelete(self):
msg = map_unittest_pb2.TestMap()
@@ -1721,6 +1857,15 @@ class Proto3Test(BaseTestCase):
self.assertEqual(10, msg2.map_int32_foreign_message[222].c)
self.assertFalse(msg2.map_int32_foreign_message[222].HasField('d'))
+ # Test when cpp extension cache a map.
+ m1 = map_unittest_pb2.TestMap()
+ m2 = map_unittest_pb2.TestMap()
+ self.assertEqual(m1.map_int32_foreign_message,
+ m1.map_int32_foreign_message)
+ m2.map_int32_foreign_message[123].c = 10
+ m1.MergeFrom(m2)
+ self.assertEqual(10, m2.map_int32_foreign_message[123].c)
+
def testMergeFromBadType(self):
msg = map_unittest_pb2.TestMap()
with self.assertRaisesRegexp(
@@ -1972,7 +2117,7 @@ class Proto3Test(BaseTestCase):
def testMapValidAfterFieldCleared(self):
# Map needs to work even if field is cleared.
# For the C++ implementation this tests the correctness of
- # ScalarMapContainer::Release()
+ # MapContainer::Release()
msg = map_unittest_pb2.TestMap()
int32_map = msg.map_int32_int32
@@ -1988,7 +2133,7 @@ class Proto3Test(BaseTestCase):
def testMessageMapValidAfterFieldCleared(self):
# Map needs to work even if field is cleared.
# For the C++ implementation this tests the correctness of
- # ScalarMapContainer::Release()
+ # MapContainer::Release()
msg = map_unittest_pb2.TestMap()
int32_foreign_message = msg.map_int32_foreign_message
@@ -1998,6 +2143,24 @@ class Proto3Test(BaseTestCase):
self.assertEqual(b'', msg.SerializeToString())
self.assertTrue(2 in int32_foreign_message.keys())
+ def testMessageMapItemValidAfterTopMessageCleared(self):
+ # Message map item needs to work even if it is cleared.
+ # For the C++ implementation this tests the correctness of
+ # MapContainer::Release()
+ msg = map_unittest_pb2.TestMap()
+ msg.map_int32_all_types[2].optional_string = 'bar'
+
+ if api_implementation.Type() == 'cpp':
+ # Need to keep the map reference because of b/27942626.
+ # TODO(jieluo): Remove it.
+ unused_map = msg.map_int32_all_types # pylint: disable=unused-variable
+ msg_value = msg.map_int32_all_types[2]
+ msg.Clear()
+
+ # Reset to trigger sync between repeated field and map in c++.
+ msg.map_int32_all_types[3].optional_string = 'foo'
+ self.assertEqual(msg_value.optional_string, 'bar')
+
def testMapIterInvalidatedByClearField(self):
# Map iterator is invalidated when field is cleared.
# But this case does need to not crash the interpreter.
@@ -2058,6 +2221,82 @@ class Proto3Test(BaseTestCase):
msg.map_string_foreign_message['foo'].c = 5
self.assertEqual(0, len(msg.FindInitializationErrors()))
+ @unittest.skipIf(sys.maxunicode == UCS2_MAXUNICODE, 'Skip for ucs2')
+ def testStrictUtf8Check(self):
+ # Test u'\ud801' is rejected at parser in both python2 and python3.
+ serialized = (b'r\x03\xed\xa0\x81')
+ msg = unittest_proto3_arena_pb2.TestAllTypes()
+ with self.assertRaises(Exception) as context:
+ msg.MergeFromString(serialized)
+ if api_implementation.Type() == 'python':
+ self.assertIn('optional_string', str(context.exception))
+ else:
+ self.assertIn('Error parsing message', str(context.exception))
+
+ # Test optional_string=u'😍' is accepted.
+ serialized = unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'😍').SerializeToString()
+ msg2 = unittest_proto3_arena_pb2.TestAllTypes()
+ msg2.MergeFromString(serialized)
+ self.assertEqual(msg2.optional_string, u'😍')
+
+ msg = unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud001')
+ self.assertEqual(msg.optional_string, u'\ud001')
+
+ @unittest.skipIf(six.PY2, 'Surrogates are acceptable in python2')
+ def testSurrogatesInPython3(self):
+ # Surrogates like U+D83D is an invalid unicode character, it is
+ # supported by Python2 only because in some builds, unicode strings
+ # use 2-bytes code units. Since Python 3.3, we don't have this problem.
+ #
+ # Surrogates are utf16 code units, in a unicode string they are invalid
+ # characters even when they appear in pairs like u'\ud801\udc01'. Protobuf
+ # Python3 reject such cases at setters and parsers. Python2 accpect it
+ # to keep same features with the language itself. 'Unpaired pairs'
+ # like u'\ud801' are rejected at parsers when strict utf8 check is enabled
+ # in proto3 to keep same behavior with c extension.
+
+ # Surrogates are rejected at setters in Python3.
+ with self.assertRaises(ValueError):
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801\udc01')
+ with self.assertRaises(ValueError):
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=b'\xed\xa0\x81')
+ with self.assertRaises(ValueError):
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801')
+ with self.assertRaises(ValueError):
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801\ud801')
+
+ @unittest.skipIf(six.PY3 or sys.maxunicode == UCS2_MAXUNICODE,
+ 'Surrogates are rejected at setters in Python3')
+ def testSurrogatesInPython2(self):
+ # Test optional_string=u'\ud801\udc01'.
+ # surrogate pair is acceptable in python2.
+ msg = unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801\udc01')
+ # TODO(jieluo): Change pure python to have same behavior with c extension.
+ # Some build in python2 consider u'\ud801\udc01' and u'\U00010401' are
+ # equal, some are not equal.
+ if api_implementation.Type() == 'python':
+ self.assertEqual(msg.optional_string, u'\ud801\udc01')
+ else:
+ self.assertEqual(msg.optional_string, u'\U00010401')
+ serialized = msg.SerializeToString()
+ msg2 = unittest_proto3_arena_pb2.TestAllTypes()
+ msg2.MergeFromString(serialized)
+ self.assertEqual(msg2.optional_string, u'\U00010401')
+
+ # Python2 does not reject surrogates at setters.
+ msg = unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=b'\xed\xa0\x81')
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801')
+ unittest_proto3_arena_pb2.TestAllTypes(
+ optional_string=u'\ud801\ud801')
class ValidTypeNamesTest(BaseTestCase):
diff --git a/python/google/protobuf/internal/no_package.proto b/python/google/protobuf/internal/no_package.proto
index 3546dcc3..49eda959 100644
--- a/python/google/protobuf/internal/no_package.proto
+++ b/python/google/protobuf/internal/no_package.proto
@@ -1,3 +1,33 @@
+// 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";
enum NoPackageEnum {
diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py
index 975e3b4d..4e0f545c 100755
--- a/python/google/protobuf/internal/python_message.py
+++ b/python/google/protobuf/internal/python_message.py
@@ -56,6 +56,7 @@ import sys
import weakref
import six
+from six.moves import range
# We use "as" to avoid name collisions with variables.
from google.protobuf.internal import api_implementation
@@ -124,6 +125,21 @@ class GeneratedProtocolMessageType(type):
Newly-allocated class.
"""
descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
+
+ # If a concrete class already exists for this descriptor, don't try to
+ # create another. Doing so will break any messages that already exist with
+ # the existing class.
+ #
+ # The C++ implementation appears to have its own internal `PyMessageFactory`
+ # to achieve similar results.
+ #
+ # This most commonly happens in `text_format.py` when using descriptors from
+ # a custom pool; it calls symbol_database.Global().getPrototype() on a
+ # descriptor which already has an existing concrete class.
+ new_class = getattr(descriptor, '_concrete_class', None)
+ if new_class:
+ return new_class
+
if descriptor.full_name in well_known_types.WKTBASES:
bases += (well_known_types.WKTBASES[descriptor.full_name],)
_AddClassAttributesForNestedExtensions(descriptor, dictionary)
@@ -151,6 +167,16 @@ class GeneratedProtocolMessageType(type):
type.
"""
descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
+
+ # If this is an _existing_ class looked up via `_concrete_class` in the
+ # __new__ method above, then we don't need to re-initialize anything.
+ existing_class = getattr(descriptor, '_concrete_class', None)
+ if existing_class:
+ assert existing_class is cls, (
+ 'Duplicate `GeneratedProtocolMessageType` created for descriptor %r'
+ % (descriptor.full_name))
+ return
+
cls._decoders_by_tag = {}
if (descriptor.has_options and
descriptor.GetOptions().message_set_wire_format):
@@ -245,6 +271,7 @@ def _AddSlots(message_descriptor, dictionary):
'_cached_byte_size_dirty',
'_fields',
'_unknown_fields',
+ '_unknown_field_set',
'_is_present_in_parent',
'_listener',
'_listener_for_children',
@@ -271,6 +298,13 @@ def _IsMessageMapField(field):
return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE
+def _IsStrictUtf8Check(field):
+ if field.containing_type.syntax != 'proto3':
+ return False
+ enforce_utf8 = True
+ return enforce_utf8
+
+
def _AttachFieldHelpers(cls, field_descriptor):
is_repeated = (field_descriptor.label == _FieldDescriptor.LABEL_REPEATED)
is_packable = (is_repeated and
@@ -322,10 +356,16 @@ def _AttachFieldHelpers(cls, field_descriptor):
field_decoder = decoder.MapDecoder(
field_descriptor, _GetInitializeDefaultForMap(field_descriptor),
is_message_map)
+ elif decode_type == _FieldDescriptor.TYPE_STRING:
+ is_strict_utf8_check = _IsStrictUtf8Check(field_descriptor)
+ field_decoder = decoder.StringDecoder(
+ field_descriptor.number, is_repeated, is_packed,
+ field_descriptor, field_descriptor._default_constructor,
+ is_strict_utf8_check)
else:
field_decoder = type_checkers.TYPE_TO_DECODER[decode_type](
- field_descriptor.number, is_repeated, is_packed,
- field_descriptor, field_descriptor._default_constructor)
+ field_descriptor.number, is_repeated, is_packed,
+ field_descriptor, field_descriptor._default_constructor)
cls._decoders_by_tag[tag_bytes] = (field_decoder, oneof_descriptor)
@@ -422,6 +462,9 @@ def _DefaultValueConstructorForField(field):
# _concrete_class may not yet be initialized.
message_type = field.message_type
def MakeSubMessageDefault(message):
+ assert getattr(message_type, '_concrete_class', None), (
+ 'Uninitialized concrete class found for field %r (message type %r)'
+ % (field.full_name, message_type.full_name))
result = message_type._concrete_class()
result._SetListener(
_OneofListener(message, field)
@@ -477,6 +520,9 @@ def _AddInitMethod(message_descriptor, cls):
# _unknown_fields is () when empty for efficiency, and will be turned into
# a list if fields are added.
self._unknown_fields = ()
+ # _unknown_field_set is None when empty for efficiency, and will be
+ # turned into UnknownFieldSet struct if fields are added.
+ self._unknown_field_set = None # pylint: disable=protected-access
self._is_present_in_parent = False
self._listener = message_listener_mod.NullMessageListener()
self._listener_for_children = _Listener(self)
@@ -584,6 +630,14 @@ def _AddPropertiesForField(field, cls):
_AddPropertiesForNonRepeatedScalarField(field, cls)
+class _FieldProperty(property):
+ __slots__ = ('DESCRIPTOR',)
+
+ def __init__(self, descriptor, getter, setter, doc):
+ property.__init__(self, getter, setter, doc=doc)
+ self.DESCRIPTOR = descriptor
+
+
def _AddPropertiesForRepeatedField(field, cls):
"""Adds a public property for a "repeated" protocol message field. Clients
can use this property to get the value of the field, which will be either a
@@ -625,7 +679,7 @@ def _AddPropertiesForRepeatedField(field, cls):
'"%s" in protocol message object.' % proto_field_name)
doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
- setattr(cls, property_name, property(getter, setter, doc=doc))
+ setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc))
def _AddPropertiesForNonRepeatedScalarField(field, cls):
@@ -681,7 +735,7 @@ def _AddPropertiesForNonRepeatedScalarField(field, cls):
# Add a property to encapsulate the getter/setter.
doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
- setattr(cls, property_name, property(getter, setter, doc=doc))
+ setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc))
def _AddPropertiesForNonRepeatedCompositeField(field, cls):
@@ -725,7 +779,7 @@ def _AddPropertiesForNonRepeatedCompositeField(field, cls):
# Add a property to encapsulate the getter.
doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
- setattr(cls, property_name, property(getter, setter, doc=doc))
+ setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc))
def _AddPropertiesForExtensions(descriptor, cls):
@@ -949,12 +1003,12 @@ def _AddEqualsMethod(message_descriptor, cls):
if not self.ListFields() == other.ListFields():
return False
- # Sort unknown fields because their order shouldn't affect equality test.
+ # TODO(jieluo): Fix UnknownFieldSet to consider MessageSet extensions,
+ # then use it for the comparison.
unknown_fields = list(self._unknown_fields)
unknown_fields.sort()
other_unknown_fields = list(other._unknown_fields)
other_unknown_fields.sort()
-
return unknown_fields == other_unknown_fields
cls.__eq__ = __eq__
@@ -1078,6 +1132,13 @@ def _AddSerializePartialToStringMethod(message_descriptor, cls):
def _AddMergeFromStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def MergeFromString(self, serialized):
+ if isinstance(serialized, memoryview) and six.PY2:
+ raise TypeError(
+ 'memoryview not supported in Python 2 with the pure Python proto '
+ 'implementation: this is to maintain compatibility with the C++ '
+ 'implementation')
+
+ serialized = memoryview(serialized)
length = len(serialized)
try:
if self._InternalParse(serialized, 0, length) != length:
@@ -1095,26 +1156,54 @@ def _AddMergeFromStringMethod(message_descriptor, cls):
local_ReadTag = decoder.ReadTag
local_SkipField = decoder.SkipField
decoders_by_tag = cls._decoders_by_tag
- is_proto3 = message_descriptor.syntax == "proto3"
def InternalParse(self, buffer, pos, end):
+ """Create a message from serialized bytes.
+
+ Args:
+ self: Message, instance of the proto message object.
+ buffer: memoryview of the serialized data.
+ pos: int, position to start in the serialized data.
+ end: int, end position of the serialized data.
+
+ Returns:
+ Message object.
+ """
+ # Guard against internal misuse, since this function is called internally
+ # quite extensively, and its easy to accidentally pass bytes.
+ assert isinstance(buffer, memoryview)
self._Modified()
field_dict = self._fields
- unknown_field_list = self._unknown_fields
+ # pylint: disable=protected-access
+ unknown_field_set = self._unknown_field_set
while pos != end:
(tag_bytes, new_pos) = local_ReadTag(buffer, pos)
field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None))
if field_decoder is None:
- value_start_pos = new_pos
- new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)
+ if not self._unknown_fields: # pylint: disable=protected-access
+ self._unknown_fields = [] # pylint: disable=protected-access
+ if unknown_field_set is None:
+ # pylint: disable=protected-access
+ self._unknown_field_set = containers.UnknownFieldSet()
+ # pylint: disable=protected-access
+ unknown_field_set = self._unknown_field_set
+ # pylint: disable=protected-access
+ (tag, _) = decoder._DecodeVarint(tag_bytes, 0)
+ field_number, wire_type = wire_format.UnpackTag(tag)
+ # TODO(jieluo): remove old_pos.
+ old_pos = new_pos
+ (data, new_pos) = decoder._DecodeUnknownField(
+ buffer, new_pos, wire_type) # pylint: disable=protected-access
if new_pos == -1:
return pos
- if (not is_proto3 or
- api_implementation.GetPythonProto3PreserveUnknownsDefault()):
- if not unknown_field_list:
- unknown_field_list = self._unknown_fields = []
- unknown_field_list.append(
- (tag_bytes, buffer[value_start_pos:new_pos]))
+ # pylint: disable=protected-access
+ unknown_field_set._add(field_number, wire_type, data)
+ # TODO(jieluo): remove _unknown_fields.
+ new_pos = local_SkipField(buffer, old_pos, end, tag_bytes)
+ if new_pos == -1:
+ return pos
+ self._unknown_fields.append(
+ (tag_bytes, buffer[old_pos:new_pos].tobytes()))
pos = new_pos
else:
pos = field_decoder(buffer, new_pos, end, self, field_dict)
@@ -1259,6 +1348,10 @@ def _AddMergeFromMethod(cls):
if not self._unknown_fields:
self._unknown_fields = []
self._unknown_fields.extend(msg._unknown_fields)
+ # pylint: disable=protected-access
+ if self._unknown_field_set is None:
+ self._unknown_field_set = containers.UnknownFieldSet()
+ self._unknown_field_set._extend(msg._unknown_field_set)
cls.MergeFrom = MergeFrom
@@ -1291,12 +1384,25 @@ def _Clear(self):
# Clear fields.
self._fields = {}
self._unknown_fields = ()
+ # pylint: disable=protected-access
+ if self._unknown_field_set is not None:
+ self._unknown_field_set._clear()
+ self._unknown_field_set = None
+
self._oneofs = {}
self._Modified()
+def _UnknownFields(self):
+ if self._unknown_field_set is None: # pylint: disable=protected-access
+ # pylint: disable=protected-access
+ self._unknown_field_set = containers.UnknownFieldSet()
+ return self._unknown_field_set # pylint: disable=protected-access
+
+
def _DiscardUnknownFields(self):
self._unknown_fields = []
+ self._unknown_field_set = None # pylint: disable=protected-access
for field, value in self.ListFields():
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
if field.label == _FieldDescriptor.LABEL_REPEATED:
@@ -1335,6 +1441,7 @@ def _AddMessageMethods(message_descriptor, cls):
_AddReduceMethod(cls)
# Adds methods which do not depend on cls.
cls.Clear = _Clear
+ cls.UnknownFields = _UnknownFields
cls.DiscardUnknownFields = _DiscardUnknownFields
cls._SetListener = _SetListener
@@ -1471,6 +1578,10 @@ class _ExtensionDict(object):
if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
result = extension_handle._default_constructor(self._extended_message)
elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
+ assert getattr(extension_handle.message_type, '_concrete_class', None), (
+ 'Uninitialized concrete class found for field %r (message type %r)'
+ % (extension_handle.full_name,
+ extension_handle.message_type.full_name))
result = extension_handle.message_type._concrete_class()
try:
result._SetListener(self._extended_message._listener_for_children)
diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py
index 0306ff46..90d2fe3c 100755
--- a/python/google/protobuf/internal/reflection_test.py
+++ b/python/google/protobuf/internal/reflection_test.py
@@ -64,6 +64,10 @@ from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import decoder
+if six.PY3:
+ long = int # pylint: disable=redefined-builtin,invalid-name
+
+
BaseTestCase = testing_refleaks.BaseTestCase
@@ -647,10 +651,7 @@ class ReflectionTest(BaseTestCase):
TestGetAndDeserialize('optional_int32', 1, int)
TestGetAndDeserialize('optional_int32', 1 << 30, int)
TestGetAndDeserialize('optional_uint32', 1 << 30, int)
- try:
- integer_64 = long
- except NameError: # Python3
- integer_64 = int
+ integer_64 = long
if struct.calcsize('L') == 4:
# Python only has signed ints, so 32-bit python can't fit an uint32
# in an int.
@@ -1103,6 +1104,7 @@ class ReflectionTest(BaseTestCase):
self.assertEqual(23, myproto_instance.foo_field)
self.assertTrue(myproto_instance.HasField('foo_field'))
+ @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable')
def testDescriptorProtoSupport(self):
# Hand written descriptors/reflection are only supported by the pure-Python
# implementation of the API.
@@ -1141,7 +1143,8 @@ class ReflectionTest(BaseTestCase):
self.assertTrue('price' in desc.fields_by_name)
self.assertTrue('owners' in desc.fields_by_name)
- class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
+ class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType,
+ message.Message)):
DESCRIPTOR = desc
prius = CarMessage()
@@ -1576,6 +1579,8 @@ class ReflectionTest(BaseTestCase):
proto1.repeated_int32.append(3)
container = copy.deepcopy(proto1.repeated_int32)
self.assertEqual([2, 3], container)
+ container.remove(container[0])
+ self.assertEqual([3], container)
message1 = proto1.repeated_nested_message.add()
message1.bb = 1
@@ -1583,6 +1588,8 @@ class ReflectionTest(BaseTestCase):
self.assertEqual(proto1.repeated_nested_message, messages)
message1.bb = 2
self.assertNotEqual(proto1.repeated_nested_message, messages)
+ messages.remove(messages[0])
+ self.assertEqual(len(messages), 0)
# TODO(anuraag): Implement deepcopy for extension dict
@@ -2435,7 +2442,7 @@ class SerializationTest(BaseTestCase):
first_proto = unittest_pb2.TestAllTypes()
test_util.SetAllFields(first_proto)
- serialized = first_proto.SerializeToString()
+ serialized = memoryview(first_proto.SerializeToString())
for truncation_point in range(len(serialized) + 1):
try:
@@ -2857,6 +2864,38 @@ class SerializationTest(BaseTestCase):
self.assertEqual(unittest_pb2.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER,
51)
+ def testFieldProperties(self):
+ cls = unittest_pb2.TestAllTypes
+ self.assertIs(cls.optional_int32.DESCRIPTOR,
+ cls.DESCRIPTOR.fields_by_name['optional_int32'])
+ self.assertEqual(cls.OPTIONAL_INT32_FIELD_NUMBER,
+ cls.optional_int32.DESCRIPTOR.number)
+ self.assertIs(cls.optional_nested_message.DESCRIPTOR,
+ cls.DESCRIPTOR.fields_by_name['optional_nested_message'])
+ self.assertEqual(cls.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER,
+ cls.optional_nested_message.DESCRIPTOR.number)
+ self.assertIs(cls.repeated_int32.DESCRIPTOR,
+ cls.DESCRIPTOR.fields_by_name['repeated_int32'])
+ self.assertEqual(cls.REPEATED_INT32_FIELD_NUMBER,
+ cls.repeated_int32.DESCRIPTOR.number)
+
+ def testFieldDataDescriptor(self):
+ msg = unittest_pb2.TestAllTypes()
+ msg.optional_int32 = 42
+ self.assertEqual(unittest_pb2.TestAllTypes.optional_int32.__get__(msg), 42)
+ unittest_pb2.TestAllTypes.optional_int32.__set__(msg, 25)
+ self.assertEqual(msg.optional_int32, 25)
+ with self.assertRaises(AttributeError):
+ del msg.optional_int32
+ try:
+ unittest_pb2.ForeignMessage.c.__get__(msg)
+ except TypeError:
+ pass # The cpp implementation cannot mix fields from other messages.
+ # This test exercises a specific check that avoids a crash.
+ else:
+ pass # The python implementation allows fields from other messages.
+ # This is useless, but works.
+
def testInitKwargs(self):
proto = unittest_pb2.TestAllTypes(
optional_int32=1,
@@ -2963,6 +3002,7 @@ class ClassAPITest(BaseTestCase):
@unittest.skipIf(
api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
'C++ implementation requires a call to MakeDescriptor()')
+ @testing_refleaks.SkipReferenceLeakChecker('MakeClass is not repeatable')
def testMakeClassWithNestedDescriptor(self):
leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '',
containing_type=None, fields=[],
@@ -2980,10 +3020,7 @@ class ClassAPITest(BaseTestCase):
containing_type=None, fields=[],
nested_types=[child_desc, sibling_desc],
enum_types=[], extensions=[])
- message_class = reflection.MakeClass(parent_desc)
- self.assertIn('child', message_class.__dict__)
- self.assertIn('sibling', message_class.__dict__)
- self.assertIn('leaf', message_class.child.__dict__)
+ reflection.MakeClass(parent_desc)
def _GetSerializedFileDescriptor(self, name):
"""Get a serialized representation of a test FileDescriptorProto.
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py
index 237a2d50..ccf8ac16 100755
--- a/python/google/protobuf/internal/text_format_test.py
+++ b/python/google/protobuf/internal/text_format_test.py
@@ -33,20 +33,19 @@
"""Test for google.protobuf.text_format."""
-__author__ = 'kenton@google.com (Kenton Varda)'
-
-
+import io
import math
import re
-import six
import string
+import textwrap
+
+import six
+# pylint: disable=g-import-not-at-top
try:
- import unittest2 as unittest # PY26, pylint: disable=g-import-not-at-top
+ import unittest2 as unittest # PY26
except ImportError:
- import unittest # pylint: disable=g-import-not-at-top
-
-from google.protobuf.internal import _parameterized
+ import unittest
from google.protobuf import any_pb2
from google.protobuf import any_test_pb2
@@ -54,12 +53,13 @@ from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_mset_pb2
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 message_set_extensions_pb2
from google.protobuf.internal import test_util
from google.protobuf import descriptor_pool
from google.protobuf import text_format
+from google.protobuf.internal import _parameterized
+# pylint: enable=g-import-not-at-top
# Low-level nuts-n-bolts tests.
@@ -100,8 +100,8 @@ class TextFormatBase(unittest.TestCase):
return text
-@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2))
-class TextFormatTest(TextFormatBase):
+@_parameterized.parameters(unittest_pb2, unittest_proto3_arena_pb2)
+class TextFormatMessageToStringTests(TextFormatBase):
def testPrintExotic(self, message_module):
message = message_module.TestAllTypes()
@@ -154,6 +154,40 @@ class TextFormatTest(TextFormatBase):
'repeated_int32: 1 repeated_int32: 1 repeated_int32: 3 '
'repeated_string: "Google" repeated_string: "Zurich"')
+ def VerifyPrintShortFormatRepeatedFields(self, message_module, as_one_line):
+ message = message_module.TestAllTypes()
+ message.repeated_int32.append(1)
+ message.repeated_string.append('Google')
+ message.repeated_string.append('Hello,World')
+ message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_FOO)
+ message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAR)
+ message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAZ)
+ message.optional_nested_message.bb = 3
+ for i in (21, 32):
+ msg = message.repeated_nested_message.add()
+ msg.bb = i
+ expected_ascii = (
+ 'optional_nested_message {\n bb: 3\n}\n'
+ 'repeated_int32: [1]\n'
+ 'repeated_string: "Google"\n'
+ 'repeated_string: "Hello,World"\n'
+ 'repeated_nested_message {\n bb: 21\n}\n'
+ 'repeated_nested_message {\n bb: 32\n}\n'
+ 'repeated_foreign_enum: [FOREIGN_FOO, FOREIGN_BAR, FOREIGN_BAZ]\n')
+ if as_one_line:
+ expected_ascii = expected_ascii.replace('\n ', '').replace('\n', '')
+ actual_ascii = text_format.MessageToString(
+ message, use_short_repeated_primitives=True,
+ as_one_line=as_one_line)
+ self.CompareToGoldenText(actual_ascii, expected_ascii)
+ parsed_message = message_module.TestAllTypes()
+ text_format.Parse(actual_ascii, parsed_message)
+ self.assertEqual(parsed_message, message)
+
+ def tesPrintShortFormatRepeatedFields(self, message_module, as_one_line):
+ self.VerifyPrintShortFormatRepeatedFields(message_module, False)
+ self.VerifyPrintShortFormatRepeatedFields(message_module, True)
+
def testPrintNestedNewLineInStringAsOneLine(self, message_module):
message = message_module.TestAllTypes()
message.optional_string = 'a\nnew\nline'
@@ -213,13 +247,18 @@ class TextFormatTest(TextFormatBase):
def testPrintRawUtf8String(self, message_module):
message = message_module.TestAllTypes()
- message.repeated_string.append(u'\u00fc\ua71f')
+ message.repeated_string.append(u'\u00fc\t\ua71f')
text = text_format.MessageToString(message, as_utf8=True)
- self.CompareToGoldenText(text, 'repeated_string: "\303\274\352\234\237"\n')
+ golden_unicode = u'repeated_string: "\u00fc\\t\ua71f"\n'
+ golden_text = golden_unicode if six.PY3 else golden_unicode.encode('utf-8')
+ # MessageToString always returns a native str.
+ self.CompareToGoldenText(text, golden_text)
parsed_message = message_module.TestAllTypes()
text_format.Parse(text, parsed_message)
- self.assertEqual(message, parsed_message,
- '\n%s != %s' % (message, parsed_message))
+ self.assertEqual(
+ message, parsed_message, '\n%s != %s (%s != %s)' %
+ (message, parsed_message, message.repeated_string[0],
+ parsed_message.repeated_string[0]))
def testPrintFloatFormat(self, message_module):
# Check that float_format argument is passed to sub-message formatting.
@@ -259,6 +298,36 @@ class TextFormatTest(TextFormatBase):
message.c = 123
self.assertEqual('c: 123\n', str(message))
+ def testMessageToStringUnicode(self, message_module):
+ golden_unicode = u'Á short desçription and a 🍌.'
+ golden_bytes = golden_unicode.encode('utf-8')
+ message = message_module.TestAllTypes()
+ message.optional_string = golden_unicode
+ message.optional_bytes = golden_bytes
+ text = text_format.MessageToString(message, as_utf8=True)
+ golden_message = textwrap.dedent(
+ 'optional_string: "Á short desçription and a 🍌."\n'
+ 'optional_bytes: '
+ r'"\303\201 short des\303\247ription and a \360\237\215\214."'
+ '\n')
+ self.CompareToGoldenText(text, golden_message)
+
+ def testMessageToStringASCII(self, message_module):
+ golden_unicode = u'Á short desçription and a 🍌.'
+ golden_bytes = golden_unicode.encode('utf-8')
+ message = message_module.TestAllTypes()
+ message.optional_string = golden_unicode
+ message.optional_bytes = golden_bytes
+ text = text_format.MessageToString(message, as_utf8=False) # ASCII
+ golden_message = (
+ 'optional_string: '
+ r'"\303\201 short des\303\247ription and a \360\237\215\214."'
+ '\n'
+ 'optional_bytes: '
+ r'"\303\201 short des\303\247ription and a \360\237\215\214."'
+ '\n')
+ self.CompareToGoldenText(text, golden_message)
+
def testPrintField(self, message_module):
message = message_module.TestAllTypes()
field = message.DESCRIPTOR.fields_by_name['optional_float']
@@ -289,6 +358,45 @@ class TextFormatTest(TextFormatBase):
self.assertEqual('0.0', out.getvalue())
out.close()
+
+@_parameterized.parameters(unittest_pb2, unittest_proto3_arena_pb2)
+class TextFormatMessageToTextBytesTests(TextFormatBase):
+
+ def testMessageToBytes(self, message_module):
+ message = message_module.ForeignMessage()
+ message.c = 123
+ self.assertEqual(b'c: 123\n', text_format.MessageToBytes(message))
+
+ def testRawUtf8RoundTrip(self, message_module):
+ message = message_module.TestAllTypes()
+ message.repeated_string.append(u'\u00fc\t\ua71f')
+ utf8_text = text_format.MessageToBytes(message, as_utf8=True)
+ golden_bytes = b'repeated_string: "\xc3\xbc\\t\xea\x9c\x9f"\n'
+ self.CompareToGoldenText(utf8_text, golden_bytes)
+ parsed_message = message_module.TestAllTypes()
+ text_format.Parse(utf8_text, parsed_message)
+ self.assertEqual(
+ message, parsed_message, '\n%s != %s (%s != %s)' %
+ (message, parsed_message, message.repeated_string[0],
+ parsed_message.repeated_string[0]))
+
+ def testEscapedUtf8ASCIIRoundTrip(self, message_module):
+ message = message_module.TestAllTypes()
+ message.repeated_string.append(u'\u00fc\t\ua71f')
+ ascii_text = text_format.MessageToBytes(message) # as_utf8=False default
+ golden_bytes = b'repeated_string: "\\303\\274\\t\\352\\234\\237"\n'
+ self.CompareToGoldenText(ascii_text, golden_bytes)
+ parsed_message = message_module.TestAllTypes()
+ text_format.Parse(ascii_text, parsed_message)
+ self.assertEqual(
+ message, parsed_message, '\n%s != %s (%s != %s)' %
+ (message, parsed_message, message.repeated_string[0],
+ parsed_message.repeated_string[0]))
+
+
+@_parameterized.parameters(unittest_pb2, unittest_proto3_arena_pb2)
+class TextFormatParserTests(TextFormatBase):
+
def testParseAllFields(self, message_module):
message = message_module.TestAllTypes()
test_util.SetAllFields(message)
@@ -318,14 +426,14 @@ class TextFormatTest(TextFormatBase):
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é')
+ msg2 = message_module.TestAllTypes()
+ text = (u'optional_string: "café"')
+ text_format.Merge(text, msg2)
+ self.assertEqual(msg2.optional_string, u'café')
+ msg2.Clear()
+ self.assertEqual(msg2.optional_string, u'')
+ text_format.Parse(text, msg2)
+ self.assertEqual(msg2.optional_string, u'café')
def testParseExotic(self, message_module):
message = message_module.TestAllTypes()
@@ -425,7 +533,8 @@ class TextFormatTest(TextFormatBase):
message = message_module.TestAllTypes()
text = 'optional_nested_enum: BARR'
six.assertRaisesRegex(self, text_format.ParseError,
- (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
+ (r'1:23 : \'optional_nested_enum: BARR\': '
+ r'Enum type "\w+.TestAllTypes.NestedEnum" '
r'has no value named BARR.'), text_format.Parse,
text, message)
@@ -433,7 +542,8 @@ class TextFormatTest(TextFormatBase):
message = message_module.TestAllTypes()
text = 'optional_int32: bork'
six.assertRaisesRegex(self, text_format.ParseError,
- ('1:17 : Couldn\'t parse integer: bork'),
+ ('1:17 : \'optional_int32: bork\': '
+ 'Couldn\'t parse integer: bork'),
text_format.Parse, text, message)
def testParseStringFieldUnescape(self, message_module):
@@ -457,6 +567,96 @@ class TextFormatTest(TextFormatBase):
message.repeated_string[4])
self.assertEqual(SLASH + 'x20', message.repeated_string[5])
+ def testParseOneof(self, message_module):
+ m = message_module.TestAllTypes()
+ m.oneof_uint32 = 11
+ m2 = message_module.TestAllTypes()
+ text_format.Parse(text_format.MessageToString(m), m2)
+ self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field'))
+
+ def testParseMultipleOneof(self, message_module):
+ m_string = '\n'.join(['oneof_uint32: 11', 'oneof_string: "foo"'])
+ m2 = message_module.TestAllTypes()
+ with six.assertRaisesRegex(self, text_format.ParseError,
+ ' is specified along with field '):
+ text_format.Parse(m_string, m2)
+
+ # This example contains non-ASCII codepoint unicode data as literals
+ # which should come through as utf-8 for bytes, and as the unicode
+ # itself for string fields. It also demonstrates escaped binary data.
+ # The ur"" string prefix is unfortunately missing from Python 3
+ # so we resort to double escaping our \s so that they come through.
+ _UNICODE_SAMPLE = u"""
+ optional_bytes: 'Á short desçription'
+ optional_string: 'Á short desçription'
+ repeated_bytes: '\\303\\201 short des\\303\\247ription'
+ repeated_bytes: '\\x12\\x34\\x56\\x78\\x90\\xab\\xcd\\xef'
+ repeated_string: '\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82'
+ """
+ _BYTES_SAMPLE = _UNICODE_SAMPLE.encode('utf-8')
+ _GOLDEN_UNICODE = u'Á short desçription'
+ _GOLDEN_BYTES = _GOLDEN_UNICODE.encode('utf-8')
+ _GOLDEN_BYTES_1 = b'\x12\x34\x56\x78\x90\xab\xcd\xef'
+ _GOLDEN_STR_0 = u'Привет'
+
+ def testParseUnicode(self, message_module):
+ m = message_module.TestAllTypes()
+ text_format.Parse(self._UNICODE_SAMPLE, m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+ # repeated_bytes[1] contained simple \ escaped non-UTF-8 raw binary data.
+ self.assertEqual(m.repeated_bytes[1], self._GOLDEN_BYTES_1)
+ # repeated_string[0] contained \ escaped data representing the UTF-8
+ # representation of _GOLDEN_STR_0 - it needs to decode as such.
+ self.assertEqual(m.repeated_string[0], self._GOLDEN_STR_0)
+
+ def testParseBytes(self, message_module):
+ m = message_module.TestAllTypes()
+ text_format.Parse(self._BYTES_SAMPLE, m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+ # repeated_bytes[1] contained simple \ escaped non-UTF-8 raw binary data.
+ self.assertEqual(m.repeated_bytes[1], self._GOLDEN_BYTES_1)
+ # repeated_string[0] contained \ escaped data representing the UTF-8
+ # representation of _GOLDEN_STR_0 - it needs to decode as such.
+ self.assertEqual(m.repeated_string[0], self._GOLDEN_STR_0)
+
+ def testFromBytesFile(self, message_module):
+ m = message_module.TestAllTypes()
+ f = io.BytesIO(self._BYTES_SAMPLE)
+ text_format.ParseLines(f, m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+
+ def testFromUnicodeFile(self, message_module):
+ m = message_module.TestAllTypes()
+ f = io.StringIO(self._UNICODE_SAMPLE)
+ text_format.ParseLines(f, m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+
+ def testFromBytesLines(self, message_module):
+ m = message_module.TestAllTypes()
+ text_format.ParseLines(self._BYTES_SAMPLE.split(b'\n'), m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+
+ def testFromUnicodeLines(self, message_module):
+ m = message_module.TestAllTypes()
+ text_format.ParseLines(self._UNICODE_SAMPLE.split(u'\n'), m)
+ self.assertEqual(m.optional_bytes, self._GOLDEN_BYTES)
+ self.assertEqual(m.optional_string, self._GOLDEN_UNICODE)
+ self.assertEqual(m.repeated_bytes[0], self._GOLDEN_BYTES)
+
+
+@_parameterized.parameters(unittest_pb2, unittest_proto3_arena_pb2)
+class TextFormatMergeTests(TextFormatBase):
+
def testMergeDuplicateScalars(self, message_module):
message = message_module.TestAllTypes()
text = ('optional_int32: 42 ' 'optional_int32: 67')
@@ -472,26 +672,12 @@ class TextFormatTest(TextFormatBase):
self.assertTrue(r is message)
self.assertEqual(2, message.optional_nested_message.bb)
- def testParseOneof(self, message_module):
- m = message_module.TestAllTypes()
- m.oneof_uint32 = 11
- m2 = message_module.TestAllTypes()
- 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()
- with self.assertRaisesRegexp(text_format.ParseError,
- ' is specified along with field '):
- text_format.Parse(m_string, m2)
-
# These are tests that aren't fundamentally specific to proto2, but are at
# the moment because of differences between the proto2 and proto3 test schemas.
@@ -649,6 +835,29 @@ class OnlyWorksWithProto2RightNowTests(TextFormatBase):
' }\n'
'}\n')
+ # In cpp implementation, __str__ calls the cpp implementation of text format.
+ def testPrintMapUsingCppImplementation(self):
+ message = map_unittest_pb2.TestMap()
+ inner_msg = message.map_int32_foreign_message[111]
+ inner_msg.c = 1
+ self.assertEqual(
+ str(message),
+ 'map_int32_foreign_message {\n'
+ ' key: 111\n'
+ ' value {\n'
+ ' c: 1\n'
+ ' }\n'
+ '}\n')
+ inner_msg.c = 2
+ self.assertEqual(
+ str(message),
+ 'map_int32_foreign_message {\n'
+ ' key: 111\n'
+ ' value {\n'
+ ' c: 2\n'
+ ' }\n'
+ '}\n')
+
def testMapOrderEnforcement(self):
message = map_unittest_pb2.TestMap()
for letter in string.ascii_uppercase[13:26]:
@@ -938,7 +1147,7 @@ class Proto2Tests(TextFormatBase):
'}\n')
six.assertRaisesRegex(self,
text_format.ParseError,
- '5:1 : Expected ">".',
+ '5:1 : \'}\': Expected ">".',
text_format.Parse,
malformed,
message,
@@ -981,7 +1190,8 @@ class Proto2Tests(TextFormatBase):
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".')
+ '1:27 : \'optional_nested_message { "bb": 1 }\': '
+ 'Expected identifier or number, got "bb".')
def testParseBadExtension(self):
message = unittest_pb2.TestAllExtensions()
@@ -998,7 +1208,8 @@ class Proto2Tests(TextFormatBase):
message = unittest_pb2.TestAllTypes()
text = 'optional_nested_enum: 100'
six.assertRaisesRegex(self, text_format.ParseError,
- (r'1:23 : Enum type "\w+.TestAllTypes.NestedEnum" '
+ (r'1:23 : \'optional_nested_enum: 100\': '
+ r'Enum type "\w+.TestAllTypes.NestedEnum" '
r'has no value with number 100.'), text_format.Parse,
text, message)
@@ -1209,6 +1420,24 @@ class Proto3Tests(unittest.TestCase):
' < data: "string" > '
'>')
+ def testPrintAndParseMessageInvalidAny(self):
+ packed_message = unittest_pb2.OneString()
+ packed_message.data = 'string'
+ message = any_test_pb2.TestAny()
+ message.any_value.Pack(packed_message)
+ # Only include string after last '/' in type_url.
+ message.any_value.type_url = message.any_value.TypeName()
+ text = text_format.MessageToString(message)
+ self.assertEqual(
+ text, 'any_value {\n'
+ ' type_url: "protobuf_unittest.OneString"\n'
+ ' value: "\\n\\006string"\n'
+ '}\n')
+
+ parsed_message = any_test_pb2.TestAny()
+ text_format.Parse(text, parsed_message)
+ self.assertEqual(message, parsed_message)
+
def testUnknownEnums(self):
message = unittest_proto3_arena_pb2.TestAllTypes()
message2 = unittest_proto3_arena_pb2.TestAllTypes()
@@ -1448,6 +1677,26 @@ class TokenizerTest(unittest.TestCase):
self.assertEqual(0, text_format._ConsumeUint64(tokenizer))
self.assertTrue(tokenizer.AtEnd())
+ def testConsumeOctalIntegers(self):
+ """Test support for C style octal integers."""
+ text = '00 -00 04 0755 -010 007 -0033 08 -09 01'
+ tokenizer = text_format.Tokenizer(text.splitlines())
+ self.assertEqual(0, tokenizer.ConsumeInteger())
+ self.assertEqual(0, tokenizer.ConsumeInteger())
+ self.assertEqual(4, tokenizer.ConsumeInteger())
+ self.assertEqual(0o755, tokenizer.ConsumeInteger())
+ self.assertEqual(-0o10, tokenizer.ConsumeInteger())
+ self.assertEqual(7, tokenizer.ConsumeInteger())
+ self.assertEqual(-0o033, tokenizer.ConsumeInteger())
+ with self.assertRaises(text_format.ParseError):
+ tokenizer.ConsumeInteger() # 08
+ tokenizer.NextToken()
+ with self.assertRaises(text_format.ParseError):
+ tokenizer.ConsumeInteger() # -09
+ tokenizer.NextToken()
+ self.assertEqual(1, tokenizer.ConsumeInteger())
+ self.assertTrue(tokenizer.AtEnd())
+
def testConsumeByteString(self):
text = '"string1\''
tokenizer = text_format.Tokenizer(text.splitlines())
@@ -1556,6 +1805,12 @@ class TokenizerTest(unittest.TestCase):
tokenizer.ConsumeCommentOrTrailingComment())
self.assertTrue(tokenizer.AtEnd())
+ def testHugeString(self):
+ # With pathologic backtracking, fails with Forge OOM.
+ text = '"' + 'a' * (10 * 1024 * 1024) + '"'
+ tokenizer = text_format.Tokenizer(text.splitlines(), skip_comments=False)
+ tokenizer.ConsumeString()
+
# Tests for pretty printer functionality.
@_parameterized.parameters((unittest_pb2), (unittest_proto3_arena_pb2))
@@ -1652,5 +1907,64 @@ class PrettyPrinterTest(TextFormatBase):
'repeated_nested_message { My lucky number is 42 } '
'repeated_nested_message { My lucky number is 99 }'))
+
+class WhitespaceTest(TextFormatBase):
+
+ def setUp(self):
+ self.out = text_format.TextWriter(False)
+ self.addCleanup(self.out.close)
+ self.message = unittest_pb2.NestedTestAllTypes()
+ self.message.child.payload.optional_string = 'value'
+ self.field = self.message.DESCRIPTOR.fields_by_name['child']
+ self.value = self.message.child
+
+ def testMessageToString(self):
+ self.CompareToGoldenText(
+ text_format.MessageToString(self.message),
+ textwrap.dedent("""\
+ child {
+ payload {
+ optional_string: "value"
+ }
+ }
+ """))
+
+ def testPrintMessage(self):
+ text_format.PrintMessage(self.message, self.out)
+ self.CompareToGoldenText(
+ self.out.getvalue(),
+ textwrap.dedent("""\
+ child {
+ payload {
+ optional_string: "value"
+ }
+ }
+ """))
+
+ def testPrintField(self):
+ text_format.PrintField(self.field, self.value, self.out)
+ self.CompareToGoldenText(
+ self.out.getvalue(),
+ textwrap.dedent("""\
+ child {
+ payload {
+ optional_string: "value"
+ }
+ }
+ """))
+
+ def testPrintFieldValue(self):
+ text_format.PrintFieldValue(
+ self.field, self.value, self.out)
+ self.CompareToGoldenText(
+ self.out.getvalue(),
+ textwrap.dedent("""\
+ {
+ payload {
+ optional_string: "value"
+ }
+ }"""))
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/type_checkers.py b/python/google/protobuf/internal/type_checkers.py
index 4a76cd4e..0807e7f7 100755
--- a/python/google/protobuf/internal/type_checkers.py
+++ b/python/google/protobuf/internal/type_checkers.py
@@ -185,6 +185,14 @@ class UnicodeValueChecker(object):
'encoding. Non-UTF-8 strings must be converted to '
'unicode objects before being added.' %
(proposed_value))
+ else:
+ try:
+ proposed_value.encode('utf8')
+ except UnicodeEncodeError:
+ raise ValueError('%.1024r isn\'t a valid unicode string and '
+ 'can\'t be encoded in UTF-8.'%
+ (proposed_value))
+
return proposed_value
def DefaultValue(self):
diff --git a/python/google/protobuf/internal/unknown_fields_test.py b/python/google/protobuf/internal/unknown_fields_test.py
index 8b7de2e7..fceadf71 100755
--- a/python/google/protobuf/internal/unknown_fields_test.py
+++ b/python/google/protobuf/internal/unknown_fields_test.py
@@ -49,20 +49,12 @@ from google.protobuf.internal import missing_enum_values_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import type_checkers
+from google.protobuf import descriptor
BaseTestCase = testing_refleaks.BaseTestCase
-# 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,
- 'Addtional test for pure python involved protect members')(func)
-
-
class UnknownFieldsTest(BaseTestCase):
def setUp(self):
@@ -80,23 +72,11 @@ class UnknownFieldsTest(BaseTestCase):
# stdout.
self.assertTrue(data == self.all_fields_data)
- def expectSerializeProto3(self, preserve):
+ def testSerializeProto3(self):
+ # Verify proto3 unknown fields behavior.
message = unittest_proto3_arena_pb2.TestEmptyMessage()
message.ParseFromString(self.all_fields_data)
- 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)
+ self.assertEqual(self.all_fields_data, message.SerializeToString())
def testByteSize(self):
self.assertEqual(self.all_fields.ByteSize(), self.empty_message.ByteSize())
@@ -169,13 +149,15 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
self.empty_message = unittest_pb2.TestEmptyMessage()
self.empty_message.ParseFromString(self.all_fields_data)
- # CheckUnknownField() is an additional Pure Python check which checks
+ # InternalCheckUnknownField() 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 CheckUnknownField(self, name, expected_value):
+ # TODO(jieluo): Remove message._unknown_fields.
+ def InternalCheckUnknownField(self, name, expected_value):
+ if api_implementation.Type() == 'cpp':
+ return
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)
@@ -183,36 +165,80 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
for tag_bytes, value in self.empty_message._unknown_fields:
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)
+ decoder(memoryview(value), 0, len(value), self.all_fields, result_dict)
self.assertEqual(expected_value, result_dict[field_descriptor])
- @SkipCheckUnknownFieldIfCppImplementation
+ def CheckUnknownField(self, name, unknown_fields, expected_value):
+ field_descriptor = self.descriptor.fields_by_name[name]
+ expected_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[
+ field_descriptor.type]
+ for unknown_field in unknown_fields:
+ if unknown_field.field_number == field_descriptor.number:
+ self.assertEqual(expected_type, unknown_field.wire_type)
+ if expected_type == 3:
+ # Check group
+ self.assertEqual(expected_value[0],
+ unknown_field.data[0].field_number)
+ self.assertEqual(expected_value[1], unknown_field.data[0].wire_type)
+ self.assertEqual(expected_value[2], unknown_field.data[0].data)
+ continue
+ if field_descriptor.label == descriptor.FieldDescriptor.LABEL_REPEATED:
+ self.assertIn(unknown_field.data, expected_value)
+ else:
+ self.assertEqual(expected_value, unknown_field.data)
+
def testCheckUnknownFieldValue(self):
+ unknown_fields = self.empty_message.UnknownFields()
# Test enum.
self.CheckUnknownField('optional_nested_enum',
+ unknown_fields,
self.all_fields.optional_nested_enum)
+ self.InternalCheckUnknownField('optional_nested_enum',
+ self.all_fields.optional_nested_enum)
+
# Test repeated enum.
self.CheckUnknownField('repeated_nested_enum',
+ unknown_fields,
self.all_fields.repeated_nested_enum)
+ self.InternalCheckUnknownField('repeated_nested_enum',
+ self.all_fields.repeated_nested_enum)
# Test varint.
self.CheckUnknownField('optional_int32',
+ unknown_fields,
self.all_fields.optional_int32)
+ self.InternalCheckUnknownField('optional_int32',
+ self.all_fields.optional_int32)
+
# Test fixed32.
self.CheckUnknownField('optional_fixed32',
+ unknown_fields,
self.all_fields.optional_fixed32)
+ self.InternalCheckUnknownField('optional_fixed32',
+ self.all_fields.optional_fixed32)
# Test fixed64.
self.CheckUnknownField('optional_fixed64',
+ unknown_fields,
self.all_fields.optional_fixed64)
+ self.InternalCheckUnknownField('optional_fixed64',
+ self.all_fields.optional_fixed64)
# Test lengthd elimited.
self.CheckUnknownField('optional_string',
- self.all_fields.optional_string)
+ unknown_fields,
+ self.all_fields.optional_string.encode('utf-8'))
+ self.InternalCheckUnknownField('optional_string',
+ self.all_fields.optional_string)
# Test group.
self.CheckUnknownField('optionalgroup',
- self.all_fields.optionalgroup)
+ unknown_fields,
+ (17, 0, 117))
+ self.InternalCheckUnknownField('optionalgroup',
+ self.all_fields.optionalgroup)
+
+ self.assertEqual(97, len(unknown_fields))
def testCopyFrom(self):
message = unittest_pb2.TestEmptyMessage()
@@ -230,9 +256,18 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
message.optional_int64 = 3
message.optional_uint32 = 4
destination = unittest_pb2.TestEmptyMessage()
+ unknown_fields = destination.UnknownFields()
+ self.assertEqual(0, len(unknown_fields))
destination.ParseFromString(message.SerializeToString())
-
+ # ParseFromString clears the message thus unknown fields is invalid.
+ with self.assertRaises(ValueError) as context:
+ len(unknown_fields)
+ self.assertIn('UnknownFields does not exist.',
+ str(context.exception))
+ unknown_fields = destination.UnknownFields()
+ self.assertEqual(2, len(unknown_fields))
destination.MergeFrom(source)
+ self.assertEqual(4, len(unknown_fields))
# Check that the fields where correctly merged, even stored in the unknown
# fields set.
message.ParseFromString(destination.SerializeToString())
@@ -241,9 +276,58 @@ class UnknownFieldsAccessorsTest(BaseTestCase):
self.assertEqual(message.optional_int64, 3)
def testClear(self):
+ unknown_fields = self.empty_message.UnknownFields()
self.empty_message.Clear()
# All cleared, even unknown fields.
self.assertEqual(self.empty_message.SerializeToString(), b'')
+ with self.assertRaises(ValueError) as context:
+ len(unknown_fields)
+ self.assertIn('UnknownFields does not exist.',
+ str(context.exception))
+
+ def testSubUnknownFields(self):
+ message = unittest_pb2.TestAllTypes()
+ message.optionalgroup.a = 123
+ destination = unittest_pb2.TestEmptyMessage()
+ destination.ParseFromString(message.SerializeToString())
+ sub_unknown_fields = destination.UnknownFields()[0].data
+ self.assertEqual(1, len(sub_unknown_fields))
+ self.assertEqual(sub_unknown_fields[0].data, 123)
+ destination.Clear()
+ with self.assertRaises(ValueError) as context:
+ len(sub_unknown_fields)
+ self.assertIn('UnknownFields does not exist.',
+ str(context.exception))
+ with self.assertRaises(ValueError) as context:
+ # pylint: disable=pointless-statement
+ sub_unknown_fields[0]
+ self.assertIn('UnknownFields does not exist.',
+ str(context.exception))
+ message.Clear()
+ message.optional_uint32 = 456
+ nested_message = unittest_pb2.NestedTestAllTypes()
+ nested_message.payload.optional_nested_message.ParseFromString(
+ message.SerializeToString())
+ unknown_fields = (
+ nested_message.payload.optional_nested_message.UnknownFields())
+ self.assertEqual(unknown_fields[0].data, 456)
+ nested_message.ClearField('payload')
+ self.assertEqual(unknown_fields[0].data, 456)
+ unknown_fields = (
+ nested_message.payload.optional_nested_message.UnknownFields())
+ self.assertEqual(0, len(unknown_fields))
+
+ def testUnknownField(self):
+ message = unittest_pb2.TestAllTypes()
+ message.optional_int32 = 123
+ destination = unittest_pb2.TestEmptyMessage()
+ destination.ParseFromString(message.SerializeToString())
+ unknown_field = destination.UnknownFields()[0]
+ destination.Clear()
+ with self.assertRaises(ValueError) as context:
+ unknown_field.data # pylint: disable=pointless-statement
+ self.assertIn('The parent message might be cleared.',
+ str(context.exception))
def testUnknownExtensions(self):
message = unittest_pb2.TestEmptyMessageWithExtensions()
@@ -280,15 +364,13 @@ class UnknownEnumValuesTest(BaseTestCase):
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)
- result_dict = {}
- for tag_bytes, value in self.missing_message._unknown_fields:
- if tag_bytes == field_tag:
- decoder = missing_enum_values_pb2.TestEnumValues._decoders_by_tag[
- tag_bytes][0]
- decoder(value, 0, len(value), self.message, result_dict)
- self.assertEqual(expected_value, result_dict[field_descriptor])
+ unknown_fields = self.missing_message.UnknownFields()
+ for field in unknown_fields:
+ if field.field_number == field_descriptor.number:
+ if field_descriptor.label == descriptor.FieldDescriptor.LABEL_REPEATED:
+ self.assertIn(field.data, expected_value)
+ else:
+ self.assertEqual(expected_value, field.data)
def testUnknownParseMismatchEnumValue(self):
just_string = missing_enum_values_pb2.JustString()
@@ -317,7 +399,6 @@ class UnknownEnumValuesTest(BaseTestCase):
def testUnknownPackedEnumValue(self):
self.assertEqual([], self.missing_message.packed_nested_enum)
- @SkipCheckUnknownFieldIfCppImplementation
def testCheckUnknownFieldValueForEnum(self):
self.CheckUnknownField('optional_nested_enum',
self.message.optional_nested_enum)
diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py
index 37a65cfa..95c5615f 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 calendar
import collections
from datetime import datetime
from datetime import timedelta
@@ -92,7 +93,7 @@ class Any(object):
def Is(self, descriptor):
"""Checks if this Any represents the given protobuf type."""
- return self.TypeName() == descriptor.full_name
+ return '/' in self.type_url and self.TypeName() == descriptor.full_name
class Timestamp(object):
@@ -233,9 +234,15 @@ class Timestamp(object):
def FromDatetime(self, dt):
"""Converts datetime to Timestamp."""
- td = dt - datetime(1970, 1, 1)
- self.seconds = td.seconds + td.days * _SECONDS_PER_DAY
- self.nanos = td.microseconds * _NANOS_PER_MICROSECOND
+ # Using this guide: http://wiki.python.org/moin/WorkingWithTime
+ # And this conversion guide: http://docs.python.org/library/time.html
+
+ # Turn the date parameter into a tuple (struct_time) that can then be
+ # manipulated into a long value of seconds. During the conversion from
+ # struct_time to long, the source date in UTC, and so it follows that the
+ # correct transformation is calendar.timegm()
+ self.seconds = calendar.timegm(dt.utctimetuple())
+ self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND
class Duration(object):
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py
index 965940b2..4dc2ae4f 100644
--- a/python/google/protobuf/internal/well_known_types_test.py
+++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -35,7 +35,7 @@
__author__ = 'jieluo@google.com (Jie Luo)'
import collections
-from datetime import datetime
+import datetime
try:
import unittest2 as unittest #PY26
@@ -240,14 +240,34 @@ class TimeUtilTest(TimeUtilTestBase):
def testDatetimeConverison(self):
message = timestamp_pb2.Timestamp()
- dt = datetime(1970, 1, 1)
+ dt = datetime.datetime(1970, 1, 1)
message.FromDatetime(dt)
self.assertEqual(dt, message.ToDatetime())
message.FromMilliseconds(1999)
- self.assertEqual(datetime(1970, 1, 1, 0, 0, 1, 999000),
+ self.assertEqual(datetime.datetime(1970, 1, 1, 0, 0, 1, 999000),
message.ToDatetime())
+ def testDatetimeConversionWithTimezone(self):
+ class TZ(datetime.tzinfo):
+
+ def utcoffset(self, _):
+ return datetime.timedelta(hours=1)
+
+ def dst(self, _):
+ return datetime.timedelta(0)
+
+ def tzname(self, _):
+ return 'UTC+1'
+
+ message1 = timestamp_pb2.Timestamp()
+ dt = datetime.datetime(1970, 1, 1, 1, tzinfo=TZ())
+ message1.FromDatetime(dt)
+ message2 = timestamp_pb2.Timestamp()
+ dt = datetime.datetime(1970, 1, 1, 0)
+ message2.FromDatetime(dt)
+ self.assertEqual(message1, message2)
+
def testTimedeltaConversion(self):
message = duration_pb2.Duration()
message.FromNanoseconds(1999999999)
@@ -879,6 +899,17 @@ class AnyTest(unittest.TestCase):
raise AttributeError('%s should not have Pack method.' %
msg_descriptor.full_name)
+ def testUnpackWithNoSlashInTypeUrl(self):
+ msg = any_test_pb2.TestAny()
+ all_types = unittest_pb2.TestAllTypes()
+ all_descriptor = all_types.DESCRIPTOR
+ msg.value.Pack(all_types)
+ # Reset type_url to part of type_url after '/'
+ msg.value.type_url = msg.value.TypeName()
+ self.assertFalse(msg.value.Is(all_descriptor))
+ unpacked_message = unittest_pb2.TestAllTypes()
+ self.assertFalse(msg.value.Unpack(unpacked_message))
+
def testMessageName(self):
# Creates and sets message.
submessage = any_test_pb2.TestAny()
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index 8d338d3e..ce1db7d7 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -396,11 +396,7 @@ def Parse(text, message, ignore_unknown_fields=False):
"""
if not isinstance(text, six.text_type): text = text.decode('utf-8')
try:
- if sys.version_info < (2, 7):
- # object_pair_hook is not supported before python2.7
- js = json.loads(text)
- else:
- js = json.loads(text, object_pairs_hook=_DuplicateChecker)
+ js = json.loads(text, object_pairs_hook=_DuplicateChecker)
except ValueError as e:
raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
return ParseDict(js, message, ignore_unknown_fields)
@@ -486,7 +482,7 @@ class _Parser(object):
('Message type "{0}" has no field named "{1}".\n'
' Available Fields(except extensions): {2}').format(
message_descriptor.full_name, name,
- message_descriptor.fields))
+ [f.json_name for f in message_descriptor.fields]))
if name in names:
raise ParseError('Message type "{0}" should not have multiple '
'"{1}" fields.'.format(
diff --git a/python/google/protobuf/message.py b/python/google/protobuf/message.py
index eeb0d576..eca2e0a9 100755
--- a/python/google/protobuf/message.py
+++ b/python/google/protobuf/message.py
@@ -268,6 +268,10 @@ class Message(object):
def ClearExtension(self, extension_handle):
raise NotImplementedError
+ def UnknownFields(self):
+ """Returns the UnknownFieldSet."""
+ raise NotImplementedError
+
def DiscardUnknownFields(self):
raise NotImplementedError
diff --git a/python/google/protobuf/message_factory.py b/python/google/protobuf/message_factory.py
index e4fb065e..f3ab0a55 100644
--- a/python/google/protobuf/message_factory.py
+++ b/python/google/protobuf/message_factory.py
@@ -39,9 +39,18 @@ my_proto_instance = message_classes['some.proto.package.MessageName']()
__author__ = 'matthewtoia@google.com (Matt Toia)'
+from google.protobuf.internal import api_implementation
from google.protobuf import descriptor_pool
from google.protobuf import message
-from google.protobuf import reflection
+
+if api_implementation.Type() == 'cpp':
+ from google.protobuf.pyext import cpp_message as message_impl
+else:
+ from google.protobuf.internal import python_message as message_impl
+
+
+# The type of all Message classes.
+_GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType
class MessageFactory(object):
@@ -70,11 +79,11 @@ class MessageFactory(object):
descriptor_name = descriptor.name
if str is bytes: # PY2
descriptor_name = descriptor.name.encode('ascii', 'ignore')
- result_class = reflection.GeneratedProtocolMessageType(
+ result_class = _GENERATED_PROTOCOL_MESSAGE_TYPE(
descriptor_name,
(message.Message,),
{'DESCRIPTOR': descriptor, '__module__': None})
- # If module not set, it wrongly points to the reflection.py module.
+ # If module not set, it wrongly points to message_factory module.
self._classes[descriptor] = result_class
for field in descriptor.fields:
if field.message_type:
diff --git a/python/google/protobuf/proto_api.h b/python/google/protobuf/proto_api.h
new file mode 100644
index 00000000..47edf0ea
--- /dev/null
+++ b/python/google/protobuf/proto_api.h
@@ -0,0 +1,91 @@
+// 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 can be included by other C++ libraries, typically extension modules
+// which want to interact with the Python Messages coming from the "cpp"
+// implementation of protocol buffers.
+//
+// Usage:
+// Declare a (probably static) variable to hold the API:
+// const PyProto_API* py_proto_api;
+// In some initialization function, write:
+// py_proto_api = static_cast<const PyProto_API*>(PyCapsule_Import(
+// PyProtoAPICapsuleName(), 0));
+// if (!py_proto_api) { ...handle ImportError... }
+// Then use the methods of the returned class:
+// py_proto_api->GetMessagePointer(...);
+
+#ifndef GOOGLE_PROTOBUF_PYTHON_PROTO_API_H__
+#define GOOGLE_PROTOBUF_PYTHON_PROTO_API_H__
+
+#include <Python.h>
+
+#include <google/protobuf/message.h>
+
+namespace google {
+namespace protobuf {
+namespace python {
+
+// Note on the implementation:
+// This API is designed after
+// https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
+// The class below contains no mutable state, and all methods are "const";
+// we use a C++ class instead of a C struct with functions pointers just because
+// the code looks more readable.
+struct PyProto_API {
+ // The API object is created at initialization time and never freed.
+ // This destructor is never called.
+ virtual ~PyProto_API() {}
+
+ // Operations on Messages.
+
+ // If the passed object is a Python Message, returns its internal pointer.
+ // Otherwise, returns NULL with an exception set.
+ virtual const Message* GetMessagePointer(PyObject* msg) const = 0;
+
+ // If the passed object is a Python Message, returns a mutable pointer.
+ // Otherwise, returns NULL with an exception set.
+ // This function will succeed only if there are no other Python objects
+ // pointing to the message, like submessages or repeated containers.
+ // With the current implementation, only empty messages are in this case.
+ virtual Message* GetMutableMessagePointer(PyObject* msg) const = 0;
+};
+
+inline const char* PyProtoAPICapsuleName() {
+ static const char kCapsuleName[] =
+ "google.protobuf.pyext._message.proto_API";
+ return kCapsuleName;
+}
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_PYTHON_PROTO_API_H__
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index 8af0cb12..3cb16b74 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -32,8 +32,8 @@
#include <Python.h>
#include <frameobject.h>
-#include <google/protobuf/stubs/hash.h>
#include <string>
+#include <unordered_map>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/descriptor.pb.h>
@@ -44,6 +44,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
@@ -54,10 +55,12 @@
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
- #define PyString_AsStringAndSize(ob, charpp, sizep) \
- (PyUnicode_Check(ob)? \
- ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
- PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
+ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
+ ? -1 \
+ : 0) \
+ : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
@@ -70,7 +73,7 @@ namespace python {
// released.
// This is enough to support the "is" operator on live objects.
// All descriptors are stored here.
-hash_map<const void*, PyObject*> interned_descriptors;
+std::unordered_map<const void*, PyObject*>* interned_descriptors;
PyObject* PyString_FromCppString(const string& str) {
return PyString_FromStringAndSize(str.c_str(), str.size());
@@ -119,8 +122,10 @@ bool _CalledFromGeneratedFile(int stacklevel) {
PyErr_Clear();
return false;
}
- if ((filename_size < 3) || (strcmp(&filename[filename_size - 3], ".py") != 0)) {
- // Cython's stack does not have .py file name and is not at global module scope.
+ if ((filename_size < 3) ||
+ (strcmp(&filename[filename_size - 3], ".py") != 0)) {
+ // Cython's stack does not have .py file name and is not at global module
+ // scope.
return true;
}
if (filename_size < 7) {
@@ -131,7 +136,7 @@ bool _CalledFromGeneratedFile(int stacklevel) {
// Filename is not ending with _pb2.
return false;
}
-
+
if (frame->f_globals != frame->f_locals) {
// Not at global module scope
return false;
@@ -197,7 +202,7 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
// First search in the cache.
PyDescriptorPool* caching_pool = GetDescriptorPool_FromPool(
GetFileDescriptor(descriptor)->pool());
- hash_map<const void*, PyObject*>* descriptor_options =
+ std::unordered_map<const void*, PyObject*>* descriptor_options =
caching_pool->descriptor_options;
if (descriptor_options->find(descriptor) != descriptor_options->end()) {
PyObject *value = (*descriptor_options)[descriptor];
@@ -232,7 +237,7 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
if (value == NULL) {
return NULL;
}
- if (!PyObject_TypeCheck(value.get(), &CMessage_Type)) {
+ if (!PyObject_TypeCheck(value.get(), CMessage_Type)) {
PyErr_Format(PyExc_TypeError, "Invalid class for %s: %s",
message_type->full_name().c_str(),
Py_TYPE(value.get())->tp_name);
@@ -275,7 +280,7 @@ static PyObject* CopyToPythonProto(const DescriptorClass *descriptor,
const Descriptor* self_descriptor =
DescriptorProtoClass::default_instance().GetDescriptor();
CMessage* message = reinterpret_cast<CMessage*>(target);
- if (!PyObject_TypeCheck(target, &CMessage_Type) ||
+ if (!PyObject_TypeCheck(target, CMessage_Type) ||
message->message->GetDescriptor() != self_descriptor) {
PyErr_Format(PyExc_TypeError, "Not a %s message",
self_descriptor->full_name().c_str());
@@ -332,9 +337,9 @@ PyObject* NewInternedDescriptor(PyTypeObject* type,
}
// See if the object is in the map of interned descriptors
- hash_map<const void*, PyObject*>::iterator it =
- interned_descriptors.find(descriptor);
- if (it != interned_descriptors.end()) {
+ std::unordered_map<const void*, PyObject*>::iterator it =
+ interned_descriptors->find(descriptor);
+ if (it != interned_descriptors->end()) {
GOOGLE_DCHECK(Py_TYPE(it->second) == type);
Py_INCREF(it->second);
return it->second;
@@ -348,7 +353,7 @@ PyObject* NewInternedDescriptor(PyTypeObject* type,
py_descriptor->descriptor = descriptor;
// and cache it.
- interned_descriptors.insert(
+ interned_descriptors->insert(
std::make_pair(descriptor, reinterpret_cast<PyObject*>(py_descriptor)));
// Ensures that the DescriptorPool stays alive.
@@ -370,7 +375,7 @@ PyObject* NewInternedDescriptor(PyTypeObject* type,
static void Dealloc(PyBaseDescriptor* self) {
// Remove from interned dictionary
- interned_descriptors.erase(self->descriptor);
+ interned_descriptors->erase(self->descriptor);
Py_CLEAR(self->pool);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
@@ -758,6 +763,11 @@ static PyObject* HasDefaultValue(PyBaseDescriptor *self, void *closure) {
static PyObject* GetDefaultValue(PyBaseDescriptor *self, void *closure) {
PyObject *result;
+ if (_GetDescriptor(self)->is_repeated()) {
+ return PyList_New(0);
+ }
+
+
switch (_GetDescriptor(self)->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32: {
int32 value = _GetDescriptor(self)->default_value_int32();
@@ -805,6 +815,10 @@ static PyObject* GetDefaultValue(PyBaseDescriptor *self, void *closure) {
result = PyInt_FromLong(value->number());
break;
}
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
+ Py_RETURN_NONE;
+ break;
+ }
default:
PyErr_Format(PyExc_NotImplementedError, "default value for %s",
_GetDescriptor(self)->full_name().c_str());
@@ -1919,6 +1933,9 @@ bool InitDescriptor() {
if (!InitDescriptorMappingTypes())
return false;
+ // Initialize globals defined in this file.
+ interned_descriptors = new std::unordered_map<const void*, PyObject*>;
+
return true;
}
diff --git a/python/google/protobuf/pyext/descriptor.h b/python/google/protobuf/pyext/descriptor.h
index f081df84..c4dde9e7 100644
--- a/python/google/protobuf/pyext/descriptor.h
+++ b/python/google/protobuf/pyext/descriptor.h
@@ -100,6 +100,6 @@ bool InitDescriptor();
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_H__
diff --git a/python/google/protobuf/pyext/descriptor_containers.cc b/python/google/protobuf/pyext/descriptor_containers.cc
index bc007f7e..d5b5dc68 100644
--- a/python/google/protobuf/pyext/descriptor_containers.cc
+++ b/python/google/protobuf/pyext/descriptor_containers.cc
@@ -33,7 +33,7 @@
//
// They avoid the allocation of a full dictionary or a full list: they simply
// store a pointer to the parent descriptor, use the C++ Descriptor methods (see
-// google/protobuf/descriptor.h) to retrieve other descriptors, and create
+// net/proto2/public/descriptor.h) to retrieve other descriptors, and create
// Python objects on the fly.
//
// The containers fully conform to abc.Mapping and abc.Sequence, and behave just
@@ -64,10 +64,12 @@
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
- #define PyString_AsStringAndSize(ob, charpp, sizep) \
- (PyUnicode_Check(ob)? \
- ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
- PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
+ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
+ ? -1 \
+ : 0) \
+ : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
diff --git a/python/google/protobuf/pyext/descriptor_containers.h b/python/google/protobuf/pyext/descriptor_containers.h
index 83de07b6..4e05c58e 100644
--- a/python/google/protobuf/pyext/descriptor_containers.h
+++ b/python/google/protobuf/pyext/descriptor_containers.h
@@ -104,6 +104,6 @@ PyObject* NewServiceMethodsByName(const ServiceDescriptor* descriptor);
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_CONTAINERS_H__
diff --git a/python/google/protobuf/pyext/descriptor_database.cc b/python/google/protobuf/pyext/descriptor_database.cc
index daa40cc7..0514b35c 100644
--- a/python/google/protobuf/pyext/descriptor_database.cc
+++ b/python/google/protobuf/pyext/descriptor_database.cc
@@ -70,7 +70,7 @@ static bool GetFileDescriptorProto(PyObject* py_descriptor,
const Descriptor* filedescriptor_descriptor =
FileDescriptorProto::default_instance().GetDescriptor();
CMessage* message = reinterpret_cast<CMessage*>(py_descriptor);
- if (PyObject_TypeCheck(py_descriptor, &CMessage_Type) &&
+ if (PyObject_TypeCheck(py_descriptor, CMessage_Type) &&
message->message->GetDescriptor() == filedescriptor_descriptor) {
// Fast path: Just use the pointer.
FileDescriptorProto* file_proto =
@@ -143,6 +143,43 @@ bool PyDescriptorDatabase::FindFileContainingExtension(
return GetFileDescriptorProto(py_descriptor.get(), output);
}
+// Finds the tag numbers used by all known extensions of
+// containing_type, and appends them to output in an undefined
+// order.
+// Python DescriptorDatabases are not required to implement this method.
+bool PyDescriptorDatabase::FindAllExtensionNumbers(
+ const string& containing_type, std::vector<int>* output) {
+ ScopedPyObjectPtr py_method(
+ PyObject_GetAttrString(py_database_, "FindAllExtensionNumbers"));
+ if (py_method == NULL) {
+ // This method is not implemented, returns without error.
+ PyErr_Clear();
+ return false;
+ }
+ ScopedPyObjectPtr py_list(
+ PyObject_CallFunction(py_method.get(), "s#", containing_type.c_str(),
+ containing_type.size()));
+ if (py_list == NULL) {
+ PyErr_Print();
+ return false;
+ }
+ Py_ssize_t size = PyList_Size(py_list.get());
+ int64 item_value;
+ for (Py_ssize_t i = 0 ; i < size; ++i) {
+ ScopedPyObjectPtr item(PySequence_GetItem(py_list.get(), i));
+ item_value = PyLong_AsLong(item.get());
+ if (item_value < 0) {
+ GOOGLE_LOG(ERROR)
+ << "FindAllExtensionNumbers method did not return "
+ << "valid extension numbers.";
+ PyErr_Print();
+ return false;
+ }
+ output->push_back(item_value);
+ }
+ return true;
+}
+
} // namespace python
} // namespace protobuf
} // namespace google
diff --git a/python/google/protobuf/pyext/descriptor_database.h b/python/google/protobuf/pyext/descriptor_database.h
index fc71c4bc..30aa1b73 100644
--- a/python/google/protobuf/pyext/descriptor_database.h
+++ b/python/google/protobuf/pyext/descriptor_database.h
@@ -48,21 +48,28 @@ class PyDescriptorDatabase : public DescriptorDatabase {
// with a copy of FileDescriptorProto.
// Find a file by file name.
- bool FindFileByName(const string& filename,
+ bool FindFileByName(const std::string& filename,
FileDescriptorProto* output);
// Find the file that declares the given fully-qualified symbol name.
- bool FindFileContainingSymbol(const string& symbol_name,
+ bool FindFileContainingSymbol(const std::string& symbol_name,
FileDescriptorProto* output);
// Find the file which defines an extension extending the given message type
// with the given field number.
// Containing_type must be a fully-qualified type name.
// Python objects are not required to implement this method.
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
FileDescriptorProto* output);
+ // Finds the tag numbers used by all known extensions of
+ // containing_type, and appends them to output in an undefined
+ // order.
+ // Python objects are not required to implement this method.
+ bool FindAllExtensionNumbers(const std::string& containing_type,
+ std::vector<int>* output);
+
private:
// The python object that implements the database. The reference is owned.
PyObject* py_database_;
@@ -70,6 +77,6 @@ class PyDescriptorDatabase : public DescriptorDatabase {
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_DATABASE_H__
diff --git a/python/google/protobuf/pyext/descriptor_pool.cc b/python/google/protobuf/pyext/descriptor_pool.cc
index 95882aeb..d0038b10 100644
--- a/python/google/protobuf/pyext/descriptor_pool.cc
+++ b/python/google/protobuf/pyext/descriptor_pool.cc
@@ -30,6 +30,8 @@
// Implements the DescriptorPool, which collects all descriptors.
+#include <unordered_map>
+
#include <Python.h>
#include <google/protobuf/descriptor.pb.h>
@@ -46,10 +48,12 @@
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
- #define PyString_AsStringAndSize(ob, charpp, sizep) \
- (PyUnicode_Check(ob)? \
- ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
- PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
+ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
+ ? -1 \
+ : 0) \
+ : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
@@ -58,7 +62,8 @@ namespace python {
// A map to cache Python Pools per C++ pointer.
// Pointers are not owned here, and belong to the PyDescriptorPool.
-static hash_map<const DescriptorPool*, PyDescriptorPool*> descriptor_pool_map;
+static std::unordered_map<const DescriptorPool*, PyDescriptorPool*>*
+ descriptor_pool_map;
namespace cdescriptor_pool {
@@ -74,8 +79,7 @@ static PyDescriptorPool* _CreateDescriptorPool() {
cpool->underlay = NULL;
cpool->database = NULL;
- cpool->descriptor_options =
- new hash_map<const void*, PyObject *>();
+ cpool->descriptor_options = new std::unordered_map<const void*, PyObject*>();
cpool->py_message_factory = message_factory::NewMessageFactory(
&PyMessageFactory_Type, cpool);
@@ -101,7 +105,7 @@ static PyDescriptorPool* PyDescriptorPool_NewWithUnderlay(
cpool->pool = new DescriptorPool(underlay);
cpool->underlay = underlay;
- if (!descriptor_pool_map.insert(
+ if (!descriptor_pool_map->insert(
std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
@@ -124,7 +128,7 @@ static PyDescriptorPool* PyDescriptorPool_NewWithDatabase(
cpool->pool = new DescriptorPool();
}
- if (!descriptor_pool_map.insert(std::make_pair(cpool->pool, cpool)).second) {
+ if (!descriptor_pool_map->insert(std::make_pair(cpool->pool, cpool)).second) {
// Should never happen -- would indicate an internal error / bug.
PyErr_SetString(PyExc_ValueError, "DescriptorPool already registered");
return NULL;
@@ -151,9 +155,9 @@ static PyObject* New(PyTypeObject* type,
static void Dealloc(PyObject* pself) {
PyDescriptorPool* self = reinterpret_cast<PyDescriptorPool*>(pself);
- descriptor_pool_map.erase(self->pool);
+ descriptor_pool_map->erase(self->pool);
Py_CLEAR(self->py_message_factory);
- for (hash_map<const void*, PyObject*>::iterator it =
+ for (std::unordered_map<const void*, PyObject*>::iterator it =
self->descriptor_options->begin();
it != self->descriptor_options->end(); ++it) {
Py_DECREF(it->second);
@@ -180,6 +184,7 @@ static PyObject* FindMessageByName(PyObject* self, PyObject* arg) {
return NULL;
}
+
return PyMessageDescriptor_FromDescriptor(message_descriptor);
}
@@ -218,6 +223,7 @@ PyObject* FindFieldByName(PyDescriptorPool* self, PyObject* arg) {
return NULL;
}
+
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
@@ -239,6 +245,7 @@ PyObject* FindExtensionByName(PyDescriptorPool* self, PyObject* arg) {
return NULL;
}
+
return PyFieldDescriptor_FromDescriptor(field_descriptor);
}
@@ -260,6 +267,7 @@ PyObject* FindEnumTypeByName(PyDescriptorPool* self, PyObject* arg) {
return NULL;
}
+
return PyEnumDescriptor_FromDescriptor(enum_descriptor);
}
@@ -281,6 +289,7 @@ PyObject* FindOneofByName(PyDescriptorPool* self, PyObject* arg) {
return NULL;
}
+
return PyOneofDescriptor_FromDescriptor(oneof_descriptor);
}
@@ -303,6 +312,7 @@ static PyObject* FindServiceByName(PyObject* self, PyObject* arg) {
return NULL;
}
+
return PyServiceDescriptor_FromDescriptor(service_descriptor);
}
@@ -321,6 +331,7 @@ static PyObject* FindMethodByName(PyObject* self, PyObject* arg) {
return NULL;
}
+
return PyMethodDescriptor_FromDescriptor(method_descriptor);
}
@@ -339,6 +350,7 @@ static PyObject* FindFileContainingSymbol(PyObject* self, PyObject* arg) {
return NULL;
}
+
return PyFileDescriptor_FromDescriptor(file_descriptor);
}
@@ -362,6 +374,7 @@ static PyObject* FindExtensionByNumber(PyObject* self, PyObject* args) {
return NULL;
}
+
return PyFieldDescriptor_FromDescriptor(extension_descriptor);
}
@@ -668,13 +681,17 @@ bool InitDescriptorPool() {
// The Pool of messages declared in Python libraries.
// generated_pool() contains all messages already linked in C++ libraries, and
// is used as underlay.
+ descriptor_pool_map =
+ new std::unordered_map<const DescriptorPool*, PyDescriptorPool*>;
python_generated_pool = cdescriptor_pool::PyDescriptorPool_NewWithUnderlay(
DescriptorPool::generated_pool());
if (python_generated_pool == NULL) {
+ delete descriptor_pool_map;
return false;
}
+
// Register this pool to be found for C++-generated descriptors.
- descriptor_pool_map.insert(
+ descriptor_pool_map->insert(
std::make_pair(DescriptorPool::generated_pool(),
python_generated_pool));
@@ -695,9 +712,9 @@ PyDescriptorPool* GetDescriptorPool_FromPool(const DescriptorPool* pool) {
pool == DescriptorPool::generated_pool()) {
return python_generated_pool;
}
- hash_map<const DescriptorPool*, PyDescriptorPool*>::iterator it =
- descriptor_pool_map.find(pool);
- if (it == descriptor_pool_map.end()) {
+ std::unordered_map<const DescriptorPool*, PyDescriptorPool*>::iterator it =
+ descriptor_pool_map->find(pool);
+ if (it == descriptor_pool_map->end()) {
PyErr_SetString(PyExc_KeyError, "Unknown descriptor pool");
return NULL;
}
diff --git a/python/google/protobuf/pyext/descriptor_pool.h b/python/google/protobuf/pyext/descriptor_pool.h
index 53ee53dc..8e7b4d6b 100644
--- a/python/google/protobuf/pyext/descriptor_pool.h
+++ b/python/google/protobuf/pyext/descriptor_pool.h
@@ -33,7 +33,7 @@
#include <Python.h>
-#include <google/protobuf/stubs/hash.h>
+#include <unordered_map>
#include <google/protobuf/descriptor.h>
namespace google {
@@ -77,7 +77,7 @@ typedef struct PyDescriptorPool {
// Cache the options for any kind of descriptor.
// Descriptor pointers are owned by the DescriptorPool above.
// Python objects are owned by the map.
- hash_map<const void*, PyObject*>* descriptor_options;
+ std::unordered_map<const void*, PyObject*>* descriptor_options;
} PyDescriptorPool;
@@ -89,7 +89,7 @@ namespace cdescriptor_pool {
// Looks up a message by name.
// Returns a message Descriptor, or NULL if not found.
const Descriptor* FindMessageTypeByName(PyDescriptorPool* self,
- const string& name);
+ const std::string& name);
// The functions below are also exposed as methods of the DescriptorPool type.
@@ -140,6 +140,6 @@ bool InitDescriptorPool();
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_DESCRIPTOR_POOL_H__
diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc
index 018b5c2c..b73368eb 100644
--- a/python/google/protobuf/pyext/extension_dict.cc
+++ b/python/google/protobuf/pyext/extension_dict.cc
@@ -51,10 +51,12 @@
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#endif
- #define PyString_AsStringAndSize(ob, charpp, sizep) \
- (PyUnicode_Check(ob)? \
- ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
- PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
+ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
+ ? -1 \
+ : 0) \
+ : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
namespace google {
@@ -63,40 +65,25 @@ namespace python {
namespace extension_dict {
-PyObject* len(ExtensionDict* self) {
-#if PY_MAJOR_VERSION >= 3
- return PyLong_FromLong(PyDict_Size(self->values));
-#else
- return PyInt_FromLong(PyDict_Size(self->values));
-#endif
-}
-
PyObject* subscript(ExtensionDict* self, PyObject* key) {
const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
if (descriptor == NULL) {
return NULL;
}
- if (!CheckFieldBelongsToMessage(descriptor, self->message)) {
+ if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) {
return NULL;
}
if (descriptor->label() != FieldDescriptor::LABEL_REPEATED &&
descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
- return cmessage::InternalGetScalar(self->message, descriptor);
+ return cmessage::InternalGetScalar(self->parent->message, descriptor);
}
- PyObject* value = PyDict_GetItem(self->values, key);
- if (value != NULL) {
- Py_INCREF(value);
- return value;
- }
-
- if (self->parent == NULL) {
- // We are in "detached" state. Don't allow further modifications.
- // TODO(amauryfa): Support adding non-scalars to a detached extension dict.
- // This probably requires to store the type of the main message.
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
+ CMessage::CompositeFieldsMap::iterator iterator =
+ self->parent->composite_fields->find(descriptor);
+ if (iterator != self->parent->composite_fields->end()) {
+ Py_INCREF(iterator->second);
+ return iterator->second;
}
if (descriptor->label() != FieldDescriptor::LABEL_REPEATED &&
@@ -107,7 +94,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
if (sub_message == NULL) {
return NULL;
}
- PyDict_SetItem(self->values, key, sub_message);
+ Py_INCREF(sub_message);
+ (*self->parent->composite_fields)[descriptor] = sub_message;
return sub_message;
}
@@ -136,7 +124,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
if (py_container == NULL) {
return NULL;
}
- PyDict_SetItem(self->values, key, py_container);
+ Py_INCREF(py_container);
+ (*self->parent->composite_fields)[descriptor] = py_container;
return py_container;
} else {
PyObject* py_container = repeated_scalar_container::NewContainer(
@@ -144,7 +133,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
if (py_container == NULL) {
return NULL;
}
- PyDict_SetItem(self->values, key, py_container);
+ Py_INCREF(py_container);
+ (*self->parent->composite_fields)[descriptor] = py_container;
return py_container;
}
}
@@ -157,7 +147,7 @@ int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value) {
if (descriptor == NULL) {
return -1;
}
- if (!CheckFieldBelongsToMessage(descriptor, self->message)) {
+ if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) {
return -1;
}
@@ -167,14 +157,10 @@ int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value) {
"type");
return -1;
}
- if (self->parent) {
- cmessage::AssureWritable(self->parent);
- if (cmessage::InternalSetScalar(self->parent, descriptor, value) < 0) {
- return -1;
- }
+ cmessage::AssureWritable(self->parent);
+ if (cmessage::InternalSetScalar(self->parent, descriptor, value) < 0) {
+ return -1;
}
- // TODO(tibell): We shouldn't write scalars to the cache.
- PyDict_SetItem(self->values, key, value);
return 0;
}
@@ -232,22 +218,36 @@ ExtensionDict* NewExtensionDict(CMessage *parent) {
return NULL;
}
- self->parent = parent; // Store a borrowed reference.
- self->message = parent->message;
- self->owner = parent->owner;
- self->values = PyDict_New();
+ Py_INCREF(parent);
+ self->parent = parent;
return self;
}
void dealloc(ExtensionDict* self) {
- Py_CLEAR(self->values);
- self->owner.reset();
+ Py_CLEAR(self->parent);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
+static PyObject* RichCompare(ExtensionDict* self, PyObject* other, int opid) {
+ // Only equality comparisons are implemented.
+ if (opid != Py_EQ && opid != Py_NE) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ bool equals = false;
+ if (PyObject_TypeCheck(other, &ExtensionDict_Type)) {
+ equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent;;
+ }
+ if (equals ^ (opid == Py_EQ)) {
+ Py_RETURN_FALSE;
+ } else {
+ Py_RETURN_TRUE;
+ }
+}
+
static PyMappingMethods MpMethods = {
- (lenfunc)len, /* mp_length */
- (binaryfunc)subscript, /* mp_subscript */
+ (lenfunc)NULL, /* mp_length */
+ (binaryfunc)subscript, /* mp_subscript */
(objobjargproc)ass_subscript,/* mp_ass_subscript */
};
@@ -286,7 +286,7 @@ PyTypeObject ExtensionDict_Type = {
"An extension dict", // tp_doc
0, // tp_traverse
0, // tp_clear
- 0, // tp_richcompare
+ (richcmpfunc)extension_dict::RichCompare, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
diff --git a/python/google/protobuf/pyext/extension_dict.h b/python/google/protobuf/pyext/extension_dict.h
index 0de2c4ee..a7d6bb7b 100644
--- a/python/google/protobuf/pyext/extension_dict.h
+++ b/python/google/protobuf/pyext/extension_dict.h
@@ -51,23 +51,8 @@ namespace python {
typedef struct ExtensionDict {
PyObject_HEAD;
- // This is the top-level C++ Message object that owns the whole
- // proto tree. Every Python container class holds a
- // reference to it in order to keep it alive as long as there's a
- // Python object that references any part of the tree.
- CMessage::OwnerRef owner;
-
- // Weak reference to parent message. Used to make sure
- // the parent is writable when an extension field is modified.
+ // Strong, owned reference to the parent message. Never NULL.
CMessage* parent;
-
- // Pointer to the C++ Message that this ExtensionDict extends.
- // Not owned by us.
- Message* message;
-
- // A dict of child messages, indexed by Extension descriptors.
- // Similar to CMessage::composite_fields.
- PyObject* values;
} ExtensionDict;
extern PyTypeObject ExtensionDict_Type;
@@ -80,6 +65,6 @@ ExtensionDict* NewExtensionDict(CMessage *parent);
} // namespace extension_dict
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_EXTENSION_DICT_H__
diff --git a/python/google/protobuf/pyext/field.cc b/python/google/protobuf/pyext/field.cc
new file mode 100755
index 00000000..1afd4583
--- /dev/null
+++ b/python/google/protobuf/pyext/field.cc
@@ -0,0 +1,142 @@
+// 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/pyext/field.h>
+
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/pyext/descriptor.h>
+#include <google/protobuf/pyext/message.h>
+
+#if PY_MAJOR_VERSION >= 3
+ #define PyString_FromFormat PyUnicode_FromFormat
+#endif
+
+namespace google {
+namespace protobuf {
+namespace python {
+
+namespace field {
+
+static PyObject* Repr(PyMessageFieldProperty* self) {
+ return PyString_FromFormat("<field property '%s'>",
+ self->field_descriptor->full_name().c_str());
+}
+
+static PyObject* DescrGet(PyMessageFieldProperty* self, PyObject* obj,
+ PyObject* type) {
+ if (obj == NULL) {
+ Py_INCREF(self);
+ return reinterpret_cast<PyObject*>(self);
+ }
+ return cmessage::GetFieldValue(reinterpret_cast<CMessage*>(obj),
+ self->field_descriptor);
+}
+
+static int DescrSet(PyMessageFieldProperty* self, PyObject* obj,
+ PyObject* value) {
+ if (value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "Cannot delete field attribute");
+ return -1;
+ }
+ return cmessage::SetFieldValue(reinterpret_cast<CMessage*>(obj),
+ self->field_descriptor, value);
+}
+
+static PyObject* GetDescriptor(PyMessageFieldProperty* self, void* closure) {
+ return PyFieldDescriptor_FromDescriptor(self->field_descriptor);
+}
+
+static PyObject* GetDoc(PyMessageFieldProperty* self, void* closure) {
+ return PyString_FromFormat("Field %s",
+ self->field_descriptor->full_name().c_str());
+}
+
+static PyGetSetDef Getters[] = {
+ {"DESCRIPTOR", (getter)GetDescriptor, NULL, "Field descriptor"},
+ {"__doc__", (getter)GetDoc, NULL, NULL},
+ {NULL}};
+} // namespace field
+
+static PyTypeObject _CFieldProperty_Type = {
+ PyVarObject_HEAD_INIT(&PyType_Type, 0) // head
+ FULL_MODULE_NAME ".FieldProperty", // tp_name
+ sizeof(PyMessageFieldProperty), // tp_basicsize
+ 0, // tp_itemsize
+ 0, // tp_dealloc
+ 0, // tp_print
+ 0, // tp_getattr
+ 0, // tp_setattr
+ 0, // tp_compare
+ (reprfunc)field::Repr, // tp_repr
+ 0, // tp_as_number
+ 0, // tp_as_sequence
+ 0, // tp_as_mapping
+ 0, // tp_hash
+ 0, // tp_call
+ 0, // tp_str
+ 0, // tp_getattro
+ 0, // tp_setattro
+ 0, // tp_as_buffer
+ Py_TPFLAGS_DEFAULT, // tp_flags
+ "Field property of a Message", // tp_doc
+ 0, // tp_traverse
+ 0, // tp_clear
+ 0, // tp_richcompare
+ 0, // tp_weaklistoffset
+ 0, // tp_iter
+ 0, // tp_iternext
+ 0, // tp_methods
+ 0, // tp_members
+ field::Getters, // tp_getset
+ 0, // tp_base
+ 0, // tp_dict
+ (descrgetfunc)field::DescrGet, // tp_descr_get
+ (descrsetfunc)field::DescrSet, // tp_descr_set
+ 0, // tp_dictoffset
+ 0, // tp_init
+ 0, // tp_alloc
+ 0, // tp_new
+};
+PyTypeObject* CFieldProperty_Type = &_CFieldProperty_Type;
+
+PyObject* NewFieldProperty(const FieldDescriptor* field_descriptor) {
+ // Create a new descriptor object
+ PyMessageFieldProperty* property =
+ PyObject_New(PyMessageFieldProperty, CFieldProperty_Type);
+ if (property == NULL) {
+ return NULL;
+ }
+ property->field_descriptor = field_descriptor;
+ return reinterpret_cast<PyObject*>(property);
+}
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/js/well_known_types/timestamp.js b/python/google/protobuf/pyext/field.h
index b7e43f19..7b4660ca 100644..100755
--- a/src/google/protobuf/compiler/js/well_known_types/timestamp.js
+++ b/python/google/protobuf/pyext/field.h
@@ -28,26 +28,32 @@
// (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 code will be inserted into generated code for
- * google/protobuf/timestamp.proto. */
-
-/**
- * Returns a JavaScript 'Date' object corresponding to this Timestamp.
- * @return {!Date}
- */
-proto.google.protobuf.Timestamp.prototype.toDate = function() {
- var seconds = this.getSeconds();
- var nanos = this.getNanos();
-
- return new Date((seconds * 1000) + (nanos / 1000000));
-};
+#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_FIELD_H__
+#define GOOGLE_PROTOBUF_PYTHON_CPP_FIELD_H__
+
+#include <Python.h>
+
+namespace google {
+namespace protobuf {
+
+class FieldDescriptor;
+
+namespace python {
+// A data descriptor that represents a field in a Message class.
+struct PyMessageFieldProperty {
+ PyObject_HEAD;
-/**
- * Sets the value of this Timestamp object to be the given Date.
- * @param {!Date} value The value to set.
- */
-proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {
- this.setSeconds(Math.floor(value.getTime() / 1000));
- this.setNanos(value.getMilliseconds() * 1000000);
+ // This pointer is owned by the same pool as the Message class it belongs to.
+ const FieldDescriptor* field_descriptor;
};
+
+extern PyTypeObject* CFieldProperty_Type;
+
+PyObject* NewFieldProperty(const FieldDescriptor* field_descriptor);
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_PYTHON_CPP_FIELD_H__
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc
index 6d7ee285..77c61706 100644
--- a/python/google/protobuf/pyext/map_container.cc
+++ b/python/google/protobuf/pyext/map_container.cc
@@ -68,6 +68,8 @@ class MapReflectionFriend {
static PyObject* MessageMapGetItem(PyObject* _self, PyObject* key);
static int ScalarMapSetItem(PyObject* _self, PyObject* key, PyObject* v);
static int MessageMapSetItem(PyObject* _self, PyObject* key, PyObject* v);
+ static PyObject* ScalarMapToStr(PyObject* _self);
+ static PyObject* MessageMapToStr(PyObject* _self);
};
struct MapIterator {
@@ -199,26 +201,26 @@ static PyObject* MapKeyToPython(const FieldDescriptor* field_descriptor,
// This is only used for ScalarMap, so we don't need to handle the
// CPPTYPE_MESSAGE case.
PyObject* MapValueRefToPython(const FieldDescriptor* field_descriptor,
- MapValueRef* value) {
+ const MapValueRef& value) {
switch (field_descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
- return PyInt_FromLong(value->GetInt32Value());
+ return PyInt_FromLong(value.GetInt32Value());
case FieldDescriptor::CPPTYPE_INT64:
- return PyLong_FromLongLong(value->GetInt64Value());
+ return PyLong_FromLongLong(value.GetInt64Value());
case FieldDescriptor::CPPTYPE_UINT32:
- return PyInt_FromSize_t(value->GetUInt32Value());
+ return PyInt_FromSize_t(value.GetUInt32Value());
case FieldDescriptor::CPPTYPE_UINT64:
- return PyLong_FromUnsignedLongLong(value->GetUInt64Value());
+ return PyLong_FromUnsignedLongLong(value.GetUInt64Value());
case FieldDescriptor::CPPTYPE_FLOAT:
- return PyFloat_FromDouble(value->GetFloatValue());
+ return PyFloat_FromDouble(value.GetFloatValue());
case FieldDescriptor::CPPTYPE_DOUBLE:
- return PyFloat_FromDouble(value->GetDoubleValue());
+ return PyFloat_FromDouble(value.GetDoubleValue());
case FieldDescriptor::CPPTYPE_BOOL:
- return PyBool_FromLong(value->GetBoolValue());
+ return PyBool_FromLong(value.GetBoolValue());
case FieldDescriptor::CPPTYPE_STRING:
- return ToStringObject(field_descriptor, value->GetStringValue());
+ return ToStringObject(field_descriptor, value.GetStringValue());
case FieldDescriptor::CPPTYPE_ENUM:
- return PyInt_FromLong(value->GetEnumValue());
+ return PyInt_FromLong(value.GetEnumValue());
default:
PyErr_Format(
PyExc_SystemError, "Couldn't convert type %d to value",
@@ -472,7 +474,7 @@ PyObject* MapReflectionFriend::ScalarMapGetItem(PyObject* _self,
self->version++;
}
- return MapValueRefToPython(self->value_field_descriptor, &value);
+ return MapValueRefToPython(self->value_field_descriptor, value);
}
int MapReflectionFriend::ScalarMapSetItem(PyObject* _self, PyObject* key,
@@ -535,10 +537,47 @@ static PyObject* ScalarMapGet(PyObject* self, PyObject* args) {
}
}
+PyObject* MapReflectionFriend::ScalarMapToStr(PyObject* _self) {
+ ScopedPyObjectPtr dict(PyDict_New());
+ if (dict == NULL) {
+ return NULL;
+ }
+ ScopedPyObjectPtr key;
+ ScopedPyObjectPtr value;
+
+ MapContainer* self = GetMap(_self);
+ Message* message = self->GetMutableMessage();
+ const Reflection* reflection = message->GetReflection();
+ for (google::protobuf::MapIterator it = reflection->MapBegin(
+ message, self->parent_field_descriptor);
+ it != reflection->MapEnd(message, self->parent_field_descriptor);
+ ++it) {
+ key.reset(MapKeyToPython(self->key_field_descriptor,
+ it.GetKey()));
+ if (key == NULL) {
+ return NULL;
+ }
+ value.reset(MapValueRefToPython(self->value_field_descriptor,
+ it.GetValueRef()));
+ if (value == NULL) {
+ return NULL;
+ }
+ if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
+ return NULL;
+ }
+ }
+ return PyObject_Repr(dict.get());
+}
+
static void ScalarMapDealloc(PyObject* _self) {
MapContainer* self = GetMap(_self);
self->owner.reset();
- Py_TYPE(_self)->tp_free(_self);
+ PyTypeObject *type = Py_TYPE(_self);
+ type->tp_free(_self);
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
+ // With Python3, the Map class is not static, and must be managed.
+ Py_DECREF(type);
+ }
}
static PyMethodDef ScalarMapMethods[] = {
@@ -570,6 +609,7 @@ PyTypeObject *ScalarMapContainer_Type;
{Py_mp_ass_subscript, (void *)MapReflectionFriend::ScalarMapSetItem},
{Py_tp_methods, (void *)ScalarMapMethods},
{Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
+ {Py_tp_repr, (void *)MapReflectionFriend::ScalarMapToStr},
{0, 0},
};
@@ -597,7 +637,7 @@ PyTypeObject *ScalarMapContainer_Type;
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- 0, // tp_repr
+ MapReflectionFriend::ScalarMapToStr, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
&ScalarMapMappingMethods, // tp_as_mapping
@@ -634,7 +674,8 @@ static MessageMapContainer* GetMessageMap(PyObject* obj) {
return reinterpret_cast<MessageMapContainer*>(obj);
}
-static PyObject* GetCMessage(MessageMapContainer* self, Message* message) {
+static PyObject* GetCMessage(MessageMapContainer* self, Message* message,
+ bool insert_message_dict) {
// Get or create the CMessage object corresponding to this message.
ScopedPyObjectPtr key(PyLong_FromVoidPtr(message));
PyObject* ret = PyDict_GetItem(self->message_dict, key.get());
@@ -649,10 +690,11 @@ static PyObject* GetCMessage(MessageMapContainer* self, Message* message) {
cmsg->owner = self->owner;
cmsg->message = message;
cmsg->parent = self->parent;
-
- if (PyDict_SetItem(self->message_dict, key.get(), ret) < 0) {
- Py_DECREF(ret);
- return NULL;
+ if (insert_message_dict) {
+ if (PyDict_SetItem(self->message_dict, key.get(), ret) < 0) {
+ Py_DECREF(ret);
+ return NULL;
+ }
}
} else {
Py_INCREF(ret);
@@ -781,7 +823,41 @@ PyObject* MapReflectionFriend::MessageMapGetItem(PyObject* _self,
self->version++;
}
- return GetCMessage(self, value.MutableMessageValue());
+ return GetCMessage(self, value.MutableMessageValue(), true);
+}
+
+PyObject* MapReflectionFriend::MessageMapToStr(PyObject* _self) {
+ ScopedPyObjectPtr dict(PyDict_New());
+ if (dict == NULL) {
+ return NULL;
+ }
+ ScopedPyObjectPtr key;
+ ScopedPyObjectPtr value;
+
+ MessageMapContainer* self = GetMessageMap(_self);
+ Message* message = self->GetMutableMessage();
+ const Reflection* reflection = message->GetReflection();
+ for (google::protobuf::MapIterator it = reflection->MapBegin(
+ message, self->parent_field_descriptor);
+ it != reflection->MapEnd(message, self->parent_field_descriptor);
+ ++it) {
+ key.reset(MapKeyToPython(self->key_field_descriptor,
+ it.GetKey()));
+ if (key == NULL) {
+ return NULL;
+ }
+ // Do not insert the cmessage to self->message_dict because
+ // the returned CMessage will not escape this function.
+ value.reset(GetCMessage(
+ self, it.MutableValueRef()->MutableMessageValue(), false));
+ if (value == NULL) {
+ return NULL;
+ }
+ if (PyDict_SetItem(dict.get(), key.get(), value.get()) < 0) {
+ return NULL;
+ }
+ }
+ return PyObject_Repr(dict.get());
}
PyObject* MessageMapGet(PyObject* self, PyObject* args) {
@@ -813,7 +889,12 @@ static void MessageMapDealloc(PyObject* _self) {
self->owner.reset();
Py_DECREF(self->message_dict);
Py_DECREF(self->message_class);
- Py_TYPE(_self)->tp_free(_self);
+ PyTypeObject *type = Py_TYPE(_self);
+ type->tp_free(_self);
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
+ // With Python3, the Map class is not static, and must be managed.
+ Py_DECREF(type);
+ }
}
static PyMethodDef MessageMapMethods[] = {
@@ -847,6 +928,7 @@ PyTypeObject *MessageMapContainer_Type;
{Py_mp_ass_subscript, (void *)MapReflectionFriend::MessageMapSetItem},
{Py_tp_methods, (void *)MessageMapMethods},
{Py_tp_iter, (void *)MapReflectionFriend::GetIterator},
+ {Py_tp_repr, (void *)MapReflectionFriend::MessageMapToStr},
{0, 0}
};
@@ -874,7 +956,7 @@ PyTypeObject *MessageMapContainer_Type;
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
- 0, // tp_repr
+ MapReflectionFriend::MessageMapToStr, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
&MessageMapMappingMethods, // tp_as_mapping
@@ -1027,17 +1109,15 @@ bool InitMapContainers() {
return false;
}
- if (!PyObject_TypeCheck(mutable_mapping.get(), &PyType_Type)) {
- return false;
- }
-
Py_INCREF(mutable_mapping.get());
#if PY_MAJOR_VERSION >= 3
- PyObject* bases = PyTuple_New(1);
- PyTuple_SET_ITEM(bases, 0, mutable_mapping.get());
+ ScopedPyObjectPtr bases(PyTuple_Pack(1, mutable_mapping.get()));
+ if (bases == NULL) {
+ return false;
+ }
ScalarMapContainer_Type = reinterpret_cast<PyTypeObject*>(
- PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases));
+ PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases.get()));
#else
_ScalarMapContainer_Type.tp_base =
reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
@@ -1055,7 +1135,7 @@ bool InitMapContainers() {
#if PY_MAJOR_VERSION >= 3
MessageMapContainer_Type = reinterpret_cast<PyTypeObject*>(
- PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases));
+ PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases.get()));
#else
Py_INCREF(mutable_mapping.get());
_MessageMapContainer_Type.tp_base =
diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h
index 111fafbf..7e77b027 100644
--- a/python/google/protobuf/pyext/map_container.h
+++ b/python/google/protobuf/pyext/map_container.h
@@ -120,6 +120,6 @@ extern PyObject* NewMessageMapContainer(
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc
index 5893533a..fecb9364 100644
--- a/python/google/protobuf/pyext/message.cc
+++ b/python/google/protobuf/pyext/message.cc
@@ -45,12 +45,11 @@
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
-#include <google/protobuf/descriptor.pb.h>
#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.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
@@ -58,12 +57,18 @@
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/extension_dict.h>
-#include <google/protobuf/pyext/repeated_composite_container.h>
-#include <google/protobuf/pyext/repeated_scalar_container.h>
+#include <google/protobuf/pyext/field.h>
#include <google/protobuf/pyext/map_container.h>
#include <google/protobuf/pyext/message_factory.h>
+#include <google/protobuf/pyext/repeated_composite_container.h>
+#include <google/protobuf/pyext/repeated_scalar_container.h>
+#include <google/protobuf/pyext/unknown_fields.h>
#include <google/protobuf/pyext/safe_numerics.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
+#include <google/protobuf/util/message_differencer.h>
+#include <google/protobuf/stubs/strutil.h>
+
+#include <google/protobuf/port_def.inc>
#if PY_MAJOR_VERSION >= 3
#define PyInt_AsLong PyLong_AsLong
@@ -72,16 +77,19 @@
#define PyString_Check PyUnicode_Check
#define PyString_FromString PyUnicode_FromString
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
+ #define PyString_FromFormat PyUnicode_FromFormat
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#else
#define PyString_AsString(ob) \
(PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
- #define PyString_AsStringAndSize(ob, charpp, sizep) \
- (PyUnicode_Check(ob)? \
- ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
- PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
- #endif
+#define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
+ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
+ ? -1 \
+ : 0) \
+ : PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#endif
#endif
namespace google {
@@ -99,44 +107,27 @@ namespace message_meta {
static int InsertEmptyWeakref(PyTypeObject* base);
namespace {
-// Copied oveer from internal 'google/protobuf/stubs/strutil.h'.
-inline void UpperString(string * s) {
+// Copied over from internal 'google/protobuf/stubs/strutil.h'.
+inline void LowerString(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';
+ // tolower() 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>
-static bool AddFieldNumberToClass(
- PyObject* cls, const FieldDescriptor* field_descriptor) {
- string constant_name = field_descriptor->name() + "_FIELD_NUMBER";
- UpperString(&constant_name);
- ScopedPyObjectPtr attr_name(PyString_FromStringAndSize(
- constant_name.c_str(), constant_name.size()));
- if (attr_name == NULL) {
- return false;
- }
- ScopedPyObjectPtr number(PyInt_FromLong(field_descriptor->number()));
- if (number == NULL) {
- return false;
- }
- if (PyObject_SetAttr(cls, attr_name.get(), number.get()) == -1) {
- return false;
- }
- return true;
-}
-
-
// Finalize the creation of the Message class.
static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
// For each field set: cls.<field>_FIELD_NUMBER = <number>
for (int i = 0; i < descriptor->field_count(); ++i) {
- if (!AddFieldNumberToClass(cls, descriptor->field(i))) {
+ const FieldDescriptor* field_descriptor = descriptor->field(i);
+ ScopedPyObjectPtr property(NewFieldProperty(field_descriptor));
+ if (property == NULL) {
+ return -1;
+ }
+ if (PyObject_SetAttrString(cls, field_descriptor->name().c_str(),
+ property.get()) < 0) {
return -1;
}
}
@@ -193,11 +184,6 @@ static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
cls, field->name().c_str(), extension_field.get()) == -1) {
return -1;
}
-
- // For each extension set cls.<extension name>_FIELD_NUMBER = <number>.
- if (!AddFieldNumberToClass(cls, field)) {
- return -1;
- }
}
return 0;
@@ -265,10 +251,10 @@ static PyObject* New(PyTypeObject* type,
PyObject* well_known_class = PyDict_GetItemString(
WKT_classes, message_descriptor->full_name().c_str());
if (well_known_class == NULL) {
- new_args.reset(Py_BuildValue("s(OO)O", name, &CMessage_Type,
+ new_args.reset(Py_BuildValue("s(OO)O", name, CMessage_Type,
PythonMessage_class, dict));
} else {
- new_args.reset(Py_BuildValue("s(OOO)O", name, &CMessage_Type,
+ new_args.reset(Py_BuildValue("s(OOO)O", name, CMessage_Type,
PythonMessage_class, well_known_class, dict));
}
@@ -285,7 +271,7 @@ static PyObject* New(PyTypeObject* type,
// Insert the empty weakref into the base classes.
if (InsertEmptyWeakref(
reinterpret_cast<PyTypeObject*>(PythonMessage_class)) < 0 ||
- InsertEmptyWeakref(&CMessage_Type) < 0) {
+ InsertEmptyWeakref(CMessage_Type) < 0) {
return NULL;
}
@@ -353,6 +339,13 @@ static int InsertEmptyWeakref(PyTypeObject *base_type) {
// The _extensions_by_name dictionary is built on every access.
// TODO(amauryfa): Migrate all users to pool.FindAllExtensions()
static PyObject* GetExtensionsByName(CMessageClass *self, void *closure) {
+ if (self->message_descriptor == NULL) {
+ // This is the base Message object, simply raise AttributeError.
+ PyErr_SetString(PyExc_AttributeError,
+ "Base Message class has no DESCRIPTOR");
+ return NULL;
+ }
+
const PyDescriptorPool* pool = self->py_message_factory->pool;
std::vector<const FieldDescriptor*> extensions;
@@ -376,6 +369,13 @@ static PyObject* GetExtensionsByName(CMessageClass *self, void *closure) {
// The _extensions_by_number dictionary is built on every access.
// TODO(amauryfa): Migrate all users to pool.FindExtensionByNumber()
static PyObject* GetExtensionsByNumber(CMessageClass *self, void *closure) {
+ if (self->message_descriptor == NULL) {
+ // This is the base Message object, simply raise AttributeError.
+ PyErr_SetString(PyExc_AttributeError,
+ "Base Message class has no DESCRIPTOR");
+ return NULL;
+ }
+
const PyDescriptorPool* pool = self->py_message_factory->pool;
std::vector<const FieldDescriptor*> extensions;
@@ -405,9 +405,51 @@ static PyGetSetDef Getters[] = {
{NULL}
};
+// Compute some class attributes on the fly:
+// - All the _FIELD_NUMBER attributes, for all fields and nested extensions.
+// Returns a new reference, or NULL with an exception set.
+static PyObject* GetClassAttribute(CMessageClass *self, PyObject* name) {
+ char* attr;
+ Py_ssize_t attr_size;
+ static const char kSuffix[] = "_FIELD_NUMBER";
+ if (PyString_AsStringAndSize(name, &attr, &attr_size) >= 0 &&
+ strings::EndsWith(StringPiece(attr, attr_size), kSuffix)) {
+ string field_name(attr, attr_size - sizeof(kSuffix) + 1);
+ LowerString(&field_name);
+
+ // Try to find a field with the given name, without the suffix.
+ const FieldDescriptor* field =
+ self->message_descriptor->FindFieldByLowercaseName(field_name);
+ if (!field) {
+ // Search nested extensions as well.
+ field =
+ self->message_descriptor->FindExtensionByLowercaseName(field_name);
+ }
+ if (field) {
+ return PyInt_FromLong(field->number());
+ }
+ }
+ PyErr_SetObject(PyExc_AttributeError, name);
+ return NULL;
+}
+
+static PyObject* GetAttr(CMessageClass* self, PyObject* name) {
+ PyObject* result = CMessageClass_Type->tp_base->tp_getattro(
+ reinterpret_cast<PyObject*>(self), name);
+ if (result != NULL) {
+ return result;
+ }
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ return NULL;
+ }
+
+ PyErr_Clear();
+ return GetClassAttribute(self, name);
+}
+
} // namespace message_meta
-PyTypeObject CMessageClass_Type = {
+static PyTypeObject _CMessageClass_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".MessageMeta", // tp_name
sizeof(CMessageClass), // tp_basicsize
@@ -424,7 +466,7 @@ PyTypeObject CMessageClass_Type = {
0, // tp_hash
0, // tp_call
0, // tp_str
- 0, // tp_getattro
+ (getattrofunc)message_meta::GetAttr, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
@@ -447,9 +489,10 @@ PyTypeObject CMessageClass_Type = {
0, // tp_alloc
message_meta::New, // tp_new
};
+PyTypeObject* CMessageClass_Type = &_CMessageClass_Type;
static CMessageClass* CheckMessageClass(PyTypeObject* cls) {
- if (!PyObject_TypeCheck(cls, &CMessageClass_Type)) {
+ if (!PyObject_TypeCheck(cls, CMessageClass_Type)) {
PyErr_Format(PyExc_TypeError, "Class %s is not a Message", cls->tp_name);
return NULL;
}
@@ -487,10 +530,20 @@ struct ChildVisitor {
}
// Returns 0 on success, -1 on failure.
+ int VisitMapContainer(MapContainer* container) {
+ return 0;
+ }
+
+ // Returns 0 on success, -1 on failure.
int VisitCMessage(CMessage* cmessage,
const FieldDescriptor* field_descriptor) {
return 0;
}
+
+ // Returns 0 on success, -1 on failure.
+ int VisitUnknownFieldSet(PyUnknownFields* unknown_field_set) {
+ return 0;
+ }
};
// Apply a function to a composite field. Does nothing if child is of
@@ -538,34 +591,19 @@ int ForEachCompositeField(CMessage* self, Visitor visitor) {
// Visit normal fields.
if (self->composite_fields) {
- // Never use self->message in this function, it may be already freed.
- const Descriptor* message_descriptor =
- GetMessageDescriptor(Py_TYPE(self));
- while (PyDict_Next(self->composite_fields, &pos, &key, &field)) {
- Py_ssize_t key_str_size;
- char *key_str_data;
- if (PyString_AsStringAndSize(key, &key_str_data, &key_str_size) != 0)
- return -1;
- const string key_str(key_str_data, key_str_size);
- const FieldDescriptor* descriptor =
- message_descriptor->FindFieldByName(key_str);
- if (descriptor != NULL) {
- if (VisitCompositeField(descriptor, field, visitor) == -1)
- return -1;
- }
+ for (CMessage::CompositeFieldsMap::iterator it =
+ self->composite_fields->begin();
+ it != self->composite_fields->end(); it++) {
+ const FieldDescriptor* descriptor = it->first;
+ PyObject* field = it->second;
+ if (VisitCompositeField(descriptor, field, visitor) == -1) return -1;
}
}
- // Visit extension fields.
- if (self->extensions != NULL) {
- pos = 0;
- while (PyDict_Next(self->extensions->values, &pos, &key, &field)) {
- const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
- if (descriptor == NULL)
- return -1;
- if (VisitCompositeField(descriptor, field, visitor) == -1)
- return -1;
- }
+ if (self->unknown_field_set) {
+ PyUnknownFields* unknown_field_set =
+ reinterpret_cast<PyUnknownFields*>(self->unknown_field_set);
+ visitor.VisitUnknownFieldSet(unknown_field_set);
}
return 0;
@@ -577,8 +615,12 @@ PyObject* EncodeError_class;
PyObject* DecodeError_class;
PyObject* PickleError_class;
-/* Is 64bit */
+// Format an error message for unexpected types.
+// Always return with an exception set.
void FormatTypeError(PyObject* arg, char* expected_types) {
+ // This function is often called with an exception set.
+ // Clear it to call PyObject_Repr() in good conditions.
+ PyErr_Clear();
PyObject* repr = PyObject_Repr(arg);
if (repr) {
PyErr_Format(PyExc_TypeError,
@@ -602,7 +644,7 @@ void OutOfRangeError(PyObject* arg) {
template<class RangeType, class ValueType>
bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
- if (GOOGLE_PREDICT_FALSE(value == -1 && PyErr_Occurred())) {
+ if (PROTOBUF_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.
@@ -611,7 +653,7 @@ bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
} // Otherwise propagate existing error.
return false;
}
- if (GOOGLE_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value))) {
+ if (PROTOBUF_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value))) {
OutOfRangeError(arg);
return false;
}
@@ -623,22 +665,22 @@ 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))) {
+ if (PROTOBUF_PREDICT_TRUE(PyInt_Check(arg))) {
long int_result = PyInt_AsLong(arg);
- if (GOOGLE_PREDICT_TRUE(IsValidNumericCast<T>(int_result))) {
+ if (PROTOBUF_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))) {
+ if (PROTOBUF_PREDICT_FALSE(!PyIndex_Check(arg))) {
FormatTypeError(arg, "int, long");
return false;
}
@@ -655,7 +697,7 @@ 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 == nullptr)) {
+ if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
@@ -680,7 +722,7 @@ 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 == nullptr)) {
+ if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
@@ -706,7 +748,7 @@ template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
bool CheckAndGetDouble(PyObject* arg, double* value) {
*value = PyFloat_AsDouble(arg);
- if (GOOGLE_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) {
+ if (PROTOBUF_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) {
FormatTypeError(arg, "int, long, float");
return false;
}
@@ -859,7 +901,7 @@ bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
namespace cmessage {
PyMessageFactory* GetFactoryForMessage(CMessage* message) {
- GOOGLE_DCHECK(PyObject_TypeCheck(message, &CMessage_Type));
+ GOOGLE_DCHECK(PyObject_TypeCheck(message, CMessage_Type));
return reinterpret_cast<CMessageClass*>(Py_TYPE(message))->py_message_factory;
}
@@ -883,22 +925,20 @@ static int MaybeReleaseOverlappingOneofField(
// Non-message fields don't need to be released.
return 0;
}
- const char* field_name = existing_field->name().c_str();
- PyObject* child_message = cmessage->composite_fields ?
- PyDict_GetItemString(cmessage->composite_fields, field_name) : NULL;
- if (child_message == NULL) {
- // No python reference to this field so no need to release.
- return 0;
- }
-
- if (InternalReleaseFieldByDescriptor(
- cmessage, existing_field, child_message) < 0) {
- return -1;
+ if (cmessage->composite_fields) {
+ CMessage::CompositeFieldsMap::iterator iterator =
+ cmessage->composite_fields->find(existing_field);
+ if (iterator != cmessage->composite_fields->end()) {
+ if (InternalReleaseFieldByDescriptor(cmessage, existing_field,
+ iterator->second) < 0) {
+ return -1;
+ }
+ Py_DECREF(iterator->second);
+ cmessage->composite_fields->erase(iterator);
+ }
}
- return PyDict_DelItemString(cmessage->composite_fields, field_name);
-#else
- return 0;
#endif
+ return 0;
}
// ---------------------------------------------------------------------
@@ -937,10 +977,49 @@ struct FixupMessageReference : public ChildVisitor {
return 0;
}
+ int VisitUnknownFieldSet(PyUnknownFields* unknown_field_set) {
+ const Reflection* reflection = message_->GetReflection();
+ unknown_field_set->fields = &reflection->GetUnknownFields(*message_);
+ return 0;
+ }
+
private:
Message* message_;
};
+// After a Merge, visit every sub-message that was read-only, and
+// eventually update their pointer if the Merge operation modified them.
+struct FixupMessageAfterMerge : public FixupMessageReference {
+ explicit FixupMessageAfterMerge(CMessage* parent) :
+ FixupMessageReference(parent->message),
+ parent_cmessage(parent), message(parent->message) {}
+
+ int VisitCMessage(CMessage* cmessage,
+ const FieldDescriptor* field_descriptor) {
+ if (cmessage->read_only == false) {
+ return 0;
+ }
+ if (message->GetReflection()->HasField(*message, field_descriptor)) {
+ Message* mutable_message = GetMutableMessage(
+ parent_cmessage, field_descriptor);
+ if (mutable_message == NULL) {
+ return -1;
+ }
+ cmessage->message = mutable_message;
+ cmessage->read_only = false;
+ if (ForEachCompositeField(
+ cmessage, FixupMessageAfterMerge(cmessage)) == -1) {
+ return -1;
+ }
+ }
+ return 0;
+ }
+
+ private:
+ CMessage* parent_cmessage;
+ Message* message;
+};
+
int AssureWritable(CMessage* self) {
if (self == NULL || !self->read_only) {
return 0;
@@ -974,10 +1053,8 @@ int AssureWritable(CMessage* self) {
// When a CMessage is made writable its Message pointer is updated
// to point to a new mutable Message. When that happens we need to
// update any references to the old, read-only CMessage. There are
- // four places such references occur: RepeatedScalarContainer,
- // RepeatedCompositeContainer, MapContainer, and ExtensionDict.
- if (self->extensions != NULL)
- self->extensions->message = self->message;
+ // three places such references occur: RepeatedScalarContainer,
+ // RepeatedCompositeContainer, and MapContainer.
if (ForEachCompositeField(self, FixupMessageReference(self->message)) == -1)
return -1;
@@ -986,27 +1063,6 @@ int AssureWritable(CMessage* self) {
// --- Globals:
-// Retrieve a C++ FieldDescriptor for a message attribute.
-// The C++ message must be valid.
-// TODO(amauryfa): This function should stay internal, because exception
-// handling is not consistent.
-static const FieldDescriptor* GetFieldDescriptor(
- CMessage* self, PyObject* name) {
- const Descriptor *message_descriptor = self->message->GetDescriptor();
- char* field_name;
- Py_ssize_t size;
- if (PyString_AsStringAndSize(name, &field_name, &size) < 0) {
- return NULL;
- }
- const FieldDescriptor *field_descriptor =
- message_descriptor->FindFieldByName(string(field_name, size));
- if (field_descriptor == NULL) {
- // Note: No exception is set!
- return NULL;
- }
- return field_descriptor;
-}
-
// Retrieve a C++ FieldDescriptor for an extension handle.
const FieldDescriptor* GetExtensionDescriptor(PyObject* extension) {
ScopedPyObjectPtr cdescriptor;
@@ -1038,7 +1094,7 @@ static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor,
const EnumValueDescriptor* enum_value_descriptor =
enum_descriptor->FindValueByName(string(enum_label, size));
if (enum_value_descriptor == NULL) {
- PyErr_SetString(PyExc_ValueError, "unknown enum label");
+ PyErr_Format(PyExc_ValueError, "unknown enum label \"%s\"", enum_label);
return NULL;
}
return PyInt_FromLong(enum_value_descriptor->number());
@@ -1052,11 +1108,10 @@ static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor,
// needs to do this to make sure CMessages stay alive if they're still
// referenced after deletion. Repeated scalar container doesn't need to worry.
int InternalDeleteRepeatedField(
- CMessage* self,
+ Message* message,
const FieldDescriptor* field_descriptor,
PyObject* slice,
PyObject* cmessage_list) {
- Message* message = self->message;
Py_ssize_t length, from, to, step, slice_length;
const Reflection* reflection = message->GetReflection();
int min, max;
@@ -1134,7 +1189,7 @@ int InternalDeleteRepeatedField(
CMessage* last_cmessage = reinterpret_cast<CMessage*>(
PyList_GET_ITEM(cmessage_list, PyList_GET_SIZE(cmessage_list) - 1));
repeated_composite_container::ReleaseLastTo(
- self, field_descriptor, last_cmessage);
+ message, field_descriptor, last_cmessage);
if (PySequence_DelItem(cmessage_list, -1) < 0) {
return -1;
}
@@ -1160,23 +1215,28 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
PyObject* name;
PyObject* value;
while (PyDict_Next(kwargs, &pos, &name, &value)) {
- if (!PyString_Check(name)) {
+ if (!(PyString_Check(name) || PyUnicode_Check(name))) {
PyErr_SetString(PyExc_ValueError, "Field name must be a string");
return -1;
}
- const FieldDescriptor* descriptor = GetFieldDescriptor(self, name);
- if (descriptor == NULL) {
+ ScopedPyObjectPtr property(
+ PyObject_GetAttr(reinterpret_cast<PyObject*>(Py_TYPE(self)), name));
+ if (property == NULL ||
+ !PyObject_TypeCheck(property.get(), CFieldProperty_Type)) {
PyErr_Format(PyExc_ValueError, "Protocol message %s has no \"%s\" field.",
self->message->GetDescriptor()->name().c_str(),
PyString_AsString(name));
return -1;
}
+ const FieldDescriptor* descriptor =
+ reinterpret_cast<PyMessageFieldProperty*>(property.get())
+ ->field_descriptor;
if (value == Py_None) {
// field=None is the same as no field at all.
continue;
}
if (descriptor->is_map()) {
- ScopedPyObjectPtr map(GetAttr(reinterpret_cast<PyObject*>(self), name));
+ ScopedPyObjectPtr map(GetFieldValue(self, descriptor));
const FieldDescriptor* value_descriptor =
descriptor->message_type()->FindFieldByName("value");
if (value_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
@@ -1204,8 +1264,7 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
}
}
} else if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
- ScopedPyObjectPtr container(
- GetAttr(reinterpret_cast<PyObject*>(self), name));
+ ScopedPyObjectPtr container(GetFieldValue(self, descriptor));
if (container == NULL) {
return -1;
}
@@ -1272,8 +1331,7 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
}
}
} else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- ScopedPyObjectPtr message(
- GetAttr(reinterpret_cast<PyObject*>(self), name));
+ ScopedPyObjectPtr message(GetFieldValue(self, descriptor));
if (message == NULL) {
return -1;
}
@@ -1297,9 +1355,9 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
if (new_val == NULL) {
return -1;
}
+ value = new_val.get();
}
- if (SetAttr(reinterpret_cast<PyObject*>(self), name,
- (new_val.get() == NULL) ? value : new_val.get()) < 0) {
+ if (SetFieldValue(self, descriptor, value) < 0) {
return -1;
}
}
@@ -1322,10 +1380,11 @@ CMessage* NewEmptyMessage(CMessageClass* type) {
self->parent = NULL;
self->parent_field_descriptor = NULL;
self->read_only = false;
- self->extensions = NULL;
self->composite_fields = NULL;
+ self->unknown_field_set = NULL;
+
return self;
}
@@ -1408,12 +1467,20 @@ static void Dealloc(CMessage* self) {
}
// Null out all weak references from children to this message.
GOOGLE_CHECK_EQ(0, ForEachCompositeField(self, ClearWeakReferences()));
- if (self->extensions) {
- self->extensions->parent = NULL;
- }
- Py_CLEAR(self->extensions);
- Py_CLEAR(self->composite_fields);
+ if (self->composite_fields) {
+ for (CMessage::CompositeFieldsMap::iterator it =
+ self->composite_fields->begin();
+ it != self->composite_fields->end(); it++) {
+ Py_DECREF(it->second);
+ }
+ delete self->composite_fields;
+ }
+ if (self->unknown_field_set) {
+ unknown_fields::Clear(
+ reinterpret_cast<PyUnknownFields*>(self->unknown_field_set));
+ Py_CLEAR(self->unknown_field_set);
+ }
self->owner.~ThreadUnsafeSharedPtr<Message>();
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
@@ -1529,7 +1596,7 @@ PyObject* HasField(CMessage* self, PyObject* arg) {
return NULL;
}
#else
- field_name = PyUnicode_AsUTF8AndSize(arg, &size);
+ field_name = const_cast<char*>(PyUnicode_AsUTF8AndSize(arg, &size));
if (!field_name) {
return NULL;
}
@@ -1564,13 +1631,16 @@ PyObject* ClearExtension(CMessage* self, PyObject* extension) {
if (descriptor == NULL) {
return NULL;
}
- if (self->extensions != NULL) {
- PyObject* value = PyDict_GetItem(self->extensions->values, extension);
- if (value != NULL) {
- if (InternalReleaseFieldByDescriptor(self, descriptor, value) < 0) {
+ if (self->composite_fields != NULL) {
+ CMessage::CompositeFieldsMap::iterator iterator =
+ self->composite_fields->find(descriptor);
+ if (iterator != self->composite_fields->end()) {
+ if (InternalReleaseFieldByDescriptor(self, descriptor,
+ iterator->second) < 0) {
return NULL;
}
- PyDict_DelItem(self->extensions->values, extension);
+ Py_DECREF(iterator->second);
+ self->composite_fields->erase(iterator);
}
}
return ClearFieldByDescriptor(self, descriptor);
@@ -1739,13 +1809,16 @@ PyObject* ClearFieldByDescriptor(
}
PyObject* ClearField(CMessage* self, PyObject* arg) {
- if (!PyString_Check(arg)) {
+ if (!(PyString_Check(arg) || PyUnicode_Check(arg))) {
PyErr_SetString(PyExc_TypeError, "field name must be a string");
return NULL;
}
#if PY_MAJOR_VERSION < 3
- const char* field_name = PyString_AS_STRING(arg);
- Py_ssize_t size = PyString_GET_SIZE(arg);
+ char* field_name;
+ Py_ssize_t size;
+ if (PyString_AsStringAndSize(arg, &field_name, &size) < 0) {
+ return NULL;
+ }
#else
Py_ssize_t size;
const char* field_name = PyUnicode_AsUTF8AndSize(arg, &size);
@@ -1770,14 +1843,16 @@ PyObject* ClearField(CMessage* self, PyObject* arg) {
arg = arg_in_oneof.get();
}
- // Release the field if it exists in the dict of composite fields.
if (self->composite_fields) {
- PyObject* value = PyDict_GetItem(self->composite_fields, arg);
- if (value != NULL) {
- if (InternalReleaseFieldByDescriptor(self, field_descriptor, value) < 0) {
+ CMessage::CompositeFieldsMap::iterator iterator =
+ self->composite_fields->find(field_descriptor);
+ if (iterator != self->composite_fields->end()) {
+ if (InternalReleaseFieldByDescriptor(self, field_descriptor,
+ iterator->second) < 0) {
return NULL;
}
- PyDict_DelItem(self->composite_fields, arg);
+ Py_DECREF(iterator->second);
+ self->composite_fields->erase(iterator);
}
}
return ClearFieldByDescriptor(self, field_descriptor);
@@ -1787,9 +1862,18 @@ PyObject* Clear(CMessage* self) {
AssureWritable(self);
if (ForEachCompositeField(self, ReleaseChild(self)) == -1)
return NULL;
- Py_CLEAR(self->extensions);
if (self->composite_fields) {
- PyDict_Clear(self->composite_fields);
+ for (CMessage::CompositeFieldsMap::iterator it =
+ self->composite_fields->begin();
+ it != self->composite_fields->end(); it++) {
+ Py_DECREF(it->second);
+ }
+ self->composite_fields->clear();
+ }
+ if (self->unknown_field_set) {
+ unknown_fields::Clear(
+ reinterpret_cast<PyUnknownFields*>(self->unknown_field_set));
+ Py_CLEAR(self->unknown_field_set);
}
self->message->Clear();
Py_RETURN_NONE;
@@ -1946,7 +2030,7 @@ static PyObject* ToStr(CMessage* self) {
PyObject* MergeFrom(CMessage* self, PyObject* arg) {
CMessage* other_message;
- if (!PyObject_TypeCheck(arg, &CMessage_Type)) {
+ if (!PyObject_TypeCheck(arg, CMessage_Type)) {
PyErr_Format(PyExc_TypeError,
"Parameter to MergeFrom() must be instance of same class: "
"expected %s got %s.",
@@ -1967,18 +2051,19 @@ PyObject* MergeFrom(CMessage* self, PyObject* arg) {
}
AssureWritable(self);
- // TODO(tibell): Message::MergeFrom might turn some child Messages
- // into mutable messages, invalidating the message field in the
- // corresponding CMessages. We should run a FixupMessageReferences
- // pass here.
-
self->message->MergeFrom(*other_message->message);
+ // Child message might be lazily created before MergeFrom. Make sure they
+ // are mutable at this point if child messages are really created.
+ if (ForEachCompositeField(self, FixupMessageAfterMerge(self)) == -1) {
+ return NULL;
+ }
+
Py_RETURN_NONE;
}
static PyObject* CopyFrom(CMessage* self, PyObject* arg) {
CMessage* other_message;
- if (!PyObject_TypeCheck(arg, &CMessage_Type)) {
+ if (!PyObject_TypeCheck(arg, CMessage_Type)) {
PyErr_Format(PyExc_TypeError,
"Parameter to CopyFrom() must be instance of same class: "
"expected %s got %s.",
@@ -2050,6 +2135,7 @@ static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
}
AssureWritable(self);
+
io::CodedInputStream input(
reinterpret_cast<const uint8*>(data), data_length);
if (allow_oversize_protos) {
@@ -2058,6 +2144,12 @@ static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
PyMessageFactory* factory = GetFactoryForMessage(self);
input.SetExtensionRegistry(factory->pool->pool, factory->message_factory);
bool success = self->message->MergePartialFromCodedStream(&input);
+ // Child message might be lazily created before MergeFrom. Make sure they
+ // are mutable at this point if child messages are really created.
+ if (ForEachCompositeField(self, FixupMessageAfterMerge(self)) == -1) {
+ return NULL;
+ }
+
if (success) {
if (!input.ConsumedEntireMessage()) {
// TODO(jieluo): Raise error and return NULL instead.
@@ -2088,7 +2180,7 @@ PyObject* RegisterExtension(PyObject* cls, PyObject* extension_handle) {
if (descriptor == NULL) {
return NULL;
}
- if (!PyObject_TypeCheck(cls, &CMessageClass_Type)) {
+ if (!PyObject_TypeCheck(cls, CMessageClass_Type)) {
PyErr_Format(PyExc_TypeError, "Expected a message class, got %s",
cls->ob_type->tp_name);
return NULL;
@@ -2192,23 +2284,15 @@ static PyObject* ListFields(CMessage* self) {
PyTuple_SET_ITEM(t.get(), 1, extension);
} else {
// Normal field
- const string& field_name = fields[i]->name();
- ScopedPyObjectPtr py_field_name(PyString_FromStringAndSize(
- field_name.c_str(), field_name.length()));
- if (py_field_name == NULL) {
- PyErr_SetString(PyExc_ValueError, "bad string");
- return NULL;
- }
ScopedPyObjectPtr field_descriptor(
PyFieldDescriptor_FromDescriptor(fields[i]));
if (field_descriptor == NULL) {
return NULL;
}
- PyObject* field_value =
- GetAttr(reinterpret_cast<PyObject*>(self), py_field_name.get());
+ PyObject* field_value = GetFieldValue(self, fields[i]);
if (field_value == NULL) {
- PyErr_SetObject(PyExc_ValueError, py_field_name.get());
+ PyErr_SetString(PyExc_ValueError, fields[i]->name().c_str());
return NULL;
}
PyTuple_SET_ITEM(t.get(), 0, field_descriptor.release());
@@ -2261,7 +2345,7 @@ static PyObject* RichCompare(CMessage* self, PyObject* other, int opid) {
}
bool equals = true;
// If other is not a message, it cannot be equal.
- if (!PyObject_TypeCheck(other, &CMessage_Type)) {
+ if (!PyObject_TypeCheck(other, CMessage_Type)) {
equals = false;
}
const google::protobuf::Message* other_message =
@@ -2277,6 +2361,7 @@ static PyObject* RichCompare(CMessage* self, PyObject* other, int opid) {
*reinterpret_cast<CMessage*>(other)->message)) {
equals = false;
}
+
if (equals ^ (opid == Py_EQ)) {
Py_RETURN_FALSE;
} else {
@@ -2498,7 +2583,7 @@ PyObject* DeepCopy(CMessage* self, PyObject* arg) {
if (clone == NULL) {
return NULL;
}
- if (!PyObject_TypeCheck(clone, &CMessage_Type)) {
+ if (!PyObject_TypeCheck(clone, CMessage_Type)) {
Py_DECREF(clone);
return NULL;
}
@@ -2592,26 +2677,29 @@ PyObject* _CheckCalledFromGeneratedFile(PyObject* unused,
}
static PyObject* GetExtensionDict(CMessage* self, void *closure) {
- if (self->extensions) {
- Py_INCREF(self->extensions);
- return reinterpret_cast<PyObject*>(self->extensions);
- }
-
// If there are extension_ranges, the message is "extendable". Allocate a
// dictionary to store the extension fields.
const Descriptor* descriptor = GetMessageDescriptor(Py_TYPE(self));
- if (descriptor->extension_range_count() > 0) {
- ExtensionDict* extension_dict = extension_dict::NewExtensionDict(self);
- if (extension_dict == NULL) {
- return NULL;
- }
- self->extensions = extension_dict;
- Py_INCREF(self->extensions);
- return reinterpret_cast<PyObject*>(self->extensions);
+ if (!descriptor->extension_range_count()) {
+ PyErr_SetNone(PyExc_AttributeError);
+ return NULL;
}
+ if (!self->composite_fields) {
+ self->composite_fields = new CMessage::CompositeFieldsMap();
+ }
+ if (!self->composite_fields) {
+ return NULL;
+ }
+ ExtensionDict* extension_dict = extension_dict::NewExtensionDict(self);
+ return reinterpret_cast<PyObject*>(extension_dict);
+}
- PyErr_SetNone(PyExc_AttributeError);
- return NULL;
+static PyObject* UnknownFieldSet(CMessage* self) {
+ if (self->unknown_field_set == NULL) {
+ self->unknown_field_set = unknown_fields::NewPyUnknownFields(self);
+ }
+ Py_INCREF(self->unknown_field_set);
+ return self->unknown_field_set;
}
static PyObject* GetExtensionsByName(CMessage *self, void *closure) {
@@ -2682,6 +2770,8 @@ static PyMethodDef Methods[] = {
"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." },
+ { "UnknownFields", (PyCFunction)UnknownFieldSet, METH_NOARGS,
+ "Parse unknown field set"},
{ "WhichOneof", (PyCFunction)WhichOneof, METH_O,
"Returns the name of the field set inside a oneof, "
"or None if no field is set." },
@@ -2693,30 +2783,53 @@ static PyMethodDef Methods[] = {
{ NULL, NULL}
};
-static bool SetCompositeField(
- CMessage* self, PyObject* name, PyObject* value) {
+static bool SetCompositeField(CMessage* self, const FieldDescriptor* field,
+ PyObject* value) {
if (self->composite_fields == NULL) {
- self->composite_fields = PyDict_New();
- if (self->composite_fields == NULL) {
- return false;
- }
+ self->composite_fields = new CMessage::CompositeFieldsMap();
}
- return PyDict_SetItem(self->composite_fields, name, value) == 0;
+ Py_INCREF(value);
+ Py_XDECREF((*self->composite_fields)[field]);
+ (*self->composite_fields)[field] = value;
+ return true;
}
PyObject* GetAttr(PyObject* pself, PyObject* name) {
CMessage* self = reinterpret_cast<CMessage*>(pself);
- PyObject* value = self->composite_fields ?
- PyDict_GetItem(self->composite_fields, name) : NULL;
- if (value != NULL) {
- Py_INCREF(value);
- return value;
+ PyObject* result = PyObject_GenericGetAttr(
+ reinterpret_cast<PyObject*>(self), name);
+ if (result != NULL) {
+ return result;
+ }
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ return NULL;
}
- const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
- if (field_descriptor == NULL) {
- return CMessage_Type.tp_base->tp_getattro(
- reinterpret_cast<PyObject*>(self), name);
+ PyErr_Clear();
+ return message_meta::GetClassAttribute(
+ CheckMessageClass(Py_TYPE(self)), name);
+}
+
+PyObject* GetFieldValue(CMessage* self,
+ const FieldDescriptor* field_descriptor) {
+ if (self->composite_fields) {
+ CMessage::CompositeFieldsMap::iterator it =
+ self->composite_fields->find(field_descriptor);
+ if (it != self->composite_fields->end()) {
+ PyObject* value = it->second;
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ const Descriptor* message_descriptor =
+ (reinterpret_cast<CMessageClass*>(Py_TYPE(self)))->message_descriptor;
+ if (self->message->GetDescriptor() != field_descriptor->containing_type()) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor to field '%s' doesn't apply to '%s' object",
+ field_descriptor->full_name().c_str(),
+ Py_TYPE(self)->tp_name);
+ return NULL;
}
if (field_descriptor->is_map()) {
@@ -2737,7 +2850,7 @@ PyObject* GetAttr(PyObject* pself, PyObject* name) {
if (py_container == NULL) {
return NULL;
}
- if (!SetCompositeField(self, name, py_container)) {
+ if (!SetCompositeField(self, field_descriptor, py_container)) {
Py_DECREF(py_container);
return NULL;
}
@@ -2761,7 +2874,7 @@ PyObject* GetAttr(PyObject* pself, PyObject* name) {
if (py_container == NULL) {
return NULL;
}
- if (!SetCompositeField(self, name, py_container)) {
+ if (!SetCompositeField(self, field_descriptor, py_container)) {
Py_DECREF(py_container);
return NULL;
}
@@ -2773,7 +2886,7 @@ PyObject* GetAttr(PyObject* pself, PyObject* name) {
if (sub_message == NULL) {
return NULL;
}
- if (!SetCompositeField(self, name, sub_message)) {
+ if (!SetCompositeField(self, field_descriptor, sub_message)) {
Py_DECREF(sub_message);
return NULL;
}
@@ -2783,44 +2896,35 @@ PyObject* GetAttr(PyObject* pself, PyObject* name) {
return InternalGetScalar(self->message, field_descriptor);
}
-int SetAttr(PyObject* pself, PyObject* name, PyObject* value) {
- CMessage* self = reinterpret_cast<CMessage*>(pself);
- if (self->composite_fields && PyDict_Contains(self->composite_fields, name)) {
- PyErr_SetString(PyExc_TypeError, "Can't set composite field");
+int SetFieldValue(CMessage* self, const FieldDescriptor* field_descriptor,
+ PyObject* value) {
+ if (self->message->GetDescriptor() != field_descriptor->containing_type()) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor to field '%s' doesn't apply to '%s' object",
+ field_descriptor->full_name().c_str(),
+ Py_TYPE(self)->tp_name);
return -1;
- }
-
- const FieldDescriptor* field_descriptor = GetFieldDescriptor(self, name);
- if (field_descriptor != NULL) {
+ } else if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
+ PyErr_Format(PyExc_AttributeError,
+ "Assignment not allowed to repeated "
+ "field \"%s\" in protocol message object.",
+ field_descriptor->name().c_str());
+ return -1;
+ } else if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ PyErr_Format(PyExc_AttributeError,
+ "Assignment not allowed to "
+ "field \"%s\" in protocol message object.",
+ field_descriptor->name().c_str());
+ return -1;
+ } else {
AssureWritable(self);
- if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
- PyErr_Format(PyExc_AttributeError, "Assignment not allowed to repeated "
- "field \"%s\" in protocol message object.",
- field_descriptor->name().c_str());
- return -1;
- } else {
- if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- PyErr_Format(PyExc_AttributeError, "Assignment not allowed to "
- "field \"%s\" in protocol message object.",
- field_descriptor->name().c_str());
- return -1;
- } else {
- return InternalSetScalar(self, field_descriptor, value);
- }
- }
+ return InternalSetScalar(self, field_descriptor, value);
}
-
- PyErr_Format(PyExc_AttributeError,
- "Assignment not allowed "
- "(no field \"%s\" in protocol message object).",
- PyString_AsString(name));
- return -1;
}
-
} // namespace cmessage
-PyTypeObject CMessage_Type = {
- PyVarObject_HEAD_INIT(&CMessageClass_Type, 0)
+static CMessageClass _CMessage_Type = { { {
+ PyVarObject_HEAD_INIT(&_CMessageClass_Type, 0)
FULL_MODULE_NAME ".CMessage", // tp_name
sizeof(CMessage), // tp_basicsize
0, // tp_itemsize
@@ -2837,9 +2941,10 @@ PyTypeObject CMessage_Type = {
0, // tp_call
(reprfunc)cmessage::ToStr, // tp_str
cmessage::GetAttr, // tp_getattro
- cmessage::SetAttr, // tp_setattro
+ 0, // tp_setattro
0, // tp_as_buffer
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
+ | Py_TPFLAGS_HAVE_VERSION_TAG, // tp_flags
"A ProtocolMessage", // tp_doc
0, // tp_traverse
0, // tp_clear
@@ -2858,7 +2963,8 @@ PyTypeObject CMessage_Type = {
(initproc)cmessage::Init, // tp_init
0, // tp_alloc
cmessage::New, // tp_new
-};
+} } };
+PyTypeObject* CMessage_Type = &_CMessage_Type.super.ht_type;
// --- Exposing the C proto living inside Python proto to C code:
@@ -2866,25 +2972,48 @@ const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg);
Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg);
static const Message* GetCProtoInsidePyProtoImpl(PyObject* msg) {
- if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
+ const Message* message = PyMessage_GetMessagePointer(msg);
+ if (message == NULL) {
+ PyErr_Clear();
+ return NULL;
+ }
+ return message;
+}
+
+static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
+ Message* message = PyMessage_GetMutableMessagePointer(msg);
+ if (message == NULL) {
+ PyErr_Clear();
+ return NULL;
+ }
+ return message;
+}
+
+const Message* PyMessage_GetMessagePointer(PyObject* msg) {
+ if (!PyObject_TypeCheck(msg, CMessage_Type)) {
+ PyErr_SetString(PyExc_TypeError, "Not a Message instance");
return NULL;
}
CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
return cmsg->message;
}
-static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
- if (!PyObject_TypeCheck(msg, &CMessage_Type)) {
+Message* PyMessage_GetMutableMessagePointer(PyObject* msg) {
+ if (!PyObject_TypeCheck(msg, CMessage_Type)) {
+ PyErr_SetString(PyExc_TypeError, "Not a Message instance");
return NULL;
}
+
+
CMessage* cmsg = reinterpret_cast<CMessage*>(msg);
- if ((cmsg->composite_fields && PyDict_Size(cmsg->composite_fields) != 0) ||
- (cmsg->extensions != NULL &&
- PyDict_Size(cmsg->extensions->values) != 0)) {
+ if (cmsg->composite_fields && !cmsg->composite_fields->empty()) {
// There is currently no way of accurately syncing arbitrary changes to
// the underlying C++ message back to the CMessage (e.g. removed repeated
// composite containers). We only allow direct mutation of the underlying
// C++ message if there is no child data in the CMessage.
+ PyErr_SetString(PyExc_ValueError,
+ "Cannot reliably get a mutable pointer "
+ "to a message with extra references");
return NULL;
}
cmessage::AssureWritable(cmsg);
@@ -2921,22 +3050,29 @@ bool InitProto2MessageModule(PyObject *m) {
// Initialize constants defined in this file.
InitGlobals();
- CMessageClass_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&CMessageClass_Type) < 0) {
+ CMessageClass_Type->tp_base = &PyType_Type;
+ if (PyType_Ready(CMessageClass_Type) < 0) {
return false;
}
PyModule_AddObject(m, "MessageMeta",
- reinterpret_cast<PyObject*>(&CMessageClass_Type));
+ reinterpret_cast<PyObject*>(CMessageClass_Type));
- if (PyType_Ready(&CMessage_Type) < 0) {
+ if (PyType_Ready(CMessage_Type) < 0) {
+ return false;
+ }
+ if (PyType_Ready(CFieldProperty_Type) < 0) {
return false;
}
// DESCRIPTOR is set on each protocol buffer message class elsewhere, but set
// it here as well to document that subclasses need to set it.
- PyDict_SetItem(CMessage_Type.tp_dict, kDESCRIPTOR, Py_None);
+ PyDict_SetItem(CMessage_Type->tp_dict, kDESCRIPTOR, Py_None);
+ // Invalidate any cached data for the CMessage type.
+ // This call is necessary to correctly support Py_TPFLAGS_HAVE_VERSION_TAG,
+ // after we have modified CMessage_Type.tp_dict.
+ PyType_Modified(CMessage_Type);
- PyModule_AddObject(m, "Message", reinterpret_cast<PyObject*>(&CMessage_Type));
+ PyModule_AddObject(m, "Message", reinterpret_cast<PyObject*>(CMessage_Type));
// Initialize Repeated container types.
{
@@ -2979,6 +3115,22 @@ bool InitProto2MessageModule(PyObject *m) {
}
}
+ if (PyType_Ready(&PyUnknownFields_Type) < 0) {
+ return false;
+ }
+
+ PyModule_AddObject(m, "UnknownFieldSet",
+ reinterpret_cast<PyObject*>(
+ &PyUnknownFields_Type));
+
+ if (PyType_Ready(&PyUnknownFieldRef_Type) < 0) {
+ return false;
+ }
+
+ PyModule_AddObject(m, "UnknownField",
+ reinterpret_cast<PyObject*>(
+ &PyUnknownFieldRef_Type));
+
// Initialize Map container types.
if (!InitMapContainers()) {
return false;
diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h
index 72bcfa83..c112a88f 100644
--- a/python/google/protobuf/pyext/message.h
+++ b/python/google/protobuf/pyext/message.h
@@ -38,6 +38,7 @@
#include <memory>
#include <string>
+#include <unordered_map>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/pyext/thread_unsafe_shared_ptr.h>
@@ -96,26 +97,25 @@ typedef struct CMessage {
// made writable, at which point this field is set to false.
bool read_only;
- // A reference to a Python dictionary containing CMessage,
+ // A mapping indexed by field, containing CMessage,
// RepeatedCompositeContainer, and RepeatedScalarContainer
// objects. Used as a cache to make sure we don't have to make a
// Python wrapper for the C++ Message objects on every access, or
// deal with the synchronization nightmare that could create.
- PyObject* composite_fields;
+ // Also cache extension fields.
+ // The FieldDescriptor is owned by the message's pool; PyObject references
+ // are owned.
+ typedef std::unordered_map<const FieldDescriptor*, PyObject*>
+ CompositeFieldsMap;
+ CompositeFieldsMap* composite_fields;
- // A reference to the dictionary containing the message's extensions.
- // Similar to composite_fields, acting as a cache, but also contains the
- // required extension dict logic.
- ExtensionDict* extensions;
+ // A reference to PyUnknownFields.
+ PyObject* unknown_field_set;
// Implements the "weakref" protocol for this object.
PyObject* weakreflist;
} CMessage;
-extern PyTypeObject CMessageClass_Type;
-extern PyTypeObject CMessage_Type;
-
-
// The (meta) type of all Messages classes.
// It allows us to cache some C++ pointers in the class object itself, they are
// faster to extract than from the type's dictionary.
@@ -142,6 +142,8 @@ struct CMessageClass {
}
};
+extern PyTypeObject* CMessageClass_Type;
+extern PyTypeObject* CMessage_Type;
namespace cmessage {
@@ -164,13 +166,13 @@ PyObject* InternalGetSubMessage(
// Deletes a range of C++ submessages in a repeated field (following a
// removal in a RepeatedCompositeContainer).
//
-// Releases messages to the provided cmessage_list if it is not NULL rather
+// Releases submessages to the provided cmessage_list if it is not NULL rather
// than just removing them from the underlying proto. This cmessage_list must
// have a CMessage for each underlying submessage. The CMessages referred to
// by slice will be removed from cmessage_list by this function.
//
// Corresponds to reflection api method RemoveLast.
-int InternalDeleteRepeatedField(CMessage* self,
+int InternalDeleteRepeatedField(Message* message,
const FieldDescriptor* field_descriptor,
PyObject* slice, PyObject* cmessage_list);
@@ -235,15 +237,13 @@ PyObject* MergeFrom(CMessage* self, PyObject* arg);
// has been registered with the same field number on this class.
PyObject* RegisterExtension(PyObject* cls, PyObject* extension_handle);
-// Retrieves an attribute named 'name' from 'self', which is interpreted as a
-// CMessage. Returns the attribute value on success, or null on failure.
-//
-// Returns a new reference.
-PyObject* GetAttr(PyObject* self, PyObject* name);
-
-// Set the value of the attribute named 'name', for 'self', which is interpreted
-// as a CMessage, to the value 'value'. Returns -1 on failure.
-int SetAttr(PyObject* self, PyObject* name, PyObject* value);
+// Get a field from a message.
+PyObject* GetFieldValue(CMessage* self,
+ const FieldDescriptor* field_descriptor);
+// Sets the value of a scalar field in a message.
+// On error, return -1 with an extension set.
+int SetFieldValue(CMessage* self, const FieldDescriptor* field_descriptor,
+ PyObject* value);
PyObject* FindInitializationErrors(CMessage* self);
@@ -332,7 +332,7 @@ bool CheckAndSetString(
bool append,
int index);
PyObject* ToStringObject(const FieldDescriptor* descriptor,
- const string& value);
+ const std::string& value);
// Check if the passed field descriptor belongs to the given message.
// If not, return false and set a Python exception (a KeyError)
@@ -341,6 +341,9 @@ bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
extern PyObject* PickleError_class;
+const Message* PyMessage_GetMessagePointer(PyObject* msg);
+Message* PyMessage_GetMutableMessagePointer(PyObject* msg);
+
bool InitProto2MessageModule(PyObject *m);
#if LANG_CXX11
@@ -354,6 +357,6 @@ extern template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_H__
diff --git a/python/google/protobuf/pyext/message_factory.cc b/python/google/protobuf/pyext/message_factory.cc
index bacc76a6..efaa2617 100644
--- a/python/google/protobuf/pyext/message_factory.cc
+++ b/python/google/protobuf/pyext/message_factory.cc
@@ -28,6 +28,8 @@
// (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 <unordered_map>
+
#include <Python.h>
#include <google/protobuf/dynamic_message.h>
@@ -137,7 +139,7 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
// This is the same implementation as MessageFactory.GetPrototype().
// Do not create a MessageClass that already exists.
- hash_map<const Descriptor*, CMessageClass*>::iterator it =
+ std::unordered_map<const Descriptor*, CMessageClass*>::iterator it =
self->classes_by_descriptor->find(descriptor);
if (it != self->classes_by_descriptor->end()) {
Py_INCREF(it->second);
@@ -158,7 +160,7 @@ CMessageClass* GetOrCreateMessageClass(PyMessageFactory* self,
return NULL;
}
ScopedPyObjectPtr message_class(PyObject_CallObject(
- reinterpret_cast<PyObject*>(&CMessageClass_Type), args.get()));
+ reinterpret_cast<PyObject*>(CMessageClass_Type), args.get()));
if (message_class == NULL) {
return NULL;
}
diff --git a/python/google/protobuf/pyext/message_factory.h b/python/google/protobuf/pyext/message_factory.h
index 36092f7e..06444b0a 100644
--- a/python/google/protobuf/pyext/message_factory.h
+++ b/python/google/protobuf/pyext/message_factory.h
@@ -33,7 +33,7 @@
#include <Python.h>
-#include <google/protobuf/stubs/hash.h>
+#include <unordered_map>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
@@ -66,7 +66,8 @@ struct PyMessageFactory {
//
// Descriptor pointers stored here are owned by the DescriptorPool above.
// Python references to classes are owned by this PyDescriptorPool.
- typedef hash_map<const Descriptor*, CMessageClass*> ClassesByMessageMap;
+ typedef std::unordered_map<const Descriptor*, CMessageClass*>
+ ClassesByMessageMap;
ClassesByMessageMap* classes_by_descriptor;
};
@@ -98,6 +99,6 @@ bool InitMessageFactory();
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
diff --git a/python/google/protobuf/pyext/message_module.cc b/python/google/protobuf/pyext/message_module.cc
index 7c4df47f..8d465eb5 100644
--- a/python/google/protobuf/pyext/message_module.cc
+++ b/python/google/protobuf/pyext/message_module.cc
@@ -31,29 +31,23 @@
#include <Python.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/proto_api.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;
- }
-}
+namespace {
-static PyObject* SetPythonProto3PreserveUnknownsDefault(
- PyObject* /*m*/, PyObject* arg) {
- if (!arg || !PyBool_Check(arg)) {
- PyErr_SetString(
- PyExc_TypeError,
- "Argument to SetPythonProto3PreserveUnknownsDefault must be boolean");
- return NULL;
+// C++ API. Clients get at this via proto_api.h
+struct ApiImplementation : google::protobuf::python::PyProto_API {
+ const google::protobuf::Message* GetMessagePointer(PyObject* msg) const override {
+ return google::protobuf::python::PyMessage_GetMessagePointer(msg);
}
- google::protobuf::internal::SetProto3PreserveUnknownsDefault(PyObject_IsTrue(arg));
- Py_RETURN_NONE;
-}
+ google::protobuf::Message* GetMutableMessagePointer(PyObject* msg) const override {
+ return google::protobuf::python::PyMessage_GetMutableMessagePointer(msg);
+ }
+};
+
+} // namespace
static const char module_docstring[] =
"python-proto2 is a module that can be used to enhance proto2 Python API\n"
@@ -67,13 +61,6 @@ static PyMethodDef ModuleMethods[] = {
(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}
};
@@ -96,26 +83,32 @@ static struct PyModuleDef _module = {
#define INITFUNC_ERRORVAL
#endif
-extern "C" {
- PyMODINIT_FUNC INITFUNC(void) {
- PyObject* m;
+PyMODINIT_FUNC INITFUNC() {
+ PyObject* m;
#if PY_MAJOR_VERSION >= 3
- m = PyModule_Create(&_module);
+ m = PyModule_Create(&_module);
#else
- m = Py_InitModule3("_message", ModuleMethods,
- module_docstring);
+ m = Py_InitModule3("_message", ModuleMethods, module_docstring);
#endif
- if (m == NULL) {
- return INITFUNC_ERRORVAL;
- }
+ if (m == NULL) {
+ return INITFUNC_ERRORVAL;
+ }
- if (!google::protobuf::python::InitProto2MessageModule(m)) {
- Py_DECREF(m);
- return INITFUNC_ERRORVAL;
- }
+ if (!google::protobuf::python::InitProto2MessageModule(m)) {
+ Py_DECREF(m);
+ return INITFUNC_ERRORVAL;
+ }
+
+ // Adds the C++ API
+ if (PyObject* api =
+ PyCapsule_New(new ApiImplementation(),
+ google::protobuf::python::PyProtoAPICapsuleName(), NULL)) {
+ PyModule_AddObject(m, "proto_API", api);
+ } else {
+ return INITFUNC_ERRORVAL;
+ }
#if PY_MAJOR_VERSION >= 3
- return m;
+ return m;
#endif
- }
}
diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc
index 5874d5de..ca700580 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.cc
+++ b/python/google/protobuf/pyext/repeated_composite_container.cc
@@ -61,9 +61,9 @@ namespace repeated_composite_container {
// TODO(tibell): We might also want to check:
// GOOGLE_CHECK_NOTNULL((self)->owner.get());
-#define GOOGLE_CHECK_ATTACHED(self) \
- do { \
- GOOGLE_CHECK_NOTNULL((self)->message); \
+#define GOOGLE_CHECK_ATTACHED(self) \
+ do { \
+ GOOGLE_CHECK_NOTNULL((self)->message); \
GOOGLE_CHECK_NOTNULL((self)->parent_field_descriptor); \
} while (0);
@@ -152,6 +152,8 @@ static PyObject* AddToAttached(RepeatedCompositeContainer* self,
cmsg->message = sub_message;
cmsg->parent = self->parent;
if (cmessage::InitAttributes(cmsg, args, kwargs) < 0) {
+ message->GetReflection()->RemoveLast(
+ message, self->parent_field_descriptor);
Py_DECREF(cmsg);
return NULL;
}
@@ -210,7 +212,7 @@ PyObject* Extend(RepeatedCompositeContainer* self, PyObject* value) {
}
ScopedPyObjectPtr next;
while ((next.reset(PyIter_Next(iter.get()))) != NULL) {
- if (!PyObject_TypeCheck(next.get(), &CMessage_Type)) {
+ if (!PyObject_TypeCheck(next.get(), CMessage_Type)) {
PyErr_SetString(PyExc_TypeError, "Not a cmessage");
return NULL;
}
@@ -270,8 +272,8 @@ int AssignSubscript(RepeatedCompositeContainer* self,
}
// Delete from the underlying Message, if any.
- if (self->parent != NULL) {
- if (cmessage::InternalDeleteRepeatedField(self->parent,
+ if (self->message != nullptr) {
+ if (cmessage::InternalDeleteRepeatedField(self->message,
self->parent_field_descriptor,
slice,
self->child_messages) < 0) {
@@ -484,15 +486,15 @@ static PyObject* Pop(PyObject* pself, PyObject* args) {
}
// Release field of parent message and transfer the ownership to target.
-void ReleaseLastTo(CMessage* parent,
+void ReleaseLastTo(Message* message,
const FieldDescriptor* field,
CMessage* target) {
- GOOGLE_CHECK_NOTNULL(parent);
- GOOGLE_CHECK_NOTNULL(field);
- GOOGLE_CHECK_NOTNULL(target);
+ GOOGLE_CHECK(message != nullptr);
+ GOOGLE_CHECK(field != nullptr);
+ GOOGLE_CHECK(target != nullptr);
CMessage::OwnerRef released_message(
- parent->message->GetReflection()->ReleaseLast(parent->message, field));
+ message->GetReflection()->ReleaseLast(message, field));
// TODO(tibell): Deal with proto1.
target->parent = NULL;
@@ -522,7 +524,7 @@ int Release(RepeatedCompositeContainer* self) {
for (Py_ssize_t i = size - 1; i >= 0; --i) {
CMessage* child_cmessage = reinterpret_cast<CMessage*>(
PyList_GET_ITEM(self->child_messages, i));
- ReleaseLastTo(self->parent, field, child_cmessage);
+ ReleaseLastTo(message, field, child_cmessage);
}
// Detach from containing message.
diff --git a/python/google/protobuf/pyext/repeated_composite_container.h b/python/google/protobuf/pyext/repeated_composite_container.h
index e5e946aa..d0755771 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.h
+++ b/python/google/protobuf/pyext/repeated_composite_container.h
@@ -154,13 +154,13 @@ int SetOwner(RepeatedCompositeContainer* self,
// Message to 'target'.
//
// Corresponds to reflection api method ReleaseMessage.
-void ReleaseLastTo(CMessage* parent,
+void ReleaseLastTo(Message* message,
const FieldDescriptor* field,
CMessage* target);
} // namespace repeated_composite_container
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_COMPOSITE_CONTAINER_H__
diff --git a/python/google/protobuf/pyext/repeated_scalar_container.cc b/python/google/protobuf/pyext/repeated_scalar_container.cc
index de3b6e14..ac06cff3 100644
--- a/python/google/protobuf/pyext/repeated_scalar_container.cc
+++ b/python/google/protobuf/pyext/repeated_scalar_container.cc
@@ -104,7 +104,8 @@ static int AssignItem(PyObject* pself, Py_ssize_t index, PyObject* arg) {
if (arg == NULL) {
ScopedPyObjectPtr py_index(PyLong_FromLong(index));
- return cmessage::InternalDeleteRepeatedField(self->parent, field_descriptor,
+ return cmessage::InternalDeleteRepeatedField(self->message,
+ field_descriptor,
py_index.get(), NULL);
}
@@ -467,7 +468,7 @@ static int AssSubscript(PyObject* pself, PyObject* slice, PyObject* value) {
if (value == NULL) {
return cmessage::InternalDeleteRepeatedField(
- self->parent, field_descriptor, slice, NULL);
+ self->message, field_descriptor, slice, nullptr);
}
if (!create_list) {
@@ -663,6 +664,10 @@ static PyObject* ToStr(PyObject* pself) {
return PyObject_Repr(list.get());
}
+static PyObject* MergeFrom(PyObject* pself, PyObject* arg) {
+ return Extend(reinterpret_cast<RepeatedScalarContainer*>(pself), arg);
+}
+
// The private constructor of RepeatedScalarContainer objects.
PyObject *NewContainer(
CMessage* parent, const FieldDescriptor* parent_field_descriptor) {
@@ -776,6 +781,8 @@ static PyMethodDef Methods[] = {
"Removes an object from the repeated container." },
{ "sort", (PyCFunction)Sort, METH_VARARGS | METH_KEYWORDS,
"Sorts the repeated container."},
+ { "MergeFrom", (PyCFunction)MergeFrom, METH_O,
+ "Merges a repeated container into the current container." },
{ NULL, NULL }
};
diff --git a/python/google/protobuf/pyext/repeated_scalar_container.h b/python/google/protobuf/pyext/repeated_scalar_container.h
index 559dec98..4dcecbac 100644
--- a/python/google/protobuf/pyext/repeated_scalar_container.h
+++ b/python/google/protobuf/pyext/repeated_scalar_container.h
@@ -104,6 +104,6 @@ void SetOwner(RepeatedScalarContainer* self,
} // namespace repeated_scalar_container
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_REPEATED_SCALAR_CONTAINER_H__
diff --git a/python/google/protobuf/pyext/safe_numerics.h b/python/google/protobuf/pyext/safe_numerics.h
index 639ba2c8..93ae640e 100644
--- a/python/google/protobuf/pyext/safe_numerics.h
+++ b/python/google/protobuf/pyext/safe_numerics.h
@@ -132,10 +132,10 @@ template <class Dest, class Source>
inline bool IsValidNumericCast(Source source) {
typedef std::numeric_limits<Source> SourceLimits;
typedef std::numeric_limits<Dest> DestLimits;
- GOOGLE_COMPILE_ASSERT(SourceLimits::is_specialized, argument_must_be_numeric);
- GOOGLE_COMPILE_ASSERT(SourceLimits::is_integer, argument_must_be_integral);
- GOOGLE_COMPILE_ASSERT(DestLimits::is_specialized, result_must_be_numeric);
- GOOGLE_COMPILE_ASSERT(DestLimits::is_integer, result_must_be_integral);
+ static_assert(SourceLimits::is_specialized, "argument must be numeric");
+ static_assert(SourceLimits::is_integer, "argument must be integral");
+ static_assert(DestLimits::is_specialized, "result must be numeric");
+ static_assert(DestLimits::is_integer, "result must be integral");
return IsValidNumericCastImpl<
sizeof(Dest) == sizeof(Source),
@@ -150,7 +150,7 @@ inline bool IsValidNumericCast(Source source) {
// checked_numeric_cast<> is analogous to static_cast<> for numeric types,
// except that it CHECKs that the specified numeric conversion will not
// overflow or underflow. Floating point arguments are not currently allowed
-// (this is COMPILE_ASSERTd), though this could be supported if necessary.
+// (this is static_asserted), though this could be supported if necessary.
template <class Dest, class Source>
inline Dest checked_numeric_cast(Source source) {
GOOGLE_CHECK(IsValidNumericCast<Dest>(source));
@@ -159,6 +159,6 @@ inline Dest checked_numeric_cast(Source source) {
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_SAFE_NUMERICS_H__
diff --git a/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h b/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h
index ad804b5f..79fa9e3d 100644
--- a/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h
+++ b/python/google/protobuf/pyext/thread_unsafe_shared_ptr.h
@@ -99,6 +99,6 @@ class ThreadUnsafeSharedPtr {
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_CPP_THREAD_UNSAFE_SHARED_PTR_H__
diff --git a/python/google/protobuf/pyext/unknown_fields.cc b/python/google/protobuf/pyext/unknown_fields.cc
new file mode 100755
index 00000000..760452f2
--- /dev/null
+++ b/python/google/protobuf/pyext/unknown_fields.cc
@@ -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.
+
+#include <google/protobuf/pyext/unknown_fields.h>
+
+#include <Python.h>
+#include <set>
+#include <memory>
+
+#include <google/protobuf/message.h>
+#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
+#include <google/protobuf/unknown_field_set.h>
+#include <google/protobuf/wire_format_lite.h>
+
+#if PY_MAJOR_VERSION >= 3
+ #define PyInt_FromLong PyLong_FromLong
+#endif
+
+namespace google {
+namespace protobuf {
+namespace python {
+
+namespace unknown_fields {
+
+static Py_ssize_t Len(PyObject* pself) {
+ PyUnknownFields* self =
+ reinterpret_cast<PyUnknownFields*>(pself);
+ if (self->fields == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "UnknownFields does not exist. "
+ "The parent message might be cleared.");
+ return -1;
+ }
+ return self->fields->field_count();
+}
+
+void Clear(PyUnknownFields* self) {
+ for (std::set<PyUnknownFields*>::iterator it =
+ self->sub_unknown_fields.begin();
+ it != self->sub_unknown_fields.end(); it++) {
+ Clear(*it);
+ }
+ self->fields = NULL;
+ self->sub_unknown_fields.clear();
+}
+
+PyObject* NewPyUnknownFieldRef(PyUnknownFields* parent,
+ Py_ssize_t index);
+
+static PyObject* Item(PyObject* pself, Py_ssize_t index) {
+ PyUnknownFields* self =
+ reinterpret_cast<PyUnknownFields*>(pself);
+ if (self->fields == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "UnknownFields does not exist. "
+ "The parent message might be cleared.");
+ return NULL;
+ }
+ Py_ssize_t total_size = self->fields->field_count();
+ if (index < 0) {
+ index = total_size + index;
+ }
+ if (index < 0 || index >= total_size) {
+ PyErr_Format(PyExc_IndexError,
+ "index (%zd) out of range",
+ index);
+ return NULL;
+ }
+
+ return unknown_fields::NewPyUnknownFieldRef(self, index);
+}
+
+PyObject* NewPyUnknownFields(CMessage* c_message) {
+ PyUnknownFields* self = reinterpret_cast<PyUnknownFields*>(
+ PyType_GenericAlloc(&PyUnknownFields_Type, 0));
+ if (self == NULL) {
+ return NULL;
+ }
+ // Call "placement new" to initialize PyUnknownFields.
+ new (self) PyUnknownFields;
+
+ Py_INCREF(c_message);
+ self->parent = reinterpret_cast<PyObject*>(c_message);
+ Message* message = c_message->message;
+ const Reflection* reflection = message->GetReflection();
+ self->fields = &reflection->GetUnknownFields(*message);
+
+ return reinterpret_cast<PyObject*>(self);
+}
+
+PyObject* NewPyUnknownFieldRef(PyUnknownFields* parent,
+ Py_ssize_t index) {
+ PyUnknownFieldRef* self = reinterpret_cast<PyUnknownFieldRef*>(
+ PyType_GenericAlloc(&PyUnknownFieldRef_Type, 0));
+ if (self == NULL) {
+ return NULL;
+ }
+
+ Py_INCREF(parent);
+ self->parent = parent;
+ self->index = index;
+
+ return reinterpret_cast<PyObject*>(self);
+}
+
+static void Dealloc(PyObject* pself) {
+ PyUnknownFields* self =
+ reinterpret_cast<PyUnknownFields*>(pself);
+ if (PyObject_TypeCheck(self->parent, &PyUnknownFields_Type)) {
+ reinterpret_cast<PyUnknownFields*>(
+ self->parent)->sub_unknown_fields.erase(self);
+ }
+ Py_CLEAR(self->parent);
+ self->~PyUnknownFields();
+}
+
+static PySequenceMethods SqMethods = {
+ Len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ Item, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+};
+
+} // namespace unknown_fields
+
+PyTypeObject PyUnknownFields_Type = {
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ FULL_MODULE_NAME ".PyUnknownFields", // tp_name
+ sizeof(PyUnknownFields), // tp_basicsize
+ 0, // tp_itemsize
+ unknown_fields::Dealloc, // tp_dealloc
+ 0, // tp_print
+ 0, // tp_getattr
+ 0, // tp_setattr
+ 0, // tp_compare
+ 0, // tp_repr
+ 0, // tp_as_number
+ &unknown_fields::SqMethods, // tp_as_sequence
+ 0, // tp_as_mapping
+ PyObject_HashNotImplemented, // tp_hash
+ 0, // tp_call
+ 0, // tp_str
+ 0, // tp_getattro
+ 0, // tp_setattro
+ 0, // tp_as_buffer
+ Py_TPFLAGS_DEFAULT, // tp_flags
+ "unknown field set", // tp_doc
+ 0, // tp_traverse
+ 0, // tp_clear
+ 0, // tp_richcompare
+ 0, // tp_weaklistoffset
+ 0, // tp_iter
+ 0, // tp_iternext
+ 0, // tp_methods
+ 0, // tp_members
+ 0, // tp_getset
+ 0, // tp_base
+ 0, // tp_dict
+ 0, // tp_descr_get
+ 0, // tp_descr_set
+ 0, // tp_dictoffset
+ 0, // tp_init
+};
+
+namespace unknown_field {
+static PyObject* PyUnknownFields_FromUnknownFieldSet(
+ PyUnknownFields* parent, const UnknownFieldSet& fields) {
+ PyUnknownFields* self = reinterpret_cast<PyUnknownFields*>(
+ PyType_GenericAlloc(&PyUnknownFields_Type, 0));
+ if (self == NULL) {
+ return NULL;
+ }
+ // Call "placement new" to initialize PyUnknownFields.
+ new (self) PyUnknownFields;
+
+ Py_INCREF(parent);
+ self->parent = reinterpret_cast<PyObject*>(parent);
+ self->fields = &fields;
+ parent->sub_unknown_fields.emplace(self);
+
+ return reinterpret_cast<PyObject*>(self);
+}
+
+const UnknownField* GetUnknownField(PyUnknownFieldRef* self) {
+ const UnknownFieldSet* fields = self->parent->fields;
+ if (fields == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "UnknownField does not exist. "
+ "The parent message might be cleared.");
+ return NULL;
+ }
+ ssize_t total_size = fields->field_count();
+ if (self->index >= total_size) {
+ PyErr_Format(PyExc_ValueError,
+ "UnknownField does not exist. "
+ "The parent message might be cleared.");
+ return NULL;
+ }
+ return &fields->field(self->index);
+}
+
+static PyObject* GetFieldNumber(PyUnknownFieldRef* self, void *closure) {
+ const UnknownField* unknown_field = GetUnknownField(self);
+ if (unknown_field == NULL) {
+ return NULL;
+ }
+ return PyInt_FromLong(unknown_field->number());
+}
+
+using internal::WireFormatLite;
+static PyObject* GetWireType(PyUnknownFieldRef* self, void *closure) {
+ const UnknownField* unknown_field = GetUnknownField(self);
+ if (unknown_field == NULL) {
+ return NULL;
+ }
+
+ // Assign a default value to suppress may-unintialized warnings (errors
+ // when built in some places).
+ WireFormatLite::WireType wire_type = WireFormatLite::WIRETYPE_VARINT;
+ switch (unknown_field->type()) {
+ case UnknownField::TYPE_VARINT:
+ wire_type = WireFormatLite::WIRETYPE_VARINT;
+ break;
+ case UnknownField::TYPE_FIXED32:
+ wire_type = WireFormatLite::WIRETYPE_FIXED32;
+ break;
+ case UnknownField::TYPE_FIXED64:
+ wire_type = WireFormatLite::WIRETYPE_FIXED64;
+ break;
+ case UnknownField::TYPE_LENGTH_DELIMITED:
+ wire_type = WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
+ break;
+ case UnknownField::TYPE_GROUP:
+ wire_type = WireFormatLite::WIRETYPE_START_GROUP;
+ break;
+ }
+ return PyInt_FromLong(wire_type);
+}
+
+static PyObject* GetData(PyUnknownFieldRef* self, void *closure) {
+ const UnknownField* field = GetUnknownField(self);
+ if (field == NULL) {
+ return NULL;
+ }
+ PyObject* data = NULL;
+ switch (field->type()) {
+ case UnknownField::TYPE_VARINT:
+ data = PyInt_FromLong(field->varint());
+ break;
+ case UnknownField::TYPE_FIXED32:
+ data = PyInt_FromLong(field->fixed32());
+ break;
+ case UnknownField::TYPE_FIXED64:
+ data = PyInt_FromLong(field->fixed64());
+ break;
+ case UnknownField::TYPE_LENGTH_DELIMITED:
+ data = PyBytes_FromStringAndSize(field->length_delimited().data(),
+ field->GetLengthDelimitedSize());
+ break;
+ case UnknownField::TYPE_GROUP:
+ data = PyUnknownFields_FromUnknownFieldSet(
+ self->parent, field->group());
+ break;
+ }
+ return data;
+}
+
+static void Dealloc(PyObject* pself) {
+ PyUnknownFieldRef* self =
+ reinterpret_cast<PyUnknownFieldRef*>(pself);
+ Py_CLEAR(self->parent);
+}
+
+static PyGetSetDef Getters[] = {
+ {"field_number", (getter)GetFieldNumber, NULL},
+ {"wire_type", (getter)GetWireType, NULL},
+ {"data", (getter)GetData, NULL},
+ {NULL}
+};
+
+} // namespace unknown_field
+
+PyTypeObject PyUnknownFieldRef_Type = {
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ FULL_MODULE_NAME ".PyUnknownFieldRef", // tp_name
+ sizeof(PyUnknownFieldRef), // tp_basicsize
+ 0, // tp_itemsize
+ unknown_field::Dealloc, // tp_dealloc
+ 0, // tp_print
+ 0, // tp_getattr
+ 0, // tp_setattr
+ 0, // tp_compare
+ 0, // tp_repr
+ 0, // tp_as_number
+ 0, // tp_as_sequence
+ 0, // tp_as_mapping
+ PyObject_HashNotImplemented, // tp_hash
+ 0, // tp_call
+ 0, // tp_str
+ 0, // tp_getattro
+ 0, // tp_setattro
+ 0, // tp_as_buffer
+ Py_TPFLAGS_DEFAULT, // tp_flags
+ "unknown field", // tp_doc
+ 0, // tp_traverse
+ 0, // tp_clear
+ 0, // tp_richcompare
+ 0, // tp_weaklistoffset
+ 0, // tp_iter
+ 0, // tp_iternext
+ 0, // tp_methods
+ 0, // tp_members
+ unknown_field::Getters, // tp_getset
+ 0, // tp_base
+ 0, // tp_dict
+ 0, // tp_descr_get
+ 0, // tp_descr_set
+ 0, // tp_dictoffset
+ 0, // tp_init
+};
+
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
diff --git a/python/google/protobuf/pyext/unknown_fields.h b/python/google/protobuf/pyext/unknown_fields.h
new file mode 100755
index 00000000..94d55e14
--- /dev/null
+++ b/python/google/protobuf/pyext/unknown_fields.h
@@ -0,0 +1,90 @@
+// 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_PYTHON_CPP_UNKNOWN_FIELDS_H__
+#define GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELDS_H__
+
+#include <Python.h>
+
+#include <memory>
+#include <set>
+
+#include <google/protobuf/pyext/message.h>
+
+namespace google {
+namespace protobuf {
+
+class UnknownField;
+class UnknownFieldSet;
+
+namespace python {
+struct CMessage;
+
+typedef struct PyUnknownFields {
+ PyObject_HEAD;
+ // Strong pointer to the parent CMessage or PyUnknownFields.
+ // The top PyUnknownFields holds a reference to its parent CMessage
+ // object before release.
+ // Sub PyUnknownFields holds reference to parent PyUnknownFields.
+ PyObject* parent;
+
+ // Pointer to the C++ UnknownFieldSet.
+ // PyUnknownFields does not own this pointer.
+ const UnknownFieldSet* fields;
+
+ // Weak references to child unknown fields.
+ std::set<PyUnknownFields*> sub_unknown_fields;
+} PyUnknownFields;
+
+typedef struct PyUnknownFieldRef {
+ PyObject_HEAD;
+ // Every Python PyUnknownFieldRef holds a reference to its parent
+ // PyUnknownFields in order to keep it alive.
+ PyUnknownFields* parent;
+
+ // The UnknownField index in UnknownFields.
+ Py_ssize_t index;
+} UknownFieldRef;
+
+extern PyTypeObject PyUnknownFields_Type;
+extern PyTypeObject PyUnknownFieldRef_Type;
+
+namespace unknown_fields {
+
+// Builds an PyUnknownFields for a specific message.
+PyObject* NewPyUnknownFields(CMessage *parent);
+void Clear(PyUnknownFields* self);
+
+} // namespace unknown_fields
+} // namespace python
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELDS_H__
diff --git a/python/google/protobuf/python_protobuf.h b/python/google/protobuf/python_protobuf.h
index beb6e460..8db1ffb7 100644
--- a/python/google/protobuf/python_protobuf.h
+++ b/python/google/protobuf/python_protobuf.h
@@ -52,6 +52,6 @@ Message* MutableCProtoInsidePyProto(PyObject* msg);
} // namespace python
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__
diff --git a/python/google/protobuf/reflection.py b/python/google/protobuf/reflection.py
index f4ce8caf..81e18859 100755
--- a/python/google/protobuf/reflection.py
+++ b/python/google/protobuf/reflection.py
@@ -48,25 +48,23 @@ this file*.
__author__ = 'robinson@google.com (Will Robinson)'
-from google.protobuf.internal import api_implementation
-from google.protobuf import message
-
-
-if api_implementation.Type() == 'cpp':
- from google.protobuf.pyext import cpp_message as message_impl
-else:
- from google.protobuf.internal import python_message as message_impl
+from google.protobuf import message_factory
+from google.protobuf import symbol_database
# The type of all Message classes.
# Part of the public interface, but normally only used by message factories.
-GeneratedProtocolMessageType = message_impl.GeneratedProtocolMessageType
+GeneratedProtocolMessageType = message_factory._GENERATED_PROTOCOL_MESSAGE_TYPE
MESSAGE_CLASS_CACHE = {}
+# Deprecated. Please NEVER use reflection.ParseMessage().
def ParseMessage(descriptor, byte_str):
"""Generate a new Message instance from this Descriptor and a byte string.
+ DEPRECATED: ParseMessage is deprecated because it is using MakeClass().
+ Please use MessageFactory.GetPrototype() instead.
+
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
@@ -80,42 +78,18 @@ def ParseMessage(descriptor, byte_str):
return new_msg
+# Deprecated. Please NEVER use reflection.MakeClass().
def MakeClass(descriptor):
"""Construct a class object for a protobuf described by descriptor.
- Composite descriptors are handled by defining the new class as a member of the
- parent class, recursing as deep as necessary.
- This is the dynamic equivalent to:
-
- class Parent(message.Message):
- __metaclass__ = GeneratedProtocolMessageType
- DESCRIPTOR = descriptor
- class Child(message.Message):
- __metaclass__ = GeneratedProtocolMessageType
- DESCRIPTOR = descriptor.nested_types[0]
-
- Sample usage:
- file_descriptor = descriptor_pb2.FileDescriptorProto()
- file_descriptor.ParseFromString(proto2_string)
- msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
- msg_class = reflection.MakeClass(msg_descriptor)
- msg = msg_class()
+ DEPRECATED: use MessageFactory.GetPrototype() instead.
Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
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
-
- result = GeneratedProtocolMessageType(
- str(descriptor.name), (message.Message,), attributes)
- MESSAGE_CLASS_CACHE[descriptor] = result
- return result
+ # Original implementation leads to duplicate message classes, which won't play
+ # well with extensions. Message factory info is also missing.
+ # Redirect to message_factory.
+ return symbol_database.Default().GetPrototype(descriptor)
diff --git a/python/google/protobuf/text_encoding.py b/python/google/protobuf/text_encoding.py
index 98995638..39898765 100644
--- a/python/google/protobuf/text_encoding.py
+++ b/python/google/protobuf/text_encoding.py
@@ -33,59 +33,70 @@ import re
import six
-# Lookup table for utf8
-_cescape_utf8_to_str = [chr(i) for i in range(0, 256)]
-_cescape_utf8_to_str[9] = r'\t' # optional escape
-_cescape_utf8_to_str[10] = r'\n' # optional escape
-_cescape_utf8_to_str[13] = r'\r' # optional escape
-_cescape_utf8_to_str[39] = r"\'" # optional escape
-
-_cescape_utf8_to_str[34] = r'\"' # necessary escape
-_cescape_utf8_to_str[92] = r'\\' # necessary escape
+_cescape_chr_to_symbol_map = {}
+_cescape_chr_to_symbol_map[9] = r'\t' # optional escape
+_cescape_chr_to_symbol_map[10] = r'\n' # optional escape
+_cescape_chr_to_symbol_map[13] = r'\r' # optional escape
+_cescape_chr_to_symbol_map[34] = r'\"' # necessary escape
+_cescape_chr_to_symbol_map[39] = r"\'" # optional escape
+_cescape_chr_to_symbol_map[92] = r'\\' # necessary escape
+
+# Lookup table for unicode
+_cescape_unicode_to_str = [chr(i) for i in range(0, 256)]
+for byte, string in _cescape_chr_to_symbol_map.items():
+ _cescape_unicode_to_str[byte] = string
# Lookup table for non-utf8, with necessary escapes at (o >= 127 or o < 32)
_cescape_byte_to_str = ([r'\%03o' % i for i in range(0, 32)] +
[chr(i) for i in range(32, 127)] +
[r'\%03o' % i for i in range(127, 256)])
-_cescape_byte_to_str[9] = r'\t' # optional escape
-_cescape_byte_to_str[10] = r'\n' # optional escape
-_cescape_byte_to_str[13] = r'\r' # optional escape
-_cescape_byte_to_str[39] = r"\'" # optional escape
-
-_cescape_byte_to_str[34] = r'\"' # necessary escape
-_cescape_byte_to_str[92] = r'\\' # necessary escape
+for byte, string in _cescape_chr_to_symbol_map.items():
+ _cescape_byte_to_str[byte] = string
+del byte, string
def CEscape(text, as_utf8):
- """Escape a bytes string for use in an ascii protocol buffer.
-
- text.encode('string_escape') does not seem to satisfy our needs as it
- encodes unprintable characters using two-digit hex escapes whereas our
- C++ unescaping function allows hex escapes to be any length. So,
- "\0011".encode('string_escape') ends up being "\\x011", which will be
- decoded in C++ as a single-character string with char code 0x11.
+ # type: (...) -> str
+ """Escape a bytes string for use in an text protocol buffer.
Args:
- text: A byte string to be escaped
- as_utf8: Specifies if result should be returned in UTF-8 encoding
+ text: A byte string to be escaped.
+ as_utf8: Specifies if result may contain non-ASCII characters.
+ In Python 3 this allows unescaped non-ASCII Unicode characters.
+ In Python 2 the return value will be valid UTF-8 rather than only ASCII.
Returns:
- Escaped string
+ Escaped string (str).
"""
- # PY3 hack: make Ord work for str and bytes:
- # //platforms/networking/data uses unicode here, hence basestring.
- Ord = ord if isinstance(text, six.string_types) else lambda x: x
+ # Python's text.encode() 'string_escape' or 'unicode_escape' codecs do not
+ # satisfy our needs; they encodes unprintable characters using two-digit hex
+ # escapes whereas our C++ unescaping function allows hex escapes to be any
+ # length. So, "\0011".encode('string_escape') ends up being "\\x011", which
+ # will be decoded in C++ as a single-character string with char code 0x11.
+ if six.PY3:
+ text_is_unicode = isinstance(text, str)
+ if as_utf8 and text_is_unicode:
+ # We're already unicode, no processing beyond control char escapes.
+ return text.translate(_cescape_chr_to_symbol_map)
+ ord_ = ord if text_is_unicode else lambda x: x # bytes iterate as ints.
+ else:
+ ord_ = ord # PY2
if as_utf8:
- return ''.join(_cescape_utf8_to_str[Ord(c)] for c in text)
- return ''.join(_cescape_byte_to_str[Ord(c)] for c in text)
+ return ''.join(_cescape_unicode_to_str[ord_(c)] for c in text)
+ return ''.join(_cescape_byte_to_str[ord_(c)] for c in text)
_CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])')
-_cescape_highbit_to_str = ([chr(i) for i in range(0, 127)] +
- [r'\%03o' % i for i in range(127, 256)])
def CUnescape(text):
- """Unescape a text string with C-style escape sequences to UTF-8 bytes."""
+ # type: (str) -> bytes
+ """Unescape a text string with C-style escape sequences to UTF-8 bytes.
+
+ Args:
+ text: The data to parse in a str.
+ Returns:
+ A byte string.
+ """
def ReplaceHex(m):
# Only replace the match if the number of leading back slashes is odd. i.e.
@@ -98,10 +109,9 @@ def CUnescape(text):
# allow single-digit hex escapes (like '\xf').
result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
- if str is bytes: # PY2
+ if six.PY2:
return result.decode('string_escape')
- result = ''.join(_cescape_highbit_to_str[ord(c)] for c in result)
- return (result.encode('ascii') # Make it bytes to allow decode.
+ return (result.encode('utf-8') # PY3: Make it bytes to allow decode.
.decode('unicode_escape')
# Make it bytes again to return the proper type.
.encode('raw_unicode_escape'))
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
index 2cbd21bc..998cd681 100755
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -55,15 +55,15 @@ from google.protobuf.internal import type_checkers
from google.protobuf import descriptor
from google.protobuf import text_encoding
-__all__ = ['MessageToString', 'PrintMessage', 'PrintField', 'PrintFieldValue',
- 'Merge']
+__all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField',
+ 'PrintFieldValue', 'Merge', 'MessageToBytes']
_INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
type_checkers.Int32ValueChecker(),
type_checkers.Uint64ValueChecker(),
type_checkers.Int64ValueChecker())
-_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
-_FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
+_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?$', re.IGNORECASE)
+_FLOAT_NAN = re.compile('nanf?$', re.IGNORECASE)
_FLOAT_TYPES = frozenset([descriptor.FieldDescriptor.CPPTYPE_FLOAT,
descriptor.FieldDescriptor.CPPTYPE_DOUBLE])
_QUOTES = frozenset(("'", '"'))
@@ -121,6 +121,7 @@ class TextWriter(object):
def MessageToString(message,
as_utf8=False,
as_one_line=False,
+ use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
@@ -128,6 +129,7 @@ def MessageToString(message,
descriptor_pool=None,
indent=0,
message_formatter=None):
+ # type: (...) -> str
"""Convert protobuf message to text format.
Floating point values can be formatted compactly with 15 digits of
@@ -137,8 +139,11 @@ def MessageToString(message,
Args:
message: The protocol buffers message.
- as_utf8: Produce text output in UTF8 format.
+ as_utf8: Return unescaped Unicode for non-ASCII characters.
+ In Python 3 actual Unicode characters may appear as is in strings.
+ In Python 2 the return value will be valid UTF-8 rather than only ASCII.
as_one_line: Don't introduce newlines between fields.
+ use_short_repeated_primitives: Use short repeated format for primitives.
pointy_brackets: If True, use angle brackets instead of curly braces for
nesting.
use_index_order: If True, fields of a proto message will be printed using
@@ -150,7 +155,7 @@ def MessageToString(message,
(per the "Format Specification Mini-Language"); otherwise, str() is used.
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.
+ indent: The initial 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.
@@ -159,7 +164,8 @@ def MessageToString(message,
A string of the text formatted protocol buffer message.
"""
out = TextWriter(as_utf8)
- printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
+ printer = _Printer(out, indent, as_utf8, as_one_line,
+ use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, use_field_number,
descriptor_pool, message_formatter)
printer.PrintMessage(message)
@@ -170,6 +176,16 @@ def MessageToString(message,
return result
+def MessageToBytes(message, **kwargs):
+ # type: (...) -> bytes
+ """Convert protobuf message to encoded text format. See MessageToString."""
+ text = MessageToString(message, **kwargs)
+ if isinstance(text, bytes):
+ return text
+ codec = 'utf-8' if kwargs.get('as_utf8') else 'ascii'
+ return text.encode(codec)
+
+
def _IsMapEntry(field):
return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
field.message_type.has_options and
@@ -181,13 +197,15 @@ def PrintMessage(message,
indent=0,
as_utf8=False,
as_one_line=False,
+ use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
use_field_number=False,
descriptor_pool=None,
message_formatter=None):
- printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
+ printer = _Printer(out, indent, as_utf8, as_one_line,
+ use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, use_field_number,
descriptor_pool, message_formatter)
printer.PrintMessage(message)
@@ -199,12 +217,14 @@ def PrintField(field,
indent=0,
as_utf8=False,
as_one_line=False,
+ use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
message_formatter=None):
"""Print a single field name/value pair."""
- printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets,
+ printer = _Printer(out, indent, as_utf8, as_one_line,
+ use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, message_formatter)
printer.PrintField(field, value)
@@ -215,12 +235,14 @@ def PrintFieldValue(field,
indent=0,
as_utf8=False,
as_one_line=False,
+ use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
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,
+ printer = _Printer(out, indent, as_utf8, as_one_line,
+ use_short_repeated_primitives, pointy_brackets,
use_index_order, float_format, message_formatter)
printer.PrintFieldValue(field, value)
@@ -258,6 +280,7 @@ class _Printer(object):
indent=0,
as_utf8=False,
as_one_line=False,
+ use_short_repeated_primitives=False,
pointy_brackets=False,
use_index_order=False,
float_format=None,
@@ -273,9 +296,12 @@ class _Printer(object):
Args:
out: To record the text format result.
- indent: The indent level for pretty print.
- as_utf8: Produce text output in UTF8 format.
+ indent: The initial indent level for pretty print.
+ as_utf8: Return unescaped Unicode for non-ASCII characters.
+ In Python 3 actual Unicode characters may appear as is in strings.
+ In Python 2 the return value will be valid UTF-8 rather than ASCII.
as_one_line: Don't introduce newlines between fields.
+ use_short_repeated_primitives: Use short repeated format for primitives.
pointy_brackets: If True, use angle brackets instead of curly braces for
nesting.
use_index_order: If True, print fields of a proto message using the order
@@ -294,6 +320,7 @@ class _Printer(object):
self.indent = indent
self.as_utf8 = as_utf8
self.as_one_line = as_one_line
+ self.use_short_repeated_primitives = use_short_repeated_primitives
self.pointy_brackets = pointy_brackets
self.use_index_order = use_index_order
self.float_format = float_format
@@ -303,11 +330,13 @@ class _Printer(object):
def _TryPrintAsAnyMessage(self, message):
"""Serializes if message is a google.protobuf.Any field."""
+ if '/' not in message.type_url:
+ return False
packed_message = _BuildMessageFromTypeName(message.TypeName(),
self.descriptor_pool)
if packed_message:
packed_message.MergeFromString(message.value)
- self.out.write('%s[%s]' % (self.indent * ' ', message.type_url))
+ self.out.write('%s[%s] ' % (self.indent * ' ', message.type_url))
self._PrintMessageFieldValue(packed_message)
self.out.write(' ' if self.as_one_line else '\n')
return True
@@ -351,13 +380,18 @@ class _Printer(object):
entry_submsg = value.GetEntryClass()(key=key, value=value[key])
self.PrintField(field, entry_submsg)
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
- for element in value:
- self.PrintField(field, element)
+ if (self.use_short_repeated_primitives
+ and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE
+ and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_STRING):
+ self._PrintShortRepeatedPrimitivesValue(field, value)
+ else:
+ for element in value:
+ self.PrintField(field, element)
else:
self.PrintField(field, value)
- def PrintField(self, field, value):
- """Print a single field name/value pair."""
+ def _PrintFieldName(self, field):
+ """Print field name."""
out = self.out
out.write(' ' * self.indent)
if self.use_field_number:
@@ -381,13 +415,25 @@ class _Printer(object):
if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
# The colon is optional in this case, but our cross-language golden files
# don't include it.
- out.write(': ')
+ out.write(':')
+ def PrintField(self, field, value):
+ """Print a single field name/value pair."""
+ self._PrintFieldName(field)
+ self.out.write(' ')
self.PrintFieldValue(field, value)
- if self.as_one_line:
- out.write(' ')
- else:
- out.write('\n')
+ self.out.write(' ' if self.as_one_line else '\n')
+
+ def _PrintShortRepeatedPrimitivesValue(self, field, value):
+ # Note: this is called only when value has at least one element.
+ self._PrintFieldName(field)
+ self.out.write('[')
+ for i in xrange(len(value) - 1):
+ self.PrintFieldValue(field, value[i])
+ self.out.write(', ')
+ self.PrintFieldValue(field, value[-1])
+ self.out.write(']')
+ self.out.write(' ' if self.as_one_line else '\n')
def _PrintMessageFieldValue(self, value):
if self.pointy_brackets:
@@ -398,11 +444,11 @@ class _Printer(object):
closeb = '}'
if self.as_one_line:
- self.out.write(' %s ' % openb)
+ self.out.write('%s ' % openb)
self.PrintMessage(value)
self.out.write(closeb)
else:
- self.out.write(' %s\n' % openb)
+ self.out.write('%s\n' % openb)
self.indent += 2
self.PrintMessage(value)
self.indent -= 2
@@ -428,12 +474,12 @@ class _Printer(object):
out.write(str(value))
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
out.write('\"')
- if isinstance(value, six.text_type):
+ if isinstance(value, six.text_type) and (six.PY2 or not self.as_utf8):
out_value = value.encode('utf-8')
else:
out_value = value
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
- # We need to escape non-UTF8 chars in TYPE_BYTES field.
+ # We always need to escape all binary data in TYPE_BYTES fields.
out_as_utf8 = False
else:
out_as_utf8 = self.as_utf8
@@ -487,12 +533,7 @@ def Parse(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 ParseLines(text.split('\n'),
+ return ParseLines(text.split(b'\n' if isinstance(text, bytes) else u'\n'),
message,
allow_unknown_extension,
allow_field_number,
@@ -523,13 +564,8 @@ 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'),
+ text.split(b'\n' if isinstance(text, bytes) else u'\n'),
message,
allow_unknown_extension,
allow_field_number,
@@ -570,6 +606,9 @@ def MergeLines(lines,
descriptor_pool=None):
"""Parses a text representation of a protocol message into a message.
+ Like ParseLines(), but allows repeated values for a non-repeated field, and
+ uses the last one.
+
Args:
lines: An iterable of lines of a message's text representation.
message: A protocol buffer message to merge into.
@@ -601,22 +640,12 @@ class _Parser(object):
self.allow_field_number = allow_field_number
self.descriptor_pool = descriptor_pool
- def ParseFromString(self, text, message):
- """Parses a text representation of a protocol message into a message."""
- if not isinstance(text, str):
- text = text.decode('utf-8')
- return self.ParseLines(text.split('\n'), message)
-
def ParseLines(self, lines, message):
"""Parses a text representation of a protocol message into a message."""
self._allow_multiple_scalars = False
self._ParseOrMerge(lines, message)
return message
- def MergeFromString(self, text, message):
- """Merges a text representation of a protocol message into a message."""
- return self._MergeLines(text.split('\n'), message)
-
def MergeLines(self, lines, message):
"""Merges a text representation of a protocol message into a message."""
self._allow_multiple_scalars = True
@@ -633,7 +662,14 @@ class _Parser(object):
Raises:
ParseError: On text parsing problems.
"""
- tokenizer = Tokenizer(lines)
+ # Tokenize expects native str lines.
+ if six.PY2:
+ str_lines = (line if isinstance(line, str) else line.encode('utf-8')
+ for line in lines)
+ else:
+ str_lines = (line if isinstance(line, str) else line.decode('utf-8')
+ for line in lines)
+ tokenizer = Tokenizer(str_lines)
while not tokenizer.AtEnd():
self._MergeField(tokenizer, message)
@@ -1019,7 +1055,9 @@ class Tokenizer(object):
r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
] + [ # quoted str for each quote mark
- r'{qt}([^{qt}\n\\]|\\.)*({qt}|\\?$)'.format(qt=mark) for mark in _QUOTES
+ # Avoid backtracking! https://stackoverflow.com/a/844267
+ r'{qt}[^{qt}\n\\]*((\\.)+[^{qt}\n\\]*)*({qt}|\\?$)'.format(qt=mark)
+ for mark in _QUOTES
]))
_IDENTIFIER = re.compile(r'[^\d\W]\w*')
@@ -1316,7 +1354,8 @@ class Tokenizer(object):
def ParseError(self, message):
"""Creates and *returns* a ParseError for the current token."""
- return ParseError(message, self._line + 1, self._column + 1)
+ return ParseError('\'' + self._current_line + '\': ' + message,
+ self._line + 1, self._column + 1)
def _StringParseError(self, e):
return self.ParseError('Couldn\'t parse string: ' + str(e))
@@ -1490,6 +1529,12 @@ def _ParseAbstractInteger(text, is_long=False):
ValueError: Thrown Iff the text is not a valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
+ orig_text = text
+ c_octal_match = re.match(r'(-?)0(\d+)$', text)
+ if c_octal_match:
+ # Python 3 no longer supports 0755 octal syntax without the 'o', so
+ # we always use the '0o' prefix for multi-digit numbers starting with 0.
+ text = c_octal_match.group(1) + '0o' + c_octal_match.group(2)
try:
# We force 32-bit values to int and 64-bit values to long to make
# alternate implementations where the distinction is more significant
@@ -1499,7 +1544,7 @@ def _ParseAbstractInteger(text, is_long=False):
else:
return int(text, 0)
except ValueError:
- raise ValueError('Couldn\'t parse integer: %s' % text)
+ raise ValueError('Couldn\'t parse integer: %s' % orig_text)
def ParseFloat(text):
diff --git a/python/release.sh b/python/release.sh
index a71cc7f5..b1ee937d 100755
--- a/python/release.sh
+++ b/python/release.sh
@@ -108,7 +108,7 @@ if [ $TESTING_ONLY -eq 0 ]; then
# 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
+ # https://github.com/protocolbuffers/protobuf/issues/3042
python setup.py clean build bdist_egg bdist_wheel upload
else
# Set the version number back (i.e., remove dev suffix).
diff --git a/python/release/wheel/protobuf_optimized_pip.sh b/python/release/wheel/protobuf_optimized_pip.sh
index 98306f4c..07c2a093 100755
--- a/python/release/wheel/protobuf_optimized_pip.sh
+++ b/python/release/wheel/protobuf_optimized_pip.sh
@@ -39,7 +39,7 @@ PYTHON_VERSIONS=('cp27-cp27mu' 'cp33-cp33m' 'cp34-cp34m' 'cp35-cp35m' 'cp36-cp36
mkdir -p ${DIR}
cd ${DIR}
-curl -SsL -O https://github.com/google/protobuf/archive/v${PROTOBUF_VERSION}.tar.gz
+curl -SsL -O https://github.com/protocolbuffers/protobuf/archive/v${PROTOBUF_VERSION}.tar.gz
tar xzf v${PROTOBUF_VERSION}.tar.gz
cd $DIR/protobuf-${PROTOBUF_VERSION}
diff --git a/python/setup.py b/python/setup.py
index a9df075e..9a02a246 100755
--- a/python/setup.py
+++ b/python/setup.py
@@ -44,6 +44,7 @@ def GetVersion():
with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file:
exec(version_file.read(), globals())
+ global __version__
return __version__
@@ -148,10 +149,9 @@ class build_py(_build_py):
class test_conformance(_build_py):
target = 'test_python'
def run(self):
- if sys.version_info >= (2, 7):
- # Python 2.6 dodges these extra failures.
- os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
- "--failure_list failure_list_python-post26.txt")
+ # Python 2.6 dodges these extra failures.
+ os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
+ "--failure_list failure_list_python-post26.txt")
cmd = 'cd ../conformance && make %s' % (test_conformance.target)
status = subprocess.check_call(cmd, shell=True)
@@ -185,6 +185,11 @@ if __name__ == '__main__':
extra_compile_args.append('-Wno-write-strings')
extra_compile_args.append('-Wno-invalid-offsetof')
extra_compile_args.append('-Wno-sign-compare')
+ extra_compile_args.append('-Wno-unused-variable')
+ extra_compile_args.append('-std=c++11')
+
+ if sys.platform == 'darwin':
+ extra_compile_args.append("-Wno-shorten-64-to-32");
# https://github.com/Theano/Theano/issues/4926
if sys.platform == 'win32':
@@ -201,12 +206,6 @@ 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:
- extra_compile_args.append('-std=c++11')
- elif os.getenv('KOKORO_BUILD_NUMBER') or os.getenv('KOKORO_BUILD_ID'):
- 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)
@@ -240,7 +239,7 @@ if __name__ == '__main__':
name='protobuf',
version=GetVersion(),
description='Protocol Buffers',
- download_url='https://github.com/google/protobuf/releases',
+ download_url='https://github.com/protocolbuffers/protobuf/releases',
long_description="Protocol Buffers are Google's data interchange format",
url='https://developers.google.com/protocol-buffers/',
maintainer='protobuf@googlegroups.com',
diff --git a/python/stubout.py b/python/stubout.py
index aee4f2da..ba391045 100755
--- a/python/stubout.py
+++ b/python/stubout.py
@@ -17,6 +17,9 @@
# This file is used for testing. The original is at:
# http://code.google.com/p/pymox/
+import inspect
+
+
class StubOutForTesting:
"""Sample Usage:
You want os.path.exists() to always return true during testing.
diff --git a/ruby/ext/google/protobuf_c/defs.c b/ruby/ext/google/protobuf_c/defs.c
index d9d2ebac..9fe04503 100644
--- a/ruby/ext/google/protobuf_c/defs.c
+++ b/ruby/ext/google/protobuf_c/defs.c
@@ -812,7 +812,7 @@ VALUE FieldDescriptor_submsg_name_set(VALUE _self, VALUE value) {
upb_fielddef* mut_def = check_field_notfrozen(self->fielddef);
const char* str = get_str(value);
if (!upb_fielddef_hassubdef(self->fielddef)) {
- rb_raise(rb_eTypeError, "FieldDescriptor does not have subdef.");
+ rb_raise(cTypeError, "FieldDescriptor does not have subdef.");
}
CHECK_UPB(upb_fielddef_setsubdefname(mut_def, str, &status),
"Error setting submessage name");
@@ -854,7 +854,7 @@ VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb) {
MessageHeader* msg;
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
- rb_raise(rb_eTypeError, "get method called on wrong message type");
+ rb_raise(cTypeError, "get method called on wrong message type");
}
return layout_get(msg->descriptor->layout, Message_data(msg), self->fielddef);
}
@@ -872,7 +872,7 @@ VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value) {
MessageHeader* msg;
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
if (msg->descriptor->msgdef != upb_fielddef_containingtype(self->fielddef)) {
- rb_raise(rb_eTypeError, "set method called on wrong message type");
+ rb_raise(cTypeError, "set method called on wrong message type");
}
layout_set(msg->descriptor->layout, Message_data(msg), self->fielddef, value);
return Qnil;
@@ -1713,7 +1713,7 @@ static void validate_msgdef(const upb_msgdef* msgdef) {
upb_msg_field_next(&it)) {
const upb_fielddef* field = upb_msg_iter_field(&it);
if (upb_fielddef_label(field) == UPB_LABEL_REQUIRED) {
- rb_raise(rb_eTypeError, "Required fields are unsupported in proto3.");
+ rb_raise(cTypeError, "Required fields are unsupported in proto3.");
}
}
}
@@ -1723,7 +1723,7 @@ static void validate_enumdef(const upb_enumdef* enumdef) {
// value.)
const char* lookup = upb_enumdef_iton(enumdef, 0);
if (lookup == NULL) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Enum definition does not contain a value for '0'.");
}
}
diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c
index 9fa4bfd9..d5842051 100644
--- a/ruby/ext/google/protobuf_c/encode_decode.c
+++ b/ruby/ext/google/protobuf_c/encode_decode.c
@@ -963,13 +963,15 @@ static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
if (ary == Qnil) return;
+ size = NUM2INT(RepeatedField_length(ary));
+ if (size == 0 && !emit_defaults) return;
+
upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
if (upb_fielddef_isprimitive(f)) {
sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
}
- size = NUM2INT(RepeatedField_length(ary));
for (int i = 0; i < size; i++) {
void* memory = RepeatedField_index_native(ary, i);
switch (type) {
diff --git a/ruby/ext/google/protobuf_c/message.c b/ruby/ext/google/protobuf_c/message.c
index 63a61baf..721c1112 100644
--- a/ruby/ext/google/protobuf_c/message.c
+++ b/ruby/ext/google/protobuf_c/message.c
@@ -256,6 +256,10 @@ int Message_initialize_kwarg(VALUE key, VALUE val, VALUE _self) {
"Unknown field name '%s' in initialization map entry.", name);
}
+ if (TYPE(val) == T_NIL) {
+ return 0;
+ }
+
if (is_map_field(f)) {
VALUE map;
@@ -631,7 +635,7 @@ VALUE build_module_from_enumdesc(EnumDescriptor* enumdesc) {
const char* name = upb_enum_iter_name(&it);
int32_t value = upb_enum_iter_number(&it);
if (name[0] < 'A' || name[0] > 'Z') {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Enum value '%s' does not start with an uppercase letter "
"as is required for Ruby constants.",
name);
diff --git a/ruby/ext/google/protobuf_c/protobuf.c b/ruby/ext/google/protobuf_c/protobuf.c
index db696426..fe6bb406 100644
--- a/ruby/ext/google/protobuf_c/protobuf.c
+++ b/ruby/ext/google/protobuf_c/protobuf.c
@@ -41,6 +41,7 @@ VALUE upb_def_to_ruby_obj_map;
VALUE cError;
VALUE cParseError;
+VALUE cTypeError;
void add_def_obj(const void* def, VALUE value) {
rb_hash_aset(upb_def_to_ruby_obj_map, ULL2NUM((intptr_t)def), value);
@@ -102,6 +103,7 @@ void Init_protobuf_c() {
cError = rb_const_get(protobuf, rb_intern("Error"));
cParseError = rb_const_get(protobuf, rb_intern("ParseError"));
+ cTypeError = rb_const_get(protobuf, rb_intern("TypeError"));
rb_define_singleton_method(protobuf, "discard_unknown",
Google_Protobuf_discard_unknown, 1);
diff --git a/ruby/ext/google/protobuf_c/protobuf.h b/ruby/ext/google/protobuf_c/protobuf.h
index 5266aa8d..3e5c0520 100644
--- a/ruby/ext/google/protobuf_c/protobuf.h
+++ b/ruby/ext/google/protobuf_c/protobuf.h
@@ -161,6 +161,7 @@ extern VALUE cBuilder;
extern VALUE cError;
extern VALUE cParseError;
+extern VALUE cTypeError;
// We forward-declare all of the Ruby method implementations here because we
// sometimes call the methods directly across .c files, rather than going
diff --git a/ruby/ext/google/protobuf_c/storage.c b/ruby/ext/google/protobuf_c/storage.c
index 5d842b74..163b2f81 100644
--- a/ruby/ext/google/protobuf_c/storage.c
+++ b/ruby/ext/google/protobuf_c/storage.c
@@ -96,7 +96,7 @@ static bool is_ruby_num(VALUE value) {
void native_slot_check_int_range_precision(upb_fieldtype_t type, VALUE val) {
if (!is_ruby_num(val)) {
- rb_raise(rb_eTypeError, "Expected number type for integral field.");
+ rb_raise(cTypeError, "Expected number type for integral field.");
}
// NUM2{INT,UINT,LL,ULL} macros do the appropriate range checks on upper
@@ -153,13 +153,13 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
switch (type) {
case UPB_TYPE_FLOAT:
if (!is_ruby_num(value)) {
- rb_raise(rb_eTypeError, "Expected number type for float field.");
+ rb_raise(cTypeError, "Expected number type for float field.");
}
DEREF(memory, float) = NUM2DBL(value);
break;
case UPB_TYPE_DOUBLE:
if (!is_ruby_num(value)) {
- rb_raise(rb_eTypeError, "Expected number type for double field.");
+ rb_raise(cTypeError, "Expected number type for double field.");
}
DEREF(memory, double) = NUM2DBL(value);
break;
@@ -170,7 +170,7 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
} else if (value == Qfalse) {
val = 0;
} else {
- rb_raise(rb_eTypeError, "Invalid argument for boolean field.");
+ rb_raise(cTypeError, "Invalid argument for boolean field.");
}
DEREF(memory, int8_t) = val;
break;
@@ -179,7 +179,7 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
if (CLASS_OF(value) == rb_cSymbol) {
value = rb_funcall(value, rb_intern("to_s"), 0);
} else if (CLASS_OF(value) != rb_cString) {
- rb_raise(rb_eTypeError, "Invalid argument for string field.");
+ rb_raise(cTypeError, "Invalid argument for string field.");
}
DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
@@ -187,7 +187,7 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
case UPB_TYPE_BYTES: {
if (CLASS_OF(value) != rb_cString) {
- rb_raise(rb_eTypeError, "Invalid argument for string field.");
+ rb_raise(cTypeError, "Invalid argument for string field.");
}
DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
@@ -197,7 +197,7 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
if (CLASS_OF(value) == CLASS_OF(Qnil)) {
value = Qnil;
} else if (CLASS_OF(value) != type_class) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Invalid type %s to assign to submessage field.",
rb_class2name(CLASS_OF(value)));
}
@@ -209,7 +209,7 @@ void native_slot_set_value_and_case(upb_fieldtype_t type, VALUE type_class,
if (TYPE(value) == T_STRING) {
value = rb_funcall(value, rb_intern("to_sym"), 0);
} else if (!is_ruby_num(value) && TYPE(value) != T_SYMBOL) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Expected number or symbol type for enum field.");
}
if (TYPE(value) == T_SYMBOL) {
@@ -598,18 +598,18 @@ static void check_repeated_field_type(VALUE val, const upb_fielddef* field) {
if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
RTYPEDDATA_TYPE(val) != &RepeatedField_type) {
- rb_raise(rb_eTypeError, "Expected repeated field array");
+ rb_raise(cTypeError, "Expected repeated field array");
}
self = ruby_to_RepeatedField(val);
if (self->field_type != upb_fielddef_type(field)) {
- rb_raise(rb_eTypeError, "Repeated field array has wrong element type");
+ rb_raise(cTypeError, "Repeated field array has wrong element type");
}
- if (self->field_type == UPB_TYPE_MESSAGE) {
+ if (self->field_type == UPB_TYPE_MESSAGE) {
if (self->field_type_class !=
Descriptor_msgclass(get_def_obj(upb_fielddef_subdef(field)))) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Repeated field array has wrong message class");
}
}
@@ -618,7 +618,7 @@ static void check_repeated_field_type(VALUE val, const upb_fielddef* field) {
if (self->field_type == UPB_TYPE_ENUM) {
if (self->field_type_class !=
EnumDescriptor_enummodule(get_def_obj(upb_fielddef_subdef(field)))) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Repeated field array has wrong enum class");
}
}
@@ -631,21 +631,21 @@ static void check_map_field_type(VALUE val, const upb_fielddef* field) {
if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
RTYPEDDATA_TYPE(val) != &Map_type) {
- rb_raise(rb_eTypeError, "Expected Map instance");
+ rb_raise(cTypeError, "Expected Map instance");
}
self = ruby_to_Map(val);
if (self->key_type != upb_fielddef_type(key_field)) {
- rb_raise(rb_eTypeError, "Map key type does not match field's key type");
+ rb_raise(cTypeError, "Map key type does not match field's key type");
}
if (self->value_type != upb_fielddef_type(value_field)) {
- rb_raise(rb_eTypeError, "Map value type does not match field's value type");
+ rb_raise(cTypeError, "Map value type does not match field's value type");
}
if (upb_fielddef_type(value_field) == UPB_TYPE_MESSAGE ||
upb_fielddef_type(value_field) == UPB_TYPE_ENUM) {
if (self->value_type_class !=
get_def_obj(upb_fielddef_subdef(value_field))) {
- rb_raise(rb_eTypeError,
+ rb_raise(cTypeError,
"Map value type has wrong message/enum class");
}
}
diff --git a/ruby/ext/google/protobuf_c/wrap_memcpy.c b/ruby/ext/google/protobuf_c/wrap_memcpy.c
index 394a52f9..18c03678 100644
--- a/ruby/ext/google/protobuf_c/wrap_memcpy.c
+++ b/ruby/ext/google/protobuf_c/wrap_memcpy.c
@@ -33,7 +33,7 @@
// 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).
+// the gem we distribute (https://github.com/protocolbuffers/protobuf/issues/2783).
//
// This wrapper is enabled by passing the linker flags -Wl,-wrap,memcpy in
// extconf.rb.
diff --git a/ruby/lib/google/protobuf.rb b/ruby/lib/google/protobuf.rb
index 4a805e88..e20a584e 100644
--- a/ruby/lib/google/protobuf.rb
+++ b/ruby/lib/google/protobuf.rb
@@ -37,6 +37,7 @@ module Google
module Protobuf
class Error < StandardError; end
class ParseError < Error; end
+ class TypeError < ::TypeError; end
end
end
diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb
index 921ddbc0..2ee65bc2 100644
--- a/ruby/lib/google/protobuf/well_known_types.rb
+++ b/ruby/lib/google/protobuf/well_known_types.rb
@@ -39,6 +39,12 @@ module Google
module Protobuf
Any.class_eval do
+ def self.pack(msg, type_url_prefix='type.googleapis.com/')
+ any = self.new
+ any.pack(msg, type_url_prefix)
+ any
+ end
+
def pack(msg, type_url_prefix='type.googleapis.com/')
if type_url_prefix.empty? or type_url_prefix[-1] != '/' then
self.type_url = "#{type_url_prefix}/#{msg.class.descriptor.name}"
@@ -149,6 +155,8 @@ module Google
Struct.class_eval do
def [](key)
self.fields[key].to_ruby
+ rescue NoMethodError
+ nil
end
def []=(key, value)
@@ -170,6 +178,10 @@ module Google
hash.each { |key, val| ret[key] = val }
ret
end
+
+ def has_key?(key)
+ self.fields.has_key?(key)
+ end
end
ListValue.class_eval do
diff --git a/ruby/pom.xml b/ruby/pom.xml
index adf6ff20..acd2453b 100644
--- a/ruby/pom.xml
+++ b/ruby/pom.xml
@@ -27,9 +27,9 @@
</license>
</licenses>
<scm>
- <url>https://github.com/google/protobuf</url>
+ <url>https://github.com/protocolbuffers/protobuf</url>
<connection>
- scm:git:https://github.com/google/protobuf.git
+ scm:git:https://github.com/protocolbuffers/protobuf.git
</connection>
</scm>
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 07558fbc..c3a0d81c 100644
--- a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
+++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
@@ -86,6 +86,8 @@ public class RubyMessage extends RubyObject {
throw runtime.newTypeError("Expected string or symbols as hash keys in initialization map.");
final Descriptors.FieldDescriptor fieldDescriptor = findField(context, key);
+ if (value.isNil()) return;
+
if (Utils.isMapEntry(fieldDescriptor)) {
if (!(value instanceof RubyHash))
throw runtime.newArgumentError("Expected Hash object as initializer value for map field '" + key.asJavaString() + "'.");
diff --git a/ruby/tests/basic.rb b/ruby/tests/basic.rb
index d151022e..f174402b 100644
--- a/ruby/tests/basic.rb
+++ b/ruby/tests/basic.rb
@@ -212,6 +212,15 @@ module BasicTest
assert_equal ['foo', 'bar'], m.repeated_string
end
+ def test_ctor_nil_args
+ m = TestMessage.new(:optional_enum => nil, :optional_int32 => nil, :optional_string => nil, :optional_msg => nil)
+
+ assert_equal :Default, m.optional_enum
+ assert_equal 0, m.optional_int32
+ assert_equal "", m.optional_string
+ assert_nil m.optional_msg
+ end
+
def test_embeddedmsg_hash_init
m = TestEmbeddedMessageParent.new(:child_msg => {sub_child: {optional_int32: 1}},
:number => 2,
@@ -283,31 +292,36 @@ module BasicTest
def test_type_errors
m = TestMessage.new
- assert_raise TypeError do
+ e = assert_raise Google::Protobuf::TypeError do
m.optional_int32 = "hello"
end
- assert_raise TypeError do
+
+ # Google::Protobuf::TypeError should inherit from TypeError for backwards compatibility
+ # TODO: This can be removed when we can safely migrate to Google::Protobuf::TypeError
+ assert_true e.is_a?(::TypeError)
+
+ assert_raise Google::Protobuf::TypeError do
m.optional_string = 42
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.optional_string = nil
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.optional_bool = 42
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.optional_msg = TestMessage.new # expects TestMessage2
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.repeated_int32 = [] # needs RepeatedField
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.repeated_int32.push "hello"
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.repeated_msg.push TestMessage.new
end
end
@@ -375,7 +389,7 @@ module BasicTest
assert l.pop == 9
assert l == [5, 2, 3, 4, 7, 8]
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m = TestMessage.new
l.push m
end
@@ -425,10 +439,10 @@ module BasicTest
l = Google::Protobuf::RepeatedField.new(:message, TestMessage)
l.push TestMessage.new
assert l.count == 1
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
l.push TestMessage2.new
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
l.push 42
end
@@ -577,7 +591,7 @@ module BasicTest
assert_raise RangeError do
m[0x8000_0000] = 1
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m["asdf"] = 1
end
@@ -586,7 +600,7 @@ module BasicTest
assert_raise RangeError do
m[0x1_0000_0000_0000_0000] = 1
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m["asdf"] = 1
end
@@ -611,10 +625,10 @@ module BasicTest
m = Google::Protobuf::Map.new(:bool, :int32)
m[true] = 1
m[false] = 2
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m[1] = 1
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m["asdf"] = 1
end
@@ -641,7 +655,7 @@ module BasicTest
def test_map_msg_enum_valuetypes
m = Google::Protobuf::Map.new(:string, :message, TestMessage)
m["asdf"] = TestMessage.new
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m["jkl;"] = TestMessage2.new
end
@@ -708,17 +722,17 @@ module BasicTest
m.map_string_msg.delete("c")
assert m.map_string_msg == { "a" => TestMessage2.new(:foo => 1) }
- assert_raise TypeError do
+ assert_raise Google::Protobuf::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
+ assert_raise Google::Protobuf::TypeError do
m.map_string_int32 = Google::Protobuf::Map.new(:string, :int64)
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
m.map_string_int32 = {}
end
@@ -1017,7 +1031,7 @@ module BasicTest
def test_def_errors
s = Google::Protobuf::DescriptorPool.new
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
s.build do
# enum with no default (integer value 0)
add_enum "MyEnum" do
@@ -1025,7 +1039,7 @@ module BasicTest
end
end
end
- assert_raise TypeError do
+ assert_raise Google::Protobuf::TypeError do
s.build do
# message with required field (unsupported in proto3)
add_message "MyMessage" do
@@ -1261,6 +1275,10 @@ module BasicTest
Foo.encode_json(Foo.new(bar: bar, baz: [baz1, baz2]))
end
+ def test_json_empty
+ assert TestMessage.encode_json(TestMessage.new) == '{}'
+ end
+
def test_json_emit_defaults
# TODO: Fix JSON in JRuby version.
return if RUBY_PLATFORM == "java"
diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb
index bd24c328..f35f7b13 100644
--- a/ruby/tests/well_known_types_test.rb
+++ b/ruby/tests/well_known_types_test.rb
@@ -60,6 +60,9 @@ class TestWellKnownTypes < Test::Unit::TestCase
assert_equal(Google::Protobuf::ListValue.from_a(sublist),
struct["sublist"])
+ assert_equal true, struct.has_key?("null")
+ assert_equal false, struct.has_key?("missing_key")
+
should_equal = {
"number" => 12345,
"boolean-true" => true,
@@ -82,6 +85,9 @@ class TestWellKnownTypes < Test::Unit::TestCase
# to_h returns a fully-flattened Ruby structure (Hash and Array).
assert_equal(should_equal, struct.to_h)
+ # Test that we can safely access a missing key
+ assert_equal(nil, struct["missing_key"])
+
# Test that we can assign Struct and ListValue directly.
struct["substruct"] = Google::Protobuf::Struct.from_hash(substruct)
struct["sublist"] = Google::Protobuf::ListValue.from_a(sublist)
@@ -120,11 +126,17 @@ class TestWellKnownTypes < Test::Unit::TestCase
end
def test_any
- any = Google::Protobuf::Any.new
ts = Google::Protobuf::Timestamp.new(seconds: 12345, nanos: 6789)
+
+ any = Google::Protobuf::Any.new
any.pack(ts)
assert any.is(Google::Protobuf::Timestamp)
assert_equal ts, any.unpack(Google::Protobuf::Timestamp)
+
+ any = Google::Protobuf::Any.pack(ts)
+
+ assert any.is(Google::Protobuf::Timestamp)
+ assert_equal ts, any.unpack(Google::Protobuf::Timestamp)
end
end
diff --git a/src/Makefile.am b/src/Makefile.am
index 4bb77452..1aabf972 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -112,6 +112,9 @@ nobase_include_HEADERS = \
google/protobuf/message_lite.h \
google/protobuf/metadata.h \
google/protobuf/metadata_lite.h \
+ google/protobuf/port.h \
+ google/protobuf/port_def.inc \
+ google/protobuf/port_undef.inc \
google/protobuf/reflection.h \
google/protobuf/reflection_ops.h \
google/protobuf/repeated_field.h \
@@ -311,6 +314,8 @@ libprotoc_la_SOURCES = \
google/protobuf/compiler/command_line_interface.cc \
google/protobuf/compiler/plugin.cc \
google/protobuf/compiler/plugin.pb.cc \
+ google/protobuf/compiler/scc.cc \
+ google/protobuf/compiler/scc.h \
google/protobuf/compiler/subprocess.cc \
google/protobuf/compiler/subprocess.h \
google/protobuf/compiler/zip_writer.cc \
@@ -367,10 +372,6 @@ libprotoc_la_SOURCES = \
google/protobuf/compiler/java/java_generator_factory.h \
google/protobuf/compiler/java/java_helpers.cc \
google/protobuf/compiler/java/java_helpers.h \
- google/protobuf/compiler/java/java_lazy_message_field.cc \
- google/protobuf/compiler/java/java_lazy_message_field.h \
- google/protobuf/compiler/java/java_lazy_message_field_lite.cc\
- google/protobuf/compiler/java/java_lazy_message_field_lite.h \
google/protobuf/compiler/java/java_map_field.cc \
google/protobuf/compiler/java/java_map_field.h \
google/protobuf/compiler/java/java_map_field_lite.cc \
@@ -503,6 +504,7 @@ protoc_inputs = \
google/protobuf/unittest_preserve_unknown_enum2.proto \
google/protobuf/unittest_preserve_unknown_enum.proto \
google/protobuf/unittest.proto \
+ google/protobuf/unittest_proto3.proto \
google/protobuf/unittest_proto3_arena.proto \
google/protobuf/unittest_proto3_arena_lite.proto \
google/protobuf/unittest_proto3_lite.proto \
@@ -518,6 +520,7 @@ protoc_inputs = \
google/protobuf/util/internal/testdata/struct.proto \
google/protobuf/util/internal/testdata/timestamp_duration.proto \
google/protobuf/util/internal/testdata/wrappers.proto \
+ google/protobuf/util/json_format.proto \
google/protobuf/util/json_format_proto3.proto \
google/protobuf/util/message_differencer_unittest.proto \
google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto
@@ -526,7 +529,6 @@ 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 \
@@ -624,6 +626,8 @@ protoc_outputs = \
google/protobuf/unittest_preserve_unknown_enum2.pb.h \
google/protobuf/unittest_preserve_unknown_enum.pb.cc \
google/protobuf/unittest_preserve_unknown_enum.pb.h \
+ google/protobuf/unittest_proto3.pb.cc \
+ google/protobuf/unittest_proto3.pb.h \
google/protobuf/unittest_proto3_arena.pb.cc \
google/protobuf/unittest_proto3_arena.pb.h \
google/protobuf/unittest_proto3_arena_lite.pb.cc \
@@ -654,6 +658,8 @@ protoc_outputs = \
google/protobuf/util/internal/testdata/timestamp_duration.pb.h \
google/protobuf/util/internal/testdata/wrappers.pb.cc \
google/protobuf/util/internal/testdata/wrappers.pb.h \
+ google/protobuf/util/json_format.pb.cc \
+ google/protobuf/util/json_format.pb.h \
google/protobuf/util/json_format_proto3.pb.cc \
google/protobuf/util/json_format_proto3.pb.h \
google/protobuf/util/message_differencer_unittest.pb.cc \
@@ -687,6 +693,7 @@ COMMON_TEST_SOURCES = \
google/protobuf/test_util.cc \
google/protobuf/test_util.h \
google/protobuf/test_util.inc \
+ google/protobuf/test_util2.h \
google/protobuf/testing/googletest.cc \
google/protobuf/testing/googletest.h \
google/protobuf/testing/file.cc \
@@ -740,6 +747,7 @@ protobuf_test_SOURCES = \
google/protobuf/proto3_arena_lite_unittest.cc \
google/protobuf/proto3_arena_unittest.cc \
google/protobuf/proto3_lite_unittest.cc \
+ google/protobuf/proto3_lite_unittest.inc \
google/protobuf/reflection_ops_unittest.cc \
google/protobuf/repeated_field_reflection_unittest.cc \
google/protobuf/repeated_field_unittest.cc \
@@ -876,7 +884,7 @@ no_warning_test.cc:
no_warning_test_LDADD = $(PTHREAD_LIBS) libprotobuf.la libprotoc.la
no_warning_test_CXXFLAGS = $(PTHREAD_CFLAGS) $(PTHREAD_DEF) $(ZLIB_DEF) \
- -Wall -Wextra -Werror -Wno-unused-parameter
+ -Wall -Wextra -Werror -Wno-unused-parameter -Og
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/README.md b/src/README.md
index 3cbeb3e6..d84176e3 100644
--- a/src/README.md
+++ b/src/README.md
@@ -1,7 +1,7 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf)
+[![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fcpp_distcheck%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/linux-bazel.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fubuntu%2Fbazel%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp%2Fcontinuous) [![Build status](https://storage.googleapis.com/protobuf-kokoro-results/status-badge/macos-cpp_distcheck.png)](https://fusion.corp.google.com/projectanalysis/current/KOKORO/prod:protobuf%2Fgithub%2Fmaster%2Fmacos%2Fcpp_distcheck%2Fcontinuous) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf)
Copyright 2008 Google Inc.
@@ -29,7 +29,7 @@ install them before proceeding.
To get the source, download one of the release .tar.gz or .zip packages in the
release page:
- https://github.com/google/protobuf/releases/latest
+ https://github.com/protocolbuffers/protobuf/releases/latest
For example: if you only need C++, download `protobuf-cpp-[VERSION].tar.gz`; if
you need C++ and Java, download `protobuf-java-[VERSION].tar.gz` (every package
@@ -40,7 +40,7 @@ You can also get the source by "git clone" our git repository. Make sure you
have also cloned the submodules and generated the configure script (skip this
if you are using a release .tar.gz or .zip package):
- $ git clone https://github.com/google/protobuf.git
+ $ git clone https://github.com/protocolbuffers/protobuf.git
$ cd protobuf
$ git submodule update --init --recursive
$ ./autogen.sh
@@ -184,7 +184,7 @@ C++ Installation - Windows
If you only need the protoc binary, you can download it from the release
page:
- https://github.com/google/protobuf/releases/latest
+ https://github.com/protocolbuffers/protobuf/releases/latest
In the downloads section, download the zip file protoc-$VERSION-win32.zip.
It contains the protoc binary as well as public proto files of protobuf
diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h
index a34e5f8e..db7d76a8 100644
--- a/src/google/protobuf/any.h
+++ b/src/google/protobuf/any.h
@@ -38,12 +38,14 @@
#include <google/protobuf/message.h>
#include <google/protobuf/arenastring.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
// Helper class used to implement google::protobuf::Any.
-class LIBPROTOBUF_EXPORT AnyMetadata {
+class PROTOBUF_EXPORT AnyMetadata {
typedef ArenaStringPtr UrlType;
typedef ArenaStringPtr ValueType;
public:
@@ -59,7 +61,7 @@ class LIBPROTOBUF_EXPORT AnyMetadata {
// For example, both PackFrom(message, "type.googleapis.com") and
// PackFrom(message, "type.googleapis.com/") yield the same result type
// URL: "type.googleapis.com/<message_full_name>".
- void PackFrom(const Message& message, const string& type_url_prefix);
+ void PackFrom(const Message& message, const std::string& type_url_prefix);
// 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
@@ -95,15 +97,15 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
//
// NOTE: this function is available publicly as:
// google::protobuf::Any() // static method on the generated message type.
-bool ParseAnyTypeUrl(const string& type_url, string* full_type_name);
+bool ParseAnyTypeUrl(const std::string& type_url, std::string* full_type_name);
// Get the proto type name and prefix from Any::type_url value. For example,
// passing "type.googleapis.com/rpc.QueryOrigin" will return
// "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in
// *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* url_prefix,
- string* full_type_name);
+bool ParseAnyTypeUrl(const std::string& type_url, std::string* url_prefix,
+ std::string* full_type_name);
// See if message is of type google.protobuf.Any, if so, return the descriptors
// for "type_url" and "value" fields.
@@ -113,6 +115,8 @@ bool GetAnyFieldDescriptors(const Message& message,
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_ANY_H__
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc
index 9d632efe..a45f6580 100644
--- a/src/google/protobuf/any.pb.cc
+++ b/src/google/protobuf/any.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class AnyDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Any>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Any> _instance;
} _Any_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fany_2eproto {
-static void InitDefaultsAny() {
+static void InitDefaultsAny_google_2fprotobuf_2fany_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,25 +35,27 @@ static void InitDefaultsAny() {
::google::protobuf::Any::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny_google_2fprotobuf_2fany_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Any.base);
+void InitDefaults_google_2fprotobuf_2fany_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, type_url_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Any, value_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Any)},
};
@@ -66,51 +63,33 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fany_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fany_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fany_2eproto,
+ "\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"
+ "%github.com/golang/protobuf/ptypes/any\242\002"
+ "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p"
+ "roto3"
+,
+ "google/protobuf/any.proto", &assign_descriptors_table_google_2fprotobuf_2fany_2eproto, 205,
+};
-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"
- "%github.com/golang/protobuf/ptypes/any\242\002"
- "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p"
- "roto3"
+void AddDescriptors_google_2fprotobuf_2fany_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 205);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/any.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fany_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fany_2eproto = []() { AddDescriptors_google_2fprotobuf_2fany_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -135,6 +114,17 @@ bool Any::ParseAnyTypeUrl(const string& type_url,
return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,
full_type_name);
}
+bool Any::GetAnyFieldDescriptors(
+ const ::google::protobuf::Message& message,
+ const ::google::protobuf::FieldDescriptor** type_url_field,
+ const ::google::protobuf::FieldDescriptor** value_field) {
+ return ::google::protobuf::internal::GetAnyFieldDescriptors(
+ message, type_url_field, value_field);
+}
+
+class Any::HasBitSetters {
+ public:
+};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Any::kTypeUrlFieldNumber;
@@ -143,8 +133,6 @@ const int Any::kValueFieldNumber;
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
}
@@ -165,6 +153,8 @@ Any::Any(const Any& from)
}
void Any::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -182,13 +172,8 @@ void Any::SharedDtor() {
void Any::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Any::descriptor() {
- ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Any& Any::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Any_google_2fprotobuf_2fany_2eproto.base);
return *internal_default_instance();
}
@@ -204,9 +189,76 @@ void Any::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Any::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Any*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string type_url = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Any.type_url");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_type_url();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // bytes value = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::StringParser;
+ ::std::string* str = msg->mutable_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ str->append(ptr, size);
+ ptr += size;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Any::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Any)
for (;;) {
@@ -216,8 +268,7 @@ bool Any::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string type_url = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -232,8 +283,7 @@ bool Any::MergePartialFromCodedStream(
// bytes value = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
@@ -261,6 +311,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Any::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -284,9 +335,9 @@ void Any::SerializeWithCachedSizes(
2, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Any)
}
@@ -316,9 +367,9 @@ void Any::SerializeWithCachedSizes(
2, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any)
return target;
@@ -328,11 +379,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// string type_url = 1;
if (this->type_url().size() > 0) {
total_size += 1 +
@@ -356,7 +411,7 @@ void Any::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Any)
GOOGLE_DCHECK_NE(&from, this);
const Any* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Any>(
+ ::google::protobuf::DynamicCastToGenerated<Any>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Any)
@@ -408,16 +463,16 @@ void Any::Swap(Any* other) {
}
void Any::InternalSwap(Any* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Any::GetMetadata() const {
- protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fany_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fany_2eproto[kIndexInFileMessages];
}
@@ -426,10 +481,11 @@ void Any::InternalSwap(Any* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Any >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index 157fc80c..c931d500 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -32,30 +33,28 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/any.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fany_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fany_2eproto();
namespace google {
namespace protobuf {
class Any;
class AnyDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*);
+PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -63,7 +62,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
+class PROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
public:
Any();
virtual ~Any();
@@ -89,7 +88,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Any& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -111,7 +112,10 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
}
static bool ParseAnyTypeUrl(const string& type_url,
string* full_type_name);
-
+ static bool GetAnyFieldDescriptors(
+ const ::google::protobuf::Message& message,
+ const ::google::protobuf::FieldDescriptor** type_url_field,
+ const ::google::protobuf::FieldDescriptor** value_field);
void Swap(Any* other);
friend void swap(Any& a, Any& b) {
a.Swap(&b);
@@ -134,8 +138,13 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -192,13 +201,14 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
// @@protoc_insertion_point(class_scope:google.protobuf.Any)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr type_url_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
- friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fany_2eproto;
};
// ===================================================================
@@ -328,4 +338,5 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
diff --git a/src/google/protobuf/any.proto b/src/google/protobuf/any.proto
index 49329425..c9be8541 100644
--- a/src/google/protobuf/any.proto
+++ b/src/google/protobuf/any.proto
@@ -121,7 +121,8 @@ option objc_class_prefix = "GPB";
//
message Any {
// A URL/resource name that uniquely identifies the type of the serialized
- // protocol buffer message. The last segment of the URL's path must represent
+ // protocol buffer message. This string must contain at least
+ // one "/" character. 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).
diff --git a/src/google/protobuf/any_test.cc b/src/google/protobuf/any_test.cc
index 1bfaa63d..514ac510 100644
--- a/src/google/protobuf/any_test.cc
+++ b/src/google/protobuf/any_test.cc
@@ -31,6 +31,7 @@
#include <google/protobuf/any_test.pb.h>
#include <gtest/gtest.h>
+
namespace google {
namespace protobuf {
namespace {
@@ -67,6 +68,28 @@ TEST(AnyTest, TestPackAndUnpackAny) {
EXPECT_EQ(12345, submessage.int32_value());
}
+TEST(AnyType, TestPackWithCustomTypeUrl) {
+ protobuf_unittest::TestAny submessage;
+ submessage.set_int32_value(12345);
+ google::protobuf::Any any;
+ // Pack with a custom type URL prefix.
+ any.PackFrom(submessage, "type.myservice.com");
+ EXPECT_EQ("type.myservice.com/" + submessage.GetDescriptor()->full_name(),
+ any.type_url());
+ // Pack with a custom type URL prefix ending with '/'.
+ any.PackFrom(submessage, "type.myservice.com/");
+ EXPECT_EQ("type.myservice.com/" + submessage.GetDescriptor()->full_name(),
+ any.type_url());
+ // Pack with an empty type URL prefix.
+ any.PackFrom(submessage, "");
+ EXPECT_EQ("/" + submessage.GetDescriptor()->full_name(), any.type_url());
+
+ // Test unpacking the type.
+ submessage.Clear();
+ EXPECT_TRUE(any.UnpackTo(&submessage));
+ EXPECT_EQ(12345, submessage.int32_value());
+}
+
TEST(AnyTest, TestIs) {
protobuf_unittest::TestAny submessage;
submessage.set_int32_value(12345);
@@ -83,7 +106,39 @@ TEST(AnyTest, TestIs) {
EXPECT_TRUE(message.any_value().Is<google::protobuf::Any>());
}
+TEST(AnyTest, MoveConstructor) {
+ protobuf_unittest::TestAny payload;
+ payload.set_int32_value(12345);
+
+ google::protobuf::Any src;
+ src.PackFrom(payload);
+
+ const char* type_url = src.type_url().data();
+
+ google::protobuf::Any dst(std::move(src));
+ EXPECT_EQ(type_url, dst.type_url().data());
+ ASSERT_TRUE(dst.UnpackTo(&payload));
+ EXPECT_EQ(12345, payload.int32_value());
+}
+
+TEST(AnyTest, MoveAssignment) {
+ protobuf_unittest::TestAny payload;
+ payload.set_int32_value(12345);
+
+ google::protobuf::Any src;
+ src.PackFrom(payload);
+
+ const char* type_url = src.type_url().data();
+
+ google::protobuf::Any dst;
+ dst = std::move(src);
+ EXPECT_EQ(type_url, dst.type_url().data());
+ ASSERT_TRUE(dst.UnpackTo(&payload));
+ EXPECT_EQ(12345, payload.int32_value());
+}
+
+
} // namespace
} // namespace protobuf
-
} // namespace google
+
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index e0a249d0..1734dfdf 100644
--- a/src/google/protobuf/api.pb.cc
+++ b/src/google/protobuf/api.pb.cc
@@ -6,50 +6,37 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
-namespace protobuf_google_2fprotobuf_2fapi_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method;
-} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
-namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext;
-} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
-namespace protobuf_google_2fprotobuf_2ftype_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option;
-} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto;
namespace google {
namespace protobuf {
class ApiDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Api>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Api> _instance;
} _Api_default_instance_;
class MethodDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Method>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Method> _instance;
} _Method_default_instance_;
class MixinDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Mixin>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Mixin> _instance;
} _Mixin_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fapi_2eproto {
-static void InitDefaultsApi() {
+static void InitDefaultsApi_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -60,14 +47,14 @@ static void InitDefaultsApi() {
::google::protobuf::Api::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi}, {
- &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base,
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,
- &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,
- &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api_google_2fprotobuf_2fapi_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi_google_2fprotobuf_2fapi_2eproto}, {
+ &scc_info_Method_google_2fprotobuf_2fapi_2eproto.base,
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,
+ &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base,
+ &scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base,}};
-static void InitDefaultsMethod() {
+static void InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -78,11 +65,11 @@ static void InitDefaultsMethod() {
::google::protobuf::Method::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod}, {
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method_google_2fprotobuf_2fapi_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod_google_2fprotobuf_2fapi_2eproto}, {
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}};
-static void InitDefaultsMixin() {
+static void InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -93,51 +80,53 @@ static void InitDefaultsMixin() {
::google::protobuf::Mixin::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin_google_2fprotobuf_2fapi_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin_google_2fprotobuf_2fapi_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Api.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Method.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Mixin.base);
+void InitDefaults_google_2fprotobuf_2fapi_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[3];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fapi_2eproto[3];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, methods_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, version_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, source_context_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, mixins_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Api, syntax_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_type_url_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, request_streaming_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_type_url_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, response_streaming_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Method, syntax_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Mixin, root_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Api)},
{ 12, -1, sizeof(::google::protobuf::Method)},
{ 24, -1, sizeof(::google::protobuf::Mixin)},
@@ -149,66 +138,48 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Mixin_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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);
-}
-
-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"
- "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p"
- "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google"
- ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou"
- "rce_context\030\005 \001(\0132\036.google.protobuf.Sour"
- "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto"
- "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto"
- "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r"
- "equest_type_url\030\002 \001(\t\022\031\n\021request_streami"
- "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r"
- "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013"
- "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001("
- "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n"
- "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBu\n\023com.google.pr"
- "otobufB\010ApiProtoP\001Z+google.golang.org/ge"
- "nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P"
- "rotobuf.WellKnownTypesb\006proto3"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fapi_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fapi_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fapi_2eproto, 3, file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fapi_2eproto,
+ "\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"
+ "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p"
+ "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google"
+ ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou"
+ "rce_context\030\005 \001(\0132\036.google.protobuf.Sour"
+ "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto"
+ "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto"
+ "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r"
+ "equest_type_url\030\002 \001(\t\022\031\n\021request_streami"
+ "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r"
+ "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013"
+ "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001("
+ "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n"
+ "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBu\n\023com.google.pr"
+ "otobufB\010ApiProtoP\001Z+google.golang.org/ge"
+ "nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P"
+ "rotobuf.WellKnownTypesb\006proto3"
+,
+ "google/protobuf/api.proto", &assign_descriptors_table_google_2fprotobuf_2fapi_2eproto, 750,
+};
+
+void AddDescriptors_google_2fprotobuf_2fapi_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[2] =
+ {
+ ::AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto,
+ ::AddDescriptors_google_2fprotobuf_2ftype_2eproto,
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 750);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/api.proto", &protobuf_RegisterTypes);
- ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors();
- ::protobuf_google_2fprotobuf_2ftype_2eproto::AddDescriptors();
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fapi_2eproto, deps, 2);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto = []() { AddDescriptors_google_2fprotobuf_2fapi_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -218,6 +189,15 @@ void Api::InitAsDefaultInstance() {
::google::protobuf::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
+class Api::HasBitSetters {
+ public:
+ static const ::google::protobuf::SourceContext& source_context(const Api* msg);
+};
+
+const ::google::protobuf::SourceContext&
+Api::HasBitSetters::source_context(const Api* msg) {
+ return *msg->source_context_;
+}
void Api::clear_options() {
options_.Clear();
}
@@ -239,8 +219,6 @@ const int Api::kSyntaxFieldNumber;
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
}
@@ -269,6 +247,8 @@ Api::Api(const Api& from)
}
void Api::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&source_context_, 0, static_cast<size_t>(
@@ -290,13 +270,8 @@ void Api::SharedDtor() {
void Api::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Api::descriptor() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Api& Api::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Api_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
@@ -320,9 +295,157 @@ void Api::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Api::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Api*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Api.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.Method methods = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Method::_InternalParse;
+ object = msg->add_methods();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.Option options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ // string version = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Api.version");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_version();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // .google.protobuf.SourceContext source_context = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::SourceContext::_InternalParse;
+ object = msg->mutable_source_context();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // repeated .google.protobuf.Mixin mixins = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Mixin::_InternalParse;
+ object = msg->add_mixins();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
+ break;
+ }
+ // .google.protobuf.Syntax syntax = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
+ msg->set_syntax(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Api::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Api)
for (;;) {
@@ -332,8 +455,7 @@ bool Api::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -348,8 +470,7 @@ bool Api::MergePartialFromCodedStream(
// repeated .google.protobuf.Method methods = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_methods()));
} else {
@@ -360,8 +481,7 @@ bool Api::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -372,8 +492,7 @@ bool Api::MergePartialFromCodedStream(
// string version = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -388,8 +507,7 @@ bool Api::MergePartialFromCodedStream(
// .google.protobuf.SourceContext source_context = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
@@ -400,8 +518,7 @@ bool Api::MergePartialFromCodedStream(
// repeated .google.protobuf.Mixin mixins = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_mixins()));
} else {
@@ -412,9 +529,8 @@ bool Api::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -444,6 +560,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Api::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -492,7 +609,7 @@ void Api::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->_internal_source_context(), output);
+ 5, HasBitSetters::source_context(this), output);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -510,9 +627,9 @@ void Api::SerializeWithCachedSizes(
7, this->syntax(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Api)
}
@@ -566,7 +683,7 @@ void Api::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, this->_internal_source_context(), deterministic, target);
+ 5, HasBitSetters::source_context(this), deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -583,9 +700,9 @@ void Api::SerializeWithCachedSizes(
7, this->syntax(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api)
return target;
@@ -595,11 +712,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Method methods = 2;
{
unsigned int count = static_cast<unsigned int>(this->methods_size());
@@ -669,7 +790,7 @@ void Api::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Api)
GOOGLE_DCHECK_NE(&from, this);
const Api* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Api>(
+ ::google::protobuf::DynamicCastToGenerated<Api>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Api)
@@ -730,6 +851,7 @@ void Api::Swap(Api* other) {
}
void Api::InternalSwap(Api* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_));
@@ -739,12 +861,11 @@ void Api::InternalSwap(Api* other) {
GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Api::GetMetadata() const {
- protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
@@ -752,6 +873,10 @@ void Api::InternalSwap(Api* other) {
void Method::InitAsDefaultInstance() {
}
+class Method::HasBitSetters {
+ public:
+};
+
void Method::clear_options() {
options_.Clear();
}
@@ -767,8 +892,6 @@ const int Method::kSyntaxFieldNumber;
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Method)
}
@@ -796,6 +919,8 @@ Method::Method(const Method& from)
}
void Method::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -818,13 +943,8 @@ void Method::SharedDtor() {
void Method::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Method::descriptor() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Method& Method::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Method_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
@@ -845,9 +965,142 @@ void Method::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Method::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Method*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Method.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // string request_type_url = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Method.request_type_url");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_request_type_url();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // bool request_streaming = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_request_streaming(value);
+ break;
+ }
+ // string response_type_url = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Method.response_type_url");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_response_type_url();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // bool response_streaming = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_response_streaming(value);
+ break;
+ }
+ // repeated .google.protobuf.Option options = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
+ break;
+ }
+ // .google.protobuf.Syntax syntax = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
+ msg->set_syntax(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Method::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Method)
for (;;) {
@@ -857,8 +1110,7 @@ bool Method::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -873,8 +1125,7 @@ bool Method::MergePartialFromCodedStream(
// string request_type_url = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_request_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -889,8 +1140,7 @@ bool Method::MergePartialFromCodedStream(
// bool request_streaming = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -903,8 +1153,7 @@ bool Method::MergePartialFromCodedStream(
// string response_type_url = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_response_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -919,8 +1168,7 @@ bool Method::MergePartialFromCodedStream(
// bool response_streaming = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -933,8 +1181,7 @@ bool Method::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -945,9 +1192,8 @@ bool Method::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -977,6 +1223,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Method::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1039,9 +1286,9 @@ void Method::SerializeWithCachedSizes(
7, this->syntax(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Method)
}
@@ -1110,9 +1357,9 @@ void Method::SerializeWithCachedSizes(
7, this->syntax(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method)
return target;
@@ -1122,11 +1369,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Option options = 6;
{
unsigned int count = static_cast<unsigned int>(this->options_size());
@@ -1184,7 +1435,7 @@ void Method::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Method)
GOOGLE_DCHECK_NE(&from, this);
const Method* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Method>(
+ ::google::protobuf::DynamicCastToGenerated<Method>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Method)
@@ -1250,6 +1501,7 @@ void Method::Swap(Method* other) {
}
void Method::InternalSwap(Method* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
@@ -1260,12 +1512,11 @@ void Method::InternalSwap(Method* other) {
swap(request_streaming_, other->request_streaming_);
swap(response_streaming_, other->response_streaming_);
swap(syntax_, other->syntax_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Method::GetMetadata() const {
- protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
@@ -1273,6 +1524,10 @@ void Method::InternalSwap(Method* other) {
void Mixin::InitAsDefaultInstance() {
}
+class Mixin::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Mixin::kNameFieldNumber;
const int Mixin::kRootFieldNumber;
@@ -1280,8 +1535,6 @@ const int Mixin::kRootFieldNumber;
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Mixin)
}
@@ -1301,6 +1554,8 @@ Mixin::Mixin(const Mixin& from)
}
void Mixin::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1318,13 +1573,8 @@ void Mixin::SharedDtor() {
void Mixin::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Mixin::descriptor() {
- ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Mixin& Mixin::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Mixin_google_2fprotobuf_2fapi_2eproto.base);
return *internal_default_instance();
}
@@ -1340,9 +1590,78 @@ void Mixin::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Mixin::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Mixin*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // string root = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Mixin.root");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_root();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Mixin::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Mixin)
for (;;) {
@@ -1352,8 +1671,7 @@ bool Mixin::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1368,8 +1686,7 @@ bool Mixin::MergePartialFromCodedStream(
// string root = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_root()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1401,6 +1718,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Mixin::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1428,9 +1746,9 @@ void Mixin::SerializeWithCachedSizes(
2, this->root(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Mixin)
}
@@ -1464,9 +1782,9 @@ void Mixin::SerializeWithCachedSizes(
2, this->root(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin)
return target;
@@ -1476,11 +1794,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
@@ -1504,7 +1826,7 @@ void Mixin::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Mixin)
GOOGLE_DCHECK_NE(&from, this);
const Mixin* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Mixin>(
+ ::google::protobuf::DynamicCastToGenerated<Mixin>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Mixin)
@@ -1556,16 +1878,16 @@ void Mixin::Swap(Mixin* other) {
}
void Mixin::InternalSwap(Mixin* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Mixin::GetMetadata() const {
- protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fapi_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fapi_2eproto[kIndexInFileMessages];
}
@@ -1574,16 +1896,17 @@ void Mixin::InternalSwap(Mixin* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Api >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Method >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::Mixin >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index 581e21a5..40a609b7 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -33,38 +34,36 @@
#include <google/protobuf/source_context.pb.h>
#include <google/protobuf/type.pb.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[3]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fapi_2eproto();
namespace google {
namespace protobuf {
class Api;
class ApiDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_;
+PROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_;
class Method;
class MethodDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_;
+PROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_;
class Mixin;
class MixinDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*);
+PROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -72,7 +71,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ {
+class PROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ {
public:
Api();
virtual ~Api();
@@ -98,7 +97,9 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Api& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -131,8 +132,13 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -227,9 +233,6 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
- private:
- const ::google::protobuf::SourceContext& _internal_source_context() const;
- public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
::google::protobuf::SourceContext* mutable_source_context();
@@ -243,6 +246,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
// @@protoc_insertion_point(class_scope:google.protobuf.Api)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Method > methods_;
@@ -253,11 +257,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ {
+class PROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ {
public:
Method();
virtual ~Method();
@@ -283,7 +287,9 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Method& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -316,8 +322,13 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -418,6 +429,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
// @@protoc_insertion_point(class_scope:google.protobuf.Method)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
@@ -428,11 +440,11 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool response_streaming_;
int syntax_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ {
+class PROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ {
public:
Mixin();
virtual ~Mixin();
@@ -458,7 +470,9 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Mixin& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -491,8 +505,13 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -549,12 +568,13 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(class_scope:google.protobuf.Mixin)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto;
};
// ===================================================================
@@ -734,9 +754,6 @@ 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 const ::google::protobuf::SourceContext& Api::_internal_source_context() const {
- return *source_context_;
-}
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)
@@ -1179,4 +1196,5 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc
index c117c9e5..26c291cf 100755..100644
--- a/src/google/protobuf/arena.cc
+++ b/src/google/protobuf/arena.cc
@@ -38,12 +38,12 @@
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port_def.inc>
-namespace google {
static const size_t kMinCleanupListElements = 8;
static const size_t kMaxCleanupListElements = 64; // 1kB on 64-bit.
+namespace google {
namespace protobuf {
namespace internal {
@@ -125,7 +125,7 @@ ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) {
ArenaImpl::Block::Block(size_t size, Block* next)
: next_(next), pos_(kBlockHeaderSize), size_(size) {}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
void ArenaImpl::SerialArena::AddCleanupFallback(void* elem,
void (*cleanup)(void*)) {
size_t size = cleanup_ ? cleanup_->size * 2 : kMinCleanupListElements;
@@ -142,10 +142,10 @@ void ArenaImpl::SerialArena::AddCleanupFallback(void* elem,
AddCleanup(elem, cleanup);
}
-GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32)
+PROTOBUF_FUNC_ALIGN(32)
void* ArenaImpl::AllocateAligned(size_t n) {
SerialArena* arena;
- if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
return arena->AllocateAligned(n);
} else {
return AllocateAlignedFallback(n);
@@ -155,7 +155,7 @@ void* ArenaImpl::AllocateAligned(size_t n) {
void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
void (*cleanup)(void*)) {
SerialArena* arena;
- if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
return arena->AllocateAlignedAndAddCleanup(n, cleanup);
} else {
return AllocateAlignedAndAddCleanupFallback(n, cleanup);
@@ -164,36 +164,36 @@ void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) {
SerialArena* arena;
- if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
arena->AddCleanup(elem, cleanup);
} else {
return AddCleanupFallback(elem, cleanup);
}
}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
void* ArenaImpl::AllocateAlignedFallback(size_t n) {
return GetSerialArena()->AllocateAligned(n);
}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
void* ArenaImpl::AllocateAlignedAndAddCleanupFallback(size_t n,
void (*cleanup)(void*)) {
return GetSerialArena()->AllocateAlignedAndAddCleanup(n, cleanup);
}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
void ArenaImpl::AddCleanupFallback(void* elem, void (*cleanup)(void*)) {
GetSerialArena()->AddCleanup(elem, cleanup);
}
-inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
-bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) {
+inline PROTOBUF_ALWAYS_INLINE bool ArenaImpl::GetSerialArenaFast(
+ ArenaImpl::SerialArena** arena) {
// 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.
ThreadCache* tc = &thread_cache();
- if (GOOGLE_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) {
+ if (PROTOBUF_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) {
*arena = tc->last_serial_arena;
return true;
}
@@ -201,7 +201,7 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) {
// Check whether we own the last accessed SerialArena on this arena. This
// fast path optimizes the case where a single thread uses multiple arenas.
SerialArena* serial = hint_.load(std::memory_order_acquire);
- if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) {
+ if (PROTOBUF_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) {
*arena = serial;
return true;
}
@@ -211,14 +211,14 @@ bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) {
ArenaImpl::SerialArena* ArenaImpl::GetSerialArena() {
SerialArena* arena;
- if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
+ if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
return arena;
} else {
return GetSerialArenaFallback(&thread_cache());
}
}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) {
// Sync back to current's pos.
head_->set_pos(head_->size() - (limit_ - ptr_));
@@ -362,7 +362,7 @@ ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner,
return serial;
}
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+PROTOBUF_NOINLINE
ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) {
// Look for this SerialArena in our linked list.
SerialArena* serial = threads_.load(std::memory_order_acquire);
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index 9928c8e6..a38a8021 100644
--- a/src/google/protobuf/arena.h
+++ b/src/google/protobuf/arena.h
@@ -49,22 +49,25 @@ using type_info = ::type_info;
#endif
#include <google/protobuf/arena_impl.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
#include <type_traits>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
struct ArenaOptions; // defined below
} // namespace protobuf
+} // namespace google
-namespace quality_webanswers {
-
-void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options);
-
-} // namespace quality_webanswers
+namespace google {
namespace protobuf {
class Arena; // defined below
@@ -73,7 +76,7 @@ class MessageLite;
namespace arena_metrics {
-void EnableArenaMetrics(::google::protobuf::ArenaOptions* options);
+void EnableArenaMetrics(ArenaOptions* options);
} // namespace arena_metrics
@@ -177,15 +180,14 @@ struct ArenaOptions {
static const size_t kDefaultStartBlockSize = 256;
static const size_t kDefaultMaxBlockSize = 8192;
- friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*);
- friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*);
+ friend void arena_metrics::EnableArenaMetrics(ArenaOptions*);
friend class Arena;
friend class ArenaOptionsTestFriend;
};
// Support for non-RTTI environments. (The metrics hooks API uses type
// information.)
-#ifndef GOOGLE_PROTOBUF_NO_RTTI
+#if PROTOBUF_RTTI
#define RTTI_TYPE_ID(type) (&typeid(type))
#else
#define RTTI_TYPE_ID(type) (NULL)
@@ -216,7 +218,7 @@ struct ArenaOptions {
//
// - The type T must have (at least) two constructors: a constructor with no
// arguments, called when a T is allocated on the heap; and a constructor with
-// a google::protobuf::Arena* argument, called when a T is allocated on an arena. If the
+// a Arena* argument, called when a T is allocated on an arena. If the
// second constructor is called with a NULL arena pointer, it must be
// equivalent to invoking the first (no-argument) constructor.
//
@@ -237,11 +239,13 @@ struct ArenaOptions {
// arg1, arg2).
//
// This protocol is implemented by all arena-enabled proto2 message classes as
-// well as RepeatedPtrField.
+// well as protobuf container types like RepeatedPtrField and Map. The protocol
+// is internal to protobuf and is not guaranteed to be stable. Non-proto types
+// should not rely on this protocol.
//
// Do NOT subclass Arena. This class will be marked as final when C++11 is
// enabled.
-class LIBPROTOBUF_EXPORT Arena {
+class PROTOBUF_EXPORT Arena {
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
@@ -291,8 +295,7 @@ class LIBPROTOBUF_EXPORT Arena {
// This function also accepts any type T that satisfies the arena message
// allocation protocol, documented above.
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
- Arena* arena, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
@@ -318,8 +321,7 @@ class LIBPROTOBUF_EXPORT Arena {
// if the object were allocated on the heap (except that the underlying memory
// is obtained from the arena).
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena,
- Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* Create(Arena* arena, Args&&... args) {
return CreateNoMessage<T>(arena, is_arena_constructable<T>(),
std::forward<Args>(args)...);
}
@@ -331,8 +333,8 @@ class LIBPROTOBUF_EXPORT Arena {
// (when compiled as C++11) that T is trivially default-constructible and
// trivially destructible.
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray(
- Arena* arena, size_t num_elements) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateArray(Arena* arena,
+ size_t num_elements) {
static_assert(std::is_pod<T>::value,
"CreateArray requires a trivially constructible type");
static_assert(std::is_trivially_destructible<T>::value,
@@ -359,7 +361,7 @@ class LIBPROTOBUF_EXPORT Arena {
//
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
- PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()")
+ PROTOBUF_DEPRECATED_MSG("Please use SpaceAllocated() and SpaceUsed()")
std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
return std::make_pair(SpaceAllocated(), SpaceUsed());
}
@@ -369,7 +371,7 @@ class LIBPROTOBUF_EXPORT Arena {
// 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_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() {
+ PROTOBUF_NOINLINE uint64 Reset() {
// Call the reset hook
if (on_arena_reset_ != NULL) {
on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated());
@@ -380,7 +382,7 @@ class LIBPROTOBUF_EXPORT Arena {
// 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_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) {
+ PROTOBUF_NOINLINE void Own(T* object) {
OwnInternal(object, std::is_convertible<T*, Message*>());
}
@@ -390,7 +392,7 @@ class LIBPROTOBUF_EXPORT Arena {
// normally only used for objects that are placement-newed into
// arena-allocated memory.
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) {
+ PROTOBUF_NOINLINE void OwnDestructor(T* object) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
}
@@ -400,7 +402,7 @@ 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_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor(
+ PROTOBUF_NOINLINE void OwnCustomDestructor(
void* object, void (*destruct)(void*)) {
impl_.AddCleanup(object, destruct);
}
@@ -410,8 +412,7 @@ class LIBPROTOBUF_EXPORT Arena {
// latter is a virtual call, while this method is a templated call that
// resolves at compile-time.
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena(
- const T* value) {
+ PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) {
return GetArenaInternal(value, is_arena_constructable<T>());
}
@@ -469,8 +470,8 @@ class LIBPROTOBUF_EXPORT Arena {
private:
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
- Arena* arena, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena,
+ Args&&... args) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
@@ -485,8 +486,7 @@ class LIBPROTOBUF_EXPORT Arena {
// slightly different. When the arena pointer is nullptr, it calls T()
// instead of T(nullptr).
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
- Arena* arena) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateMessageInternal(Arena* arena) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
@@ -498,8 +498,8 @@ class LIBPROTOBUF_EXPORT Arena {
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal(
- Arena* arena, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena,
+ Args&&... args) {
if (arena == NULL) {
return new T(std::forward<Args>(args)...);
} else {
@@ -511,7 +511,7 @@ class LIBPROTOBUF_EXPORT Arena {
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)) {
+ if (PROTOBUF_PREDICT_FALSE(hooks_cookie_ != NULL)) {
OnArenaAllocation(allocated_type, n);
}
}
@@ -520,8 +520,7 @@ class LIBPROTOBUF_EXPORT Arena {
// 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) {
+ PROTOBUF_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.
@@ -539,27 +538,29 @@ class LIBPROTOBUF_EXPORT Arena {
// 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, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(
- Arena* arena, std::true_type, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena,
+ std::true_type,
+ Args&&... args) {
return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage(
- Arena* arena, std::false_type, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena,
+ std::false_type,
+ Args&&... args) {
return CreateInternal<T>(arena, std::forward<Args>(args)...);
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage(
- Arena* arena, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena,
+ Args&&... args) {
return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(),
std::forward<Args>(args)...);
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage(
- Arena* arena, std::true_type, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena, std::true_type,
+ Args&&... args) {
// User is constructing with Create() despite the fact that T supports arena
// construction. In this case we have to delegate to CreateInternal(), and
// we can't use any CreateMaybeMessage() specialization that may be defined.
@@ -567,8 +568,9 @@ class LIBPROTOBUF_EXPORT Arena {
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage(
- Arena* arena, std::false_type, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE static T* CreateNoMessage(Arena* arena,
+ std::false_type,
+ Args&&... args) {
// User is constructing with Create() and the type does not support arena
// construction. In this case we can delegate to CreateMaybeMessage() and
// use any specialization that may be available for that.
@@ -578,8 +580,7 @@ class LIBPROTOBUF_EXPORT Arena {
// Just allocate the required size for the given type assuming the
// type has a trivial constructor.
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray(
- size_t num_elements) {
+ PROTOBUF_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.";
const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements);
@@ -589,21 +590,21 @@ class LIBPROTOBUF_EXPORT Arena {
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate(
- bool skip_explicit_ownership, Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE T* DoCreate(bool skip_explicit_ownership,
+ Args&&... args) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) {
+ PROTOBUF_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this, std::forward<Args>(args)...);
}
// CreateInArenaStorage is used to implement map field. Without it,
- // google::protobuf::Map need to call generated message's protected arena constructor,
- // which needs to declare google::protobuf::Map as friend of generated message.
+ // Map need to call generated message's protected arena constructor,
+ // which needs to declare Map as friend of generated message.
template <typename T>
static void CreateInArenaStorage(T* ptr, Arena* arena) {
CreateInArenaStorageInternal(ptr, arena,
@@ -635,19 +636,17 @@ class LIBPROTOBUF_EXPORT Arena {
// These implement Own(), which registers an object for deletion (destructor
// call and operator delete()). The second parameter has type 'true_type' if T
- // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing
+ // is a subtype of 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
- std::true_type) {
+ PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_delete_object<Message>);
}
}
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
- std::false_type) {
+ PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_delete_object<T>);
}
@@ -657,14 +656,14 @@ class LIBPROTOBUF_EXPORT Arena {
// InternalArenaConstructable_ tags can be associated with an arena, and such
// objects must implement a GetArenaNoVirtual() method.
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
- const T* value, std::true_type) {
+ PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value,
+ std::true_type) {
return InternalHelper<T>::GetArena(value);
}
template <typename T>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
- const T* /* value */, std::false_type) {
+ PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* /* value */,
+ std::false_type) {
return NULL;
}
@@ -698,6 +697,8 @@ class LIBPROTOBUF_EXPORT Arena {
#undef RTTI_TYPE_ID
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_ARENA_H__
diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h
index f648f166..a0fb1069 100644
--- a/src/google/protobuf/arena_impl.h
+++ b/src/google/protobuf/arena_impl.h
@@ -39,14 +39,14 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/port.h>
-
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+namespace google {
namespace protobuf {
namespace internal {
@@ -61,7 +61,7 @@ inline size_t AlignUpTo8(size_t n) {
// 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 {
+class PROTOBUF_EXPORT ArenaImpl {
public:
struct Options {
size_t start_block_size;
@@ -137,7 +137,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
class Block;
// A thread-unsafe Arena that can only be used within its owning thread.
- class LIBPROTOBUF_EXPORT SerialArena {
+ class PROTOBUF_EXPORT SerialArena {
public:
// The allocate/free methods here are a little strange, since SerialArena is
// allocated inside a Block which it also manages. This is to avoid doing
@@ -157,7 +157,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
void* AllocateAligned(size_t n) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
GOOGLE_DCHECK_GE(limit_, ptr_);
- if (GOOGLE_PREDICT_FALSE(static_cast<size_t>(limit_ - ptr_) < n)) {
+ if (PROTOBUF_PREDICT_FALSE(static_cast<size_t>(limit_ - ptr_) < n)) {
return AllocateAlignedFallback(n);
}
void* ret = ptr_;
@@ -169,7 +169,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
}
void AddCleanup(void* elem, void (*cleanup)(void*)) {
- if (GOOGLE_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) {
+ if (PROTOBUF_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) {
AddCleanupFallback(elem, cleanup);
return;
}
@@ -212,7 +212,7 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// Blocks are variable length malloc-ed objects. The following structure
// describes the common header for all blocks.
- class LIBPROTOBUF_EXPORT Block {
+ class PROTOBUF_EXPORT Block {
public:
Block(size_t size, Block* next);
@@ -316,6 +316,8 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__
diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h
index df56ece8..fdbaca06 100644
--- a/src/google/protobuf/arena_test_util.h
+++ b/src/google/protobuf/arena_test_util.h
@@ -33,6 +33,8 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/arena.h>
namespace google {
@@ -41,16 +43,23 @@ namespace protobuf {
template <typename T, bool use_arena>
void TestParseCorruptedString(const T& message) {
int success_count = 0;
- string s = message.SerializeAsString();
+ std::string s;
+ {
+ // Map order is not deterministic. To make the test deterministic we want
+ // to serialize the proto deterministically.
+ io::StringOutputStream output(&s);
+ io::CodedOutputStream out(&output);
+ out.SetSerializationDeterministic(true);
+ message.SerializePartialToCodedStream(&out);
+ }
const int kMaxIters = 900;
const int stride = s.size() <= kMaxIters ? 1 : s.size() / kMaxIters;
const int start = stride == 1 || use_arena ? 0 : (stride + 1) / 2;
for (int i = start; i < s.size(); i += stride) {
for (int c = 1 + (i % 17); c < 256; c += 2 * c + (i & 3)) {
s[i] ^= c;
- google::protobuf::Arena arena;
- T* message =
- google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : nullptr);
+ Arena arena;
+ T* message = Arena::CreateMessage<T>(use_arena ? &arena : nullptr);
if (message->ParseFromString(s)) {
++success_count;
}
@@ -86,6 +95,6 @@ class NoHeapChecker {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_ARENA_TEST_UTIL_H__
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc
index eaaffce2..361b83ef 100644
--- a/src/google/protobuf/arena_unittest.cc
+++ b/src/google/protobuf/arena_unittest.cc
@@ -52,18 +52,19 @@
#include <google/protobuf/message.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h>
-#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/unknown_field_set.h>
+#include <google/protobuf/wire_format_lite.h>
#include <gtest/gtest.h>
-namespace google {
+
using proto2_arena_unittest::ArenaMessage;
using protobuf_unittest::TestAllTypes;
using protobuf_unittest::TestAllExtensions;
using protobuf_unittest::TestOneof2;
using protobuf_unittest::TestEmptyMessage;
+namespace google {
namespace protobuf {
class Notifier {
@@ -279,7 +280,7 @@ TEST(ArenaTest, InitialBlockTooSmall) {
options.initial_block_size = arena_block.size();
Arena arena(options);
- char* p = ::google::protobuf::Arena::CreateArray<char>(&arena, 96);
+ char* p = Arena::CreateArray<char>(&arena, 96);
uintptr_t allocation = reinterpret_cast<uintptr_t>(p);
// Ensure that the arena allocator did not return memory pointing into the
@@ -585,7 +586,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) {
delete nested_string;
}
-#ifndef GOOGLE_PROTOBUF_NO_RTTI
+#if PROTOBUF_RTTI
TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) {
TestAllTypes::NestedMessage* nested_msg = NULL;
// Note: no string: reflection API only supports releasing submessages.
@@ -602,7 +603,7 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) {
EXPECT_EQ(42, nested_msg->bb());
delete nested_msg;
}
-#endif // !GOOGLE_PROTOBUF_NO_RTTI
+#endif // PROTOBUF_RTTI
TEST(ArenaTest, SetAllocatedAcrossArenas) {
Arena arena1;
@@ -1128,7 +1129,7 @@ TEST(ArenaTest, RepeatedFieldOnArena) {
}
-#ifndef GOOGLE_PROTOBUF_NO_RTTI
+#if PROTOBUF_RTTI
TEST(ArenaTest, MutableMessageReflection) {
Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
@@ -1152,7 +1153,7 @@ TEST(ArenaTest, MutableMessageReflection) {
EXPECT_EQ(submessage_expected, submessage);
EXPECT_EQ(&arena, submessage->GetArena());
}
-#endif // !GOOGLE_PROTOBUF_NO_RTTI
+#endif // PROTOBUF_RTTI
void FillArenaAwareFields(TestAllTypes* message) {
@@ -1198,7 +1199,7 @@ TEST(ArenaTest, ParseCorruptedString) {
TestParseCorruptedString<TestAllTypes, false>(message);
}
-#ifndef GOOGLE_PROTOBUF_NO_RTTI
+#if PROTOBUF_RTTI
// Test construction on an arena via generic MessageLite interface. We should be
// able to successfully deserialize on the arena without incurring heap
// allocations, i.e., everything should still be arena-allocation-aware.
@@ -1208,7 +1209,7 @@ TEST(ArenaTest, MessageLiteOnArena) {
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
Arena arena(options);
- const google::protobuf::MessageLite* prototype = &TestAllTypes::default_instance();
+ const MessageLite* prototype = &TestAllTypes::default_instance();
TestAllTypes initial_message;
FillArenaAwareFields(&initial_message);
@@ -1217,7 +1218,7 @@ TEST(ArenaTest, MessageLiteOnArena) {
{
- google::protobuf::MessageLite* generic_message = prototype->New(&arena);
+ MessageLite* generic_message = prototype->New(&arena);
EXPECT_TRUE(generic_message != NULL);
EXPECT_EQ(&arena, generic_message->GetArena());
EXPECT_TRUE(generic_message->ParseFromString(serialized));
@@ -1227,7 +1228,7 @@ TEST(ArenaTest, MessageLiteOnArena) {
arena.Reset();
}
-#endif // !GOOGLE_PROTOBUF_NO_RTTI
+#endif // PROTOBUF_RTTI
// RepeatedField should support non-POD types, and invoke constructors and
@@ -1260,7 +1261,7 @@ TEST(ArenaTest, SpaceAllocated_and_Used) {
EXPECT_EQ(0, arena_1.SpaceAllocated());
EXPECT_EQ(0, arena_1.SpaceUsed());
EXPECT_EQ(0, arena_1.Reset());
- ::google::protobuf::Arena::CreateArray<char>(&arena_1, 320);
+ Arena::CreateArray<char>(&arena_1, 320);
// Arena will allocate slightly more than 320 for the block headers.
EXPECT_LE(320, arena_1.SpaceAllocated());
EXPECT_EQ(Align8(320), arena_1.SpaceUsed());
@@ -1274,7 +1275,7 @@ TEST(ArenaTest, SpaceAllocated_and_Used) {
EXPECT_EQ(1024, arena_2.SpaceAllocated());
EXPECT_EQ(0, arena_2.SpaceUsed());
EXPECT_EQ(1024, arena_2.Reset());
- ::google::protobuf::Arena::CreateArray<char>(&arena_2, 55);
+ Arena::CreateArray<char>(&arena_2, 55);
EXPECT_EQ(1024, arena_2.SpaceAllocated());
EXPECT_EQ(Align8(55), arena_2.SpaceUsed());
EXPECT_EQ(1024, arena_2.Reset());
@@ -1284,41 +1285,41 @@ 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, 160);
+ Arena::CreateArray<char>(&arena_3, 160);
EXPECT_EQ(256, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(160), arena_3.SpaceUsed());
- ::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
+ Arena::CreateArray<char>(&arena_3, 70);
EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(160) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(256 + 512, arena_3.Reset());
}
TEST(ArenaTest, Alignment) {
- ::google::protobuf::Arena arena;
+ Arena arena;
for (int i = 0; i < 200; i++) {
- void* p = ::google::protobuf::Arena::CreateArray<char>(&arena, i);
+ void* p = Arena::CreateArray<char>(&arena, i);
GOOGLE_CHECK_EQ(reinterpret_cast<uintptr_t>(p) % 8, 0) << i << ": " << p;
}
}
TEST(ArenaTest, BlockSizeSmallerThanAllocation) {
for (size_t i = 0; i <= 8; ++i) {
- ::google::protobuf::ArenaOptions opt;
+ ArenaOptions opt;
opt.start_block_size = opt.max_block_size = i;
- ::google::protobuf::Arena arena(opt);
+ Arena arena(opt);
- *::google::protobuf::Arena::Create<int64>(&arena) = 42;
+ *Arena::Create<int64>(&arena) = 42;
EXPECT_GE(arena.SpaceAllocated(), 8);
EXPECT_EQ(8, arena.SpaceUsed());
- *::google::protobuf::Arena::Create<int64>(&arena) = 42;
+ *Arena::Create<int64>(&arena) = 42;
EXPECT_GE(arena.SpaceAllocated(), 16);
EXPECT_EQ(16, arena.SpaceUsed());
}
}
TEST(ArenaTest, GetArenaShouldReturnTheArenaForArenaAllocatedMessages) {
- ::google::protobuf::Arena arena;
+ Arena arena;
ArenaMessage* message = Arena::CreateMessage<ArenaMessage>(&arena);
const ArenaMessage* const_pointer_to_message = message;
EXPECT_EQ(&arena, Arena::GetArena(message));
@@ -1333,14 +1334,14 @@ TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) {
}
TEST(ArenaTest, AddCleanup) {
- ::google::protobuf::Arena arena;
+ Arena arena;
for (int i = 0; i < 100; i++) {
arena.Own(new int);
}
}
TEST(ArenaTest, UnsafeSetAllocatedOnArena) {
- ::google::protobuf::Arena arena;
+ Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
EXPECT_FALSE(message->has_optional_string());
@@ -1357,7 +1358,7 @@ TEST(ArenaTest, UnsafeSetAllocatedOnArena) {
// value to be verified.
class ArenaHooksTestUtil {
public:
- static void* on_init(::google::protobuf::Arena* arena) {
+ static void* on_init(Arena* arena) {
++num_init;
int* cookie = new int(kCookieValue);
return static_cast<void*>(cookie);
@@ -1370,15 +1371,13 @@ class ArenaHooksTestUtil {
EXPECT_EQ(kCookieValue, cookie_value);
}
- static void on_reset(::google::protobuf::Arena* arena, void* cookie,
- uint64 space_used) {
+ static void on_reset(Arena* arena, void* cookie, uint64 space_used) {
++num_reset;
int cookie_value = *static_cast<int*>(cookie);
EXPECT_EQ(kCookieValue, cookie_value);
}
- static void on_destruction(::google::protobuf::Arena* arena, void* cookie,
- uint64 space_used) {
+ static void on_destruction(Arena* arena, void* cookie, uint64 space_used) {
++num_destruct;
int cookie_value = *static_cast<int*>(cookie);
EXPECT_EQ(kCookieValue, cookie_value);
@@ -1399,7 +1398,7 @@ const int ArenaHooksTestUtil::kCookieValue;
class ArenaOptionsTestFriend {
public:
- static void Set(::google::protobuf::ArenaOptions* options) {
+ static void Set(ArenaOptions* options) {
options->on_arena_init = ArenaHooksTestUtil::on_init;
options->on_arena_allocation = ArenaHooksTestUtil::on_allocation;
options->on_arena_reset = ArenaHooksTestUtil::on_reset;
@@ -1409,15 +1408,15 @@ class ArenaOptionsTestFriend {
// Test the hooks are correctly called and that the cookie is passed.
TEST(ArenaTest, ArenaHooksSanity) {
- ::google::protobuf::ArenaOptions options;
+ ArenaOptions options;
ArenaOptionsTestFriend::Set(&options);
// Scope for defining the arena
{
- ::google::protobuf::Arena arena(options);
+ Arena arena(options);
EXPECT_EQ(1, ArenaHooksTestUtil::num_init);
EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations);
- ::google::protobuf::Arena::Create<uint64>(&arena);
+ Arena::Create<uint64>(&arena);
if (std::is_trivially_destructible<uint64>::value) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations);
} else {
diff --git a/src/google/protobuf/arenastring.h b/src/google/protobuf/arenastring.h
index 168fc972..cb4dc8b3 100755..100644
--- a/src/google/protobuf/arenastring.h
+++ b/src/google/protobuf/arenastring.h
@@ -39,6 +39,8 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port_def.inc>
+
// This is the implementation of arena string fields written for the open-source
// release. The ArenaStringPtr struct below is an internal implementation class
// and *should not be used* by user code. It is used to collect string
@@ -63,7 +65,7 @@ class TaggedPtr {
uintptr_t ptr_;
};
-struct LIBPROTOBUF_EXPORT ArenaStringPtr {
+struct PROTOBUF_EXPORT ArenaStringPtr {
inline void Set(const ::std::string* default_value,
const ::std::string& value, ::google::protobuf::Arena* arena) {
if (ptr_ == default_value) {
@@ -168,11 +170,12 @@ 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
+ PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
std::swap(ptr_, other->ptr_);
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(
- ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) {
+ PROTOBUF_ALWAYS_INLINE void Swap(ArenaStringPtr* other,
+ const ::std::string* default_value,
+ Arena* arena) {
#ifndef NDEBUG
// For debug builds, we swap the contents of the string, rather than the
// string instances themselves. This invalidates previously taken const
@@ -364,14 +367,14 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
private:
::std::string* ptr_;
- GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ PROTOBUF_NOINLINE
void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
// uses "new ::std::string" when arena is nullptr
ptr_ = Arena::Create< ::std::string >(arena, *initial_value);
}
- GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ PROTOBUF_NOINLINE
void CreateInstanceNoArena(const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
ptr_ = new ::std::string(*initial_value);
@@ -398,6 +401,8 @@ inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_ARENASTRING_H__
diff --git a/src/google/protobuf/arenastring_unittest.cc b/src/google/protobuf/arenastring_unittest.cc
index adc44fe2..c5f89a70 100644
--- a/src/google/protobuf/arenastring_unittest.cc
+++ b/src/google/protobuf/arenastring_unittest.cc
@@ -45,11 +45,12 @@
#include <google/protobuf/io/zero_copy_stream_impl.h>
-namespace google {
-using google::protobuf::internal::ArenaStringPtr;
+namespace google {
namespace protobuf {
+using internal::ArenaStringPtr;
+
static string WrapString(const char* value) {
return value;
@@ -81,7 +82,7 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnHeap) {
}
TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
- google::protobuf::Arena arena;
+ Arena arena;
ArenaStringPtr field;
::std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
@@ -107,7 +108,7 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
}
TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) {
- google::protobuf::Arena arena;
+ Arena arena;
ArenaStringPtr field;
::std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h
index 90bd88b3..fbd3dec5 100644
--- a/src/google/protobuf/compiler/annotation_test_util.h
+++ b/src/google/protobuf/compiler/annotation_test_util.h
@@ -49,15 +49,15 @@ namespace annotation_test_util {
// file_content = content of Foo.java
// file_info = parsed content of Foo.java.pb.meta
struct ExpectedOutput {
- string file_path;
- string file_content;
+ std::string file_path;
+ std::string file_content;
GeneratedCodeInfo file_info;
- explicit ExpectedOutput(const string& file_path) : file_path(file_path) {}
+ explicit ExpectedOutput(const std::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);
+void AddFile(const std::string& filename, const std::string& data);
// Runs proto compiler. Captures proto file structrue in FileDescriptorProto.
// Files will be generated in TestTempDir() folder. Callers of this
@@ -70,45 +70,45 @@ void AddFile(const string& filename, const string& data);
// 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.
-bool RunProtoCompiler(const string& filename,
- const string& plugin_specific_args,
+bool RunProtoCompiler(const std::string& filename,
+ const std::string& plugin_specific_args,
CommandLineInterface* cli, FileDescriptorProto* file);
-bool DecodeMetadata(const string& path, GeneratedCodeInfo* info);
+bool DecodeMetadata(const std::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
+// See Location.path in http://google3/net/proto2/proto/descriptor.proto for
// explanation of what path vector is.
void FindAnnotationsOnPath(
- const GeneratedCodeInfo& info, const string& source_file,
+ const GeneratedCodeInfo& info, const std::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
+// http://google3/net/proto2/proto/descriptor.proto for explanation of what path
// vector is.
const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
- const GeneratedCodeInfo& info, const string& source_file,
+ const GeneratedCodeInfo& info, const std::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::string& file_content,
const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
- const string& expected_text);
+ const std::string& expected_text);
// Returns true if the provided annotation covers a given substring in
// file_content.
-bool AnnotationMatchesSubstring(const string& file_content,
+bool AnnotationMatchesSubstring(const std::string& file_content,
const GeneratedCodeInfo::Annotation* annotation,
- const string& expected_text);
+ const std::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 4c2b3ee1..b1eb61ac 100644
--- a/src/google/protobuf/compiler/code_generator.h
+++ b/src/google/protobuf/compiler/code_generator.h
@@ -43,6 +43,8 @@
#include <vector>
#include <utility>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -61,7 +63,7 @@ class GeneratorContext;
// The abstract interface to a class which generates code implementing a
// particular proto file in a particular language. A number of these may
// be registered with CommandLineInterface to support various languages.
-class LIBPROTOC_EXPORT CodeGenerator {
+class PROTOC_EXPORT CodeGenerator {
public:
inline CodeGenerator() {}
virtual ~CodeGenerator();
@@ -78,9 +80,9 @@ class LIBPROTOC_EXPORT CodeGenerator {
// Returns true if successful. Otherwise, sets *error to a description of
// the problem (e.g. "invalid parameter") and returns false.
virtual bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* generator_context,
- string* error) const = 0;
+ std::string* error) const = 0;
// Generates code for all given proto files.
//
@@ -94,9 +96,9 @@ class LIBPROTOC_EXPORT CodeGenerator {
// Returns true if successful. Otherwise, sets *error to a description of
// the problem (e.g. "invalid parameter") and returns false.
virtual bool GenerateAll(const std::vector<const FileDescriptor*>& files,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* generator_context,
- string* error) const;
+ std::string* error) const;
// This is no longer used, but this class is part of the opensource protobuf
// library, so it has to remain to keep vtables the same for the current
@@ -112,7 +114,7 @@ class LIBPROTOC_EXPORT CodeGenerator {
// abstract interface represents the directory to which the CodeGenerator is
// to write and other information about the context in which the Generator
// runs.
-class LIBPROTOC_EXPORT GeneratorContext {
+class PROTOC_EXPORT GeneratorContext {
public:
inline GeneratorContext() {
}
@@ -128,10 +130,10 @@ class LIBPROTOC_EXPORT GeneratorContext {
// generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that
// "foo/" is included in these filenames. The filename is not allowed to
// contain "." or ".." components.
- virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0;
+ virtual io::ZeroCopyOutputStream* Open(const std::string& filename) = 0;
// Similar to Open() but the output will be appended to the file if exists
- virtual io::ZeroCopyOutputStream* OpenForAppend(const string& filename);
+ virtual io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename);
// Creates a ZeroCopyOutputStream which will insert code into the given file
// at the given insertion point. See plugin.proto (plugin.pb.h) for more
@@ -140,7 +142,7 @@ class LIBPROTOC_EXPORT GeneratorContext {
//
// WARNING: This feature is currently EXPERIMENTAL and is subject to change.
virtual io::ZeroCopyOutputStream* OpenForInsert(
- const string& filename, const string& insertion_point);
+ const std::string& filename, const std::string& insertion_point);
// Returns a vector of FileDescriptors for all the files being compiled
// in this run. Useful for languages, such as Go, that treat files
@@ -166,11 +168,13 @@ typedef GeneratorContext OutputDirectory;
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
-LIBPROTOC_EXPORT void ParseGeneratorParameter(
- const string&, std::vector<std::pair<string, string> >*);
+PROTOC_EXPORT void ParseGeneratorParameter(
+ const std::string&, std::vector<std::pair<std::string, std::string> >*);
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index 8380367f..4d1ef09b 100644
--- a/src/google/protobuf/compiler/command_line_interface.cc
+++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -84,6 +84,8 @@
#include <google/protobuf/stubs/io_win32.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -168,7 +170,9 @@ bool VerifyDirectoryExists(const string& path) {
// directories listed in |filename|.
bool TryCreateParentDirectory(const string& prefix, const string& filename) {
// Recursively create parent directories to the output file.
- std::vector<string> parts = Split(filename, "/", true);
+ // On Windows, both '/' and '\' are valid path separators.
+ std::vector<string> parts =
+ Split(filename, "/\\", true);
string path_so_far = prefix;
for (int i = 0; i < parts.size() - 1; i++) {
path_so_far += parts[i];
@@ -395,7 +399,7 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext {
private:
friend class MemoryOutputStream;
- // map instead of hash_map so that files are written in order (good when
+ // map instead of unordered_map so that files are written in order (good when
// writing zips).
std::map<string, string*> files_;
const std::vector<const FileDescriptor*>& parsed_files_;
@@ -749,7 +753,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Now copy in the data.
string::size_type data_pos = 0;
- char* target_ptr = string_as_array(target) + pos;
+ char* target_ptr = ::google::protobuf::string_as_array(target) + pos;
while (data_pos < data_.size()) {
// Copy indent.
memcpy(target_ptr, indent_.data(), indent_.size());
@@ -766,7 +770,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
}
GOOGLE_CHECK_EQ(target_ptr,
- string_as_array(target) + pos + data_.size() + indent_size);
+ ::google::protobuf::string_as_array(target) + pos + data_.size() + indent_size);
}
}
}
@@ -988,6 +992,7 @@ bool CommandLineInterface::InitializeDiskSourceTree(
if (!MakeInputsBeProtoPathRelative(source_tree)) {
return false;
}
+
return true;
}
@@ -1039,15 +1044,15 @@ bool CommandLineInterface::ParseInputFiles(
std::vector<const FileDescriptor*>* parsed_files) {
// Parse each file.
- for (int i = 0; i < input_files_.size(); i++) {
+ for (const auto& input_file : input_files_) {
// Import the file.
- descriptor_pool->AddUnusedImportTrackFile(input_files_[i]);
+ descriptor_pool->AddUnusedImportTrackFile(input_file);
const FileDescriptor* parsed_file =
- descriptor_pool->FindFileByName(input_files_[i]);
+ descriptor_pool->FindFileByName(input_file);
descriptor_pool->ClearUnusedImportTrackFiles();
if (parsed_file == NULL) {
if (!descriptor_set_in_names_.empty()) {
- std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
+ std::cerr << input_file << ": " << strerror(ENOENT) << std::endl;
}
return false;
}
@@ -1096,6 +1101,7 @@ void CommandLineInterface::Clear() {
descriptor_set_out_name_.clear();
dependency_out_name_.clear();
+
mode_ = MODE_COMPILE;
print_mode_ = PRINT_NONE;
imports_in_descriptor_set_ = false;
@@ -1104,64 +1110,73 @@ void CommandLineInterface::Clear() {
direct_dependencies_explicitly_set_ = false;
}
-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) {
+bool CommandLineInterface::MakeProtoProtoPathRelative(
+ DiskSourceTree* source_tree, string* proto) {
+ // If the input file path is not a physical file path, it must be a virtual
+ // path.
+ if (access(proto->c_str(), F_OK) < 0) {
+ string disk_file;
+ if (source_tree->VirtualFileToDiskFile(*proto, &disk_file)) {
+ return true;
+ } else {
+ std::cerr << *proto << ": " << strerror(ENOENT) << std::endl;
+ return false;
+ }
+ }
+ string virtual_file, shadowing_disk_file;
+ switch (source_tree->DiskFileToVirtualFile(
+ *proto, &virtual_file, &shadowing_disk_file)) {
+ case DiskSourceTree::SUCCESS:
+ *proto = virtual_file;
+ break;
+ case DiskSourceTree::SHADOWED:
+ std::cerr << *proto
+ << ": Input is shadowed in the --proto_path by \""
+ << shadowing_disk_file
+ << "\". Either use the latter file as your input or reorder "
+ "the --proto_path so that the former file's location "
+ "comes first." << std::endl;
+ return false;
+ case DiskSourceTree::CANNOT_OPEN:
+ std::cerr << *proto << ": " << strerror(errno) << std::endl;
+ return false;
+ 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;
+ if (source_tree->VirtualFileToDiskFile(*proto, &disk_file)) {
+ return true;
} else {
- std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
+ // 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
+ << *proto
+ << ": File does not reside within any path "
+ "specified using --proto_path (or -I). You must specify a "
+ "--proto_path which encompasses this file. Note that the "
+ "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;
return false;
}
}
- string virtual_file, shadowing_disk_file;
- switch (source_tree->DiskFileToVirtualFile(
- input_files_[i], &virtual_file, &shadowing_disk_file)) {
- case DiskSourceTree::SUCCESS:
- input_files_[i] = virtual_file;
- break;
- case DiskSourceTree::SHADOWED:
- std::cerr << input_files_[i]
- << ": Input is shadowed in the --proto_path by \""
- << shadowing_disk_file
- << "\". Either use the latter file as your input or reorder "
- "the --proto_path so that the former file's location "
- "comes first." << std::endl;
- return false;
- case DiskSourceTree::CANNOT_OPEN:
- std::cerr << input_files_[i] << ": " << strerror(errno) << std::endl;
- return false;
- 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 "
- "specified using --proto_path (or -I). You must specify a "
- "--proto_path which encompasses this file. Note that the "
- "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;
- return false;
- }
- }
+ }
+ return true;
+}
+
+bool CommandLineInterface::MakeInputsBeProtoPathRelative(
+ DiskSourceTree* source_tree) {
+ for (auto& input_file : input_files_) {
+ if (!MakeProtoProtoPathRelative(source_tree, &input_file)) {
+ 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
@@ -1534,7 +1549,7 @@ CommandLineInterface::InterpretArgument(const string& name,
std::cout << version_info_ << std::endl;
}
std::cout << "libprotoc "
- << protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION)
+ << protobuf::internal::VersionString(PROTOBUF_VERSION)
<< std::endl;
return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
@@ -1920,10 +1935,10 @@ bool CommandLineInterface::GeneratePluginOutput(
google::protobuf::compiler::Version* version =
request.mutable_compiler_version();
- version->set_major(GOOGLE_PROTOBUF_VERSION / 1000000);
- version->set_minor(GOOGLE_PROTOBUF_VERSION / 1000 % 1000);
- version->set_patch(GOOGLE_PROTOBUF_VERSION % 1000);
- version->set_suffix(GOOGLE_PROTOBUF_VERSION_SUFFIX);
+ version->set_major(PROTOBUF_VERSION / 1000000);
+ version->set_minor(PROTOBUF_VERSION / 1000 % 1000);
+ version->set_patch(PROTOBUF_VERSION % 1000);
+ version->set_suffix(PROTOBUF_VERSION_SUFFIX);
// Invoke the plugin.
Subprocess subprocess;
diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h
index 7d3037a9..cef29ffe 100644
--- a/src/google/protobuf/compiler/command_line_interface.h
+++ b/src/google/protobuf/compiler/command_line_interface.h
@@ -38,13 +38,16 @@
#ifndef GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
#define GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
-#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/hash.h>
-#include <string>
-#include <vector>
#include <map>
#include <set>
+#include <string>
+#include <unordered_map>
#include <utility>
+#include <vector>
+
+#include <google/protobuf/stubs/common.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -101,7 +104,7 @@ class DiskSourceTree; // importer.h
// 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 {
+class PROTOC_EXPORT CommandLineInterface {
public:
static const char* const kPathSeparator;
@@ -124,9 +127,9 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// protoc --foo_out=enable_bar:outdir
// The text before the colon is passed to CodeGenerator::Generate() as the
// "parameter".
- void RegisterGenerator(const string& flag_name,
+ void RegisterGenerator(const std::string& flag_name,
CodeGenerator* generator,
- const string& help_text);
+ const std::string& help_text);
// Register a code generator for a language.
// Besides flag_name you can specify another option_flag_name that could be
@@ -136,10 +139,10 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Then you could invoke the compiler with a command like:
// protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz
// This will pass "enable_bar,enable_baz" as the parameter to the generator.
- void RegisterGenerator(const string& flag_name,
- const string& option_flag_name,
+ void RegisterGenerator(const std::string& flag_name,
+ const std::string& option_flag_name,
CodeGenerator* generator,
- const string& help_text);
+ const std::string& help_text);
// Enables "plugins". In this mode, if a command-line flag ends with "_out"
// but does not match any registered generator, the compiler will attempt to
@@ -177,7 +180,7 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz
// This will pass "enable_bar,enable_baz" as the parameter to the plugin.
//
- void AllowPlugins(const string& exe_name_prefix);
+ void AllowPlugins(const std::string& exe_name_prefix);
// Run the Protocol Compiler with the given command-line parameters.
// Returns the error code which should be returned by main().
@@ -195,7 +198,7 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// 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
// after this text.
- void SetVersionInfo(const string& text) {
+ void SetVersionInfo(const std::string& text) {
version_info_ = text;
}
@@ -206,17 +209,21 @@ class LIBPROTOC_EXPORT CommandLineInterface {
class ErrorPrinter;
class GeneratorContextImpl;
class MemoryOutputStream;
- typedef hash_map<string, GeneratorContextImpl*> GeneratorContextMap;
+ typedef std::unordered_map<std::string, GeneratorContextImpl*> GeneratorContextMap;
// Clear state from previous Run().
void Clear();
+ // Remaps the proto file so that it is relative to one of the ddirectories
+ // in proto_path_. Returns false if an error occurred.
+ bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, std::string* proto);
+
// Remaps each file in input_files_ so that it is relative to one of the
- // directories in proto_path_. Returns false if an error occurred. This
- // is only used if inputs_are_proto_path_relative_ is false.
+ // directories in proto_path_. Returns false if an error occurred.
bool MakeInputsBeProtoPathRelative(
DiskSourceTree* source_tree);
+
// Return status for ParseArguments() and InterpretArgument().
enum ParseArgumentStatus {
PARSE_ARGUMENT_DONE_AND_CONTINUE,
@@ -229,7 +236,7 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// 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);
+ bool ExpandArgumentFile(const std::string& file, std::vector<std::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,
@@ -242,11 +249,11 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// name = "--cpp_out", value = "src/foo.pb2.cc"
// "foo.proto" ->
// name = "", value = "foo.proto"
- bool ParseArgument(const char* arg, string* name, string* value);
+ bool ParseArgument(const char* arg, std::string* name, std::string* value);
// Interprets arguments parsed with ParseArgument.
- ParseArgumentStatus InterpretArgument(const string& name,
- const string& value);
+ ParseArgumentStatus InterpretArgument(const std::string& name,
+ const std::string& value);
// Print the --help text to stderr.
void PrintHelpText();
@@ -268,8 +275,8 @@ class LIBPROTOC_EXPORT CommandLineInterface {
GeneratorContext* generator_context);
bool GeneratePluginOutput(
const std::vector<const FileDescriptor*>& parsed_files,
- const string& plugin_name, const string& parameter,
- GeneratorContext* generator_context, string* error);
+ const std::string& plugin_name, const std::string& parameter,
+ GeneratorContext* generator_context, std::string* error);
// Implements --encode and --decode.
bool EncodeOrDecode(const DescriptorPool* pool);
@@ -319,36 +326,36 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// -----------------------------------------------------------------
// The name of the executable as invoked (i.e. argv[0]).
- string executable_name_;
+ std::string executable_name_;
// Version info set with SetVersionInfo().
- string version_info_;
+ std::string version_info_;
// Registered generators.
struct GeneratorInfo {
- string flag_name;
- string option_flag_name;
+ std::string flag_name;
+ std::string option_flag_name;
CodeGenerator* generator;
- string help_text;
+ std::string help_text;
};
- typedef std::map<string, GeneratorInfo> GeneratorMap;
+ typedef std::map<std::string, GeneratorInfo> GeneratorMap;
GeneratorMap generators_by_flag_name_;
GeneratorMap generators_by_option_name_;
// A map from generator names to the parameters specified using the option
// flag. For example, if the user invokes the compiler with:
// protoc --foo_out=outputdir --foo_opt=enable_bar ...
// Then there will be an entry ("--foo_out", "enable_bar") in this map.
- std::map<string, string> generator_parameters_;
+ std::map<std::string, std::string> generator_parameters_;
// Similar to generator_parameters_, but stores the parameters for plugins.
- std::map<string, string> plugin_parameters_;
+ std::map<std::string, std::string> plugin_parameters_;
// See AllowPlugins(). If this is empty, plugins aren't allowed.
- string plugin_prefix_;
+ std::string plugin_prefix_;
// Maps specific plugin names to files. When executing a plugin, this map
// is searched first to find the plugin executable. If not found here, the
// PATH (or other OS-specific search strategy) is searched.
- std::map<string, string> plugins_;
+ std::map<std::string, std::string> plugins_;
// Stuff parsed from command line.
enum Mode {
@@ -374,44 +381,44 @@ class LIBPROTOC_EXPORT CommandLineInterface {
ErrorFormat error_format_;
- std::vector<std::pair<string, string> >
+ std::vector<std::pair<std::string, std::string> >
proto_path_; // Search path for proto files.
- std::vector<string> input_files_; // Names of the input proto files.
+ std::vector<std::string> input_files_; // Names of the input proto files.
// Names of proto files which are allowed to be imported. Used by build
// systems to enforce depend-on-what-you-import.
- std::set<string> direct_dependencies_;
+ std::set<std::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_;
+ std::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 {
- string name; // E.g. "--foo_out"
+ std::string name; // E.g. "--foo_out"
CodeGenerator* generator; // NULL for plugins
- string parameter;
- string output_location;
+ std::string parameter;
+ std::string output_location;
};
std::vector<OutputDirective> output_directives_;
// When using --encode or --decode, this names the type we are encoding or
// decoding. (Empty string indicates --decode_raw.)
- string codec_type_;
+ std::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_;
+ std::vector<std::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_out_name_;
+ std::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_;
+ std::string dependency_out_name_;
// True if --include_imports was given, meaning that we should
// write all transitive dependencies to the DescriptorSet. Otherwise, only
@@ -430,6 +437,8 @@ class LIBPROTOC_EXPORT CommandLineInterface {
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc
index 41eb244a..4e6f4af5 100644
--- a/src/google/protobuf/compiler/command_line_interface_unittest.cc
+++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -49,6 +49,7 @@
#include <google/protobuf/compiler/subprocess.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
@@ -2284,12 +2285,11 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
SplitStringUsing(command, " ", &args);
switch (GetParam()) {
case PROTO_PATH:
- args.push_back("--proto_path=" + TestSourceDir());
+ args.push_back("--proto_path=" + TestUtil::TestSourceDir());
break;
case DESCRIPTOR_SET_IN:
- args.push_back(StrCat(
- "--descriptor_set_in=",
- unittest_proto_descriptor_set_filename_));
+ args.push_back(StrCat("--descriptor_set_in=",
+ unittest_proto_descriptor_set_filename_));
break;
default:
ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam();
@@ -2369,30 +2369,34 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
};
TEST_P(EncodeDecodeTest, Encode) {
- RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/"
- "testdata/text_format_unittest_data_oneof_implemented.txt");
- EXPECT_TRUE(Run("google/protobuf/unittest.proto "
- "--encode=protobuf_unittest.TestAllTypes"));
- ExpectStdoutMatchesBinaryFile(TestSourceDir() +
- "/google/protobuf/testdata/golden_message_oneof_implemented");
+ RedirectStdinFromFile(TestUtil::GetTestDataPath(
+ "net/proto2/internal/"
+ "testdata/text_format_unittest_data_oneof_implemented.txt"));
+ EXPECT_TRUE(
+ Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") +
+ " --encode=protobuf_unittest.TestAllTypes"));
+ ExpectStdoutMatchesBinaryFile(TestUtil::GetTestDataPath(
+ "net/proto2/internal/testdata/golden_message_oneof_implemented"));
ExpectStderrMatchesText("");
}
TEST_P(EncodeDecodeTest, Decode) {
- RedirectStdinFromFile(TestSourceDir() +
- "/google/protobuf/testdata/golden_message_oneof_implemented");
- EXPECT_TRUE(Run("google/protobuf/unittest.proto "
- "--decode=protobuf_unittest.TestAllTypes"));
- ExpectStdoutMatchesTextFile(TestSourceDir() +
- "/google/protobuf/"
- "testdata/text_format_unittest_data_oneof_implemented.txt");
+ RedirectStdinFromFile(TestUtil::GetTestDataPath(
+ "net/proto2/internal/testdata/golden_message_oneof_implemented"));
+ EXPECT_TRUE(
+ Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") +
+ " --decode=protobuf_unittest.TestAllTypes"));
+ ExpectStdoutMatchesTextFile(TestUtil::GetTestDataPath(
+ "net/proto2/internal/"
+ "testdata/text_format_unittest_data_oneof_implemented.txt"));
ExpectStderrMatchesText("");
}
TEST_P(EncodeDecodeTest, Partial) {
RedirectStdinFromText("");
- EXPECT_TRUE(Run("google/protobuf/unittest.proto "
- "--encode=protobuf_unittest.TestRequired"));
+ EXPECT_TRUE(
+ Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") +
+ " --encode=protobuf_unittest.TestRequired"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText(
"warning: Input message is missing required fields: a, b, c\n");
@@ -2413,18 +2417,20 @@ TEST_P(EncodeDecodeTest, DecodeRaw) {
}
TEST_P(EncodeDecodeTest, UnknownType) {
- EXPECT_FALSE(Run("google/protobuf/unittest.proto "
- "--encode=NoSuchType"));
+ EXPECT_FALSE(
+ Run(TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto") +
+ " --encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText("Type not defined: NoSuchType\n");
}
TEST_P(EncodeDecodeTest, ProtoParseError) {
- EXPECT_FALSE(Run("google/protobuf/no_such_file.proto "
- "--encode=NoSuchType"));
+ EXPECT_FALSE(
+ Run("net/proto2/internal/no_such_file.proto "
+ "--encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText(
- "google/protobuf/no_such_file.proto: No such file or directory\n");
+ "net/proto2/internal/no_such_file.proto: No such file or directory\n");
}
INSTANTIATE_TEST_CASE_P(FileDescriptorSetSource,
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
index 4e150fe3..a19ad595 100644
--- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
@@ -32,7 +32,7 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
-// This test insures that google/protobuf/descriptor.pb.{h,cc} match exactly
+// This test insures that net/proto2/proto/descriptor.pb.{h,cc} match exactly
// what would be generated by the protocol compiler. These files are not
// generated automatically at build time because they are compiled into the
// protocol compiler itself. So, if they were auto-generated, you'd have a
@@ -47,8 +47,10 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/importer.h>
+#include <google/protobuf/test_util2.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/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
@@ -83,9 +85,7 @@ class MockErrorCollector : public MultiFileErrorCollector {
class MockGeneratorContext : public GeneratorContext {
public:
MockGeneratorContext() {}
- ~MockGeneratorContext() {
- STLDeleteValues(&files_);
- }
+ ~MockGeneratorContext() { STLDeleteValues(&files_); }
void ExpectFileMatches(const string& virtual_filename,
const string& physical_filename) {
@@ -95,9 +95,18 @@ class MockGeneratorContext : public GeneratorContext {
string actual_contents;
GOOGLE_CHECK_OK(
- File::GetContents(TestSourceDir() + "/" + physical_filename,
- &actual_contents, true));
- EXPECT_TRUE(actual_contents == *expected_contents)
+ File::GetContents(TestUtil::TestSourceDir() + "/" + physical_filename,
+ &actual_contents, true))
+ << physical_filename;
+ CleanStringLineEndings(&actual_contents, false);
+
+#ifdef WRITE_FILES // Define to debug mismatched files.
+ GOOGLE_CHECK_OK(
+ File::SetContents("/tmp/1.cc", *expected_contents, true));
+ GOOGLE_CHECK_OK(File::SetContents("/tmp/2.cc", actual_contents, true));
+#endif
+
+ EXPECT_EQ(*expected_contents, actual_contents)
<< physical_filename
<< " needs to be regenerated. Please run "
"generate_descriptor_proto.sh. "
@@ -118,8 +127,8 @@ class MockGeneratorContext : public GeneratorContext {
std::map<string, string*> files_;
};
-const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT";
-const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT";
+const char kDescriptorParameter[] = "dllexport_decl=PROTOBUF_EXPORT";
+const char kPluginParameter[] = "dllexport_decl=PROTOC_EXPORT";
const char kNormalParameter[] = "";
const char* test_protos[][2] = {
@@ -136,11 +145,11 @@ TEST(BootstrapTest, GeneratedFilesMatch) {
"net/proto2/z_generated_example/test_messages_proto2";
rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] =
"net/proto2/z_generated_example/test_messages_proto3";
- rpath_map["google/protobuf/proto2_weak"] =
+ rpath_map["net/proto2/internal/proto2_weak"] =
"net/proto2/z_generated_example/proto2_weak";
DiskSourceTree source_tree;
- source_tree.MapPath("", TestSourceDir());
+ source_tree.MapPath("", TestUtil::TestSourceDir());
for (auto file_parameter : test_protos) {
MockErrorCollector error_collector;
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc
index 0d6a9e24..39fe9e68 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc
@@ -46,7 +46,7 @@ namespace cpp {
namespace {
// The GOOGLE_ARRAYSIZE constant is the max enum value plus 1. If the max enum value
-// is ::google::protobuf::kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the
+// is kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the
// generation of the GOOGLE_ARRAYSIZE constant.
bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) {
int32 max_value = descriptor->value(0)->number();
@@ -55,61 +55,53 @@ bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) {
max_value = descriptor->value(i)->number();
}
}
- return max_value != ::google::protobuf::kint32max;
+ return max_value != kint32max;
}
} // namespace
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor,
+ const std::map<string, string>& vars,
const Options& options)
- : descriptor_(descriptor),
- classname_(ClassName(descriptor, false)),
- options_(options),
- generate_array_size_(ShouldGenerateArraySize(descriptor)) {
+ : descriptor_(descriptor),
+ classname_(ClassName(descriptor, false)),
+ options_(options),
+ generate_array_size_(ShouldGenerateArraySize(descriptor)),
+ variables_(vars) {
+ variables_["classname"] = classname_;
+ variables_["classtype"] = QualifiedClassName(descriptor_);
+ variables_["short_name"] = descriptor_->name();
+ variables_["enumbase"] = options_.proto_h ? " : int" : "";
+ variables_["nested_name"] = descriptor_->name();
+ variables_["constexpr"] = options_.proto_h ? "constexpr" : "";
+ variables_["prefix"] =
+ (descriptor_->containing_type() == NULL) ? "" : classname_ + "_";
}
EnumGenerator::~EnumGenerator() {}
-void EnumGenerator::FillForwardDeclaration(
- std::map<string, const EnumDescriptor*>* enum_names) {
- if (!options_.proto_h) {
- return;
- }
- (*enum_names)[classname_] = descriptor_;
-}
-
void EnumGenerator::GenerateDefinition(io::Printer* printer) {
- std::map<string, string> vars;
- vars["classname"] = classname_;
- vars["short_name"] = descriptor_->name();
- 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();
+ Formatter format(printer, variables_);
+ format("enum ${1$$classname$$}$$enumbase$ {\n", descriptor_);
+ format.Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
const EnumValueDescriptor* max_value = descriptor_->value(0);
for (int i = 0; i < descriptor_->value_count(); i++) {
- vars["name"] = EnumValueName(descriptor_->value(i));
+ auto format_value = format;
+ format_value.Set("name", EnumValueName(descriptor_->value(i)));
// In C++, an value of -2147483648 gets interpreted as the negative of
// 2147483648, and since 2147483648 can't fit in an integer, this produces a
// compiler warning. This works around that issue.
- vars["number"] = Int32ToString(descriptor_->value(i)->number());
- vars["prefix"] = (descriptor_->containing_type() == NULL) ?
- "" : classname_ + "_";
- vars["deprecation"] = descriptor_->value(i)->options().deprecated() ?
- " PROTOBUF_DEPRECATED" : "";
+ format_value.Set("number", Int32ToString(descriptor_->value(i)->number()));
+ format_value.Set(
+ "deprecation",
+ DeprecatedAttribute(options_,
+ descriptor_->value(i)->options().deprecated()));
- if (i > 0) printer->Print(",\n");
- printer->Print(vars, "${$$prefix$$name$$}$$deprecation$ = $number$");
- printer->Annotate("{", "}", descriptor_->value(i));
+ if (i > 0) format_value(",\n");
+ format_value("${1$$prefix$$name$$}$ $deprecation$= $number$",
+ descriptor_->value(i));
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
@@ -122,153 +114,163 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
// For new enum semantics: generate min and max sentinel values equal to
// INT32_MIN and INT32_MAX
- if (descriptor_->value_count() > 0) printer->Print(",\n");
- printer->Print(vars,
- "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,\n"
- "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max");
+ if (descriptor_->value_count() > 0) format(",\n");
+ format(
+ "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = "
+ "std::numeric_limits<$int32$>::min(),\n"
+ "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = "
+ "std::numeric_limits<$int32$>::max()");
}
- printer->Outdent();
- printer->Print("\n};\n");
+ format.Outdent();
+ format("\n};\n");
- vars["min_name"] = EnumValueName(min_value);
- vars["max_name"] = EnumValueName(max_value);
-
- if (options_.dllexport_decl.empty()) {
- vars["dllexport"] = "";
- } else {
- vars["dllexport"] = options_.dllexport_decl + " ";
- }
-
- printer->Print(vars,
- "$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_);
+ format(
+ "$dllexport_decl $bool $classname$_IsValid(int value);\n"
+ "const $classname$ ${1$$prefix$$short_name$_MIN$}$ = "
+ "$prefix$$2$;\n"
+ "const $classname$ ${1$$prefix$$short_name$_MAX$}$ = "
+ "$prefix$$3$;\n",
+ descriptor_, EnumValueName(min_value), EnumValueName(max_value));
if (generate_array_size_) {
- printer->Print(vars,
- "const int ${$$prefix$$short_name$_ARRAYSIZE$}$ = "
- "$prefix$$short_name$_MAX + 1;\n\n");
- printer->Annotate("{", "}", descriptor_);
+ format(
+ "const int ${1$$prefix$$short_name$_ARRAYSIZE$}$ = "
+ "$prefix$$short_name$_MAX + 1;\n\n",
+ descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(vars,
- "$dllexport$const ::google::protobuf::EnumDescriptor* $classname$_descriptor();\n");
+ format(
+ "$dllexport_decl $const ::$proto_ns$::EnumDescriptor* "
+ "$classname$_descriptor();\n");
// The _Name and _Parse methods
- printer->Print(
- vars,
- "inline const ::std::string& $classname$_Name($classname$ value) {\n"
- " return ::google::protobuf::internal::NameOfEnum(\n"
- " $classname$_descriptor(), value);\n"
+ if (options_.opensource_runtime) {
+ // TODO(haberman): consider removing this in favor of the stricter
+ // version below. Would this break our compatibility guarantees?
+ format(
+ "inline const $string$& $classname$_Name($classname$ value) {\n"
+ " return ::$proto_ns$::internal::NameOfEnum(\n"
+ " $classname$_descriptor(), value);\n"
+ "}\n");
+ } else {
+ // Support a stricter, type-checked enum-to-string method that
+ // statically checks whether the parameter is the exact enum type or is
+ // an integral type.
+ format(
+ "template<typename T>\n"
+ "inline const $string$& $classname$_Name(T enum_t_value) {\n"
+ " static_assert(::std::is_same<T, $classname$>::value ||\n"
+ " ::std::is_integral<T>::value,\n"
+ " \"Incorrect type passed to function $classname$_Name.\");\n"
+ " return ::$proto_ns$::internal::NameOfEnum(\n"
+ " $classname$_descriptor(), enum_t_value);\n"
+ "}\n");
+ }
+ format(
+ "inline bool $classname$_Parse(\n"
+ " const $string$& name, $classname$* value) {\n"
+ " return ::$proto_ns$::internal::ParseNamedEnum<$classname$>(\n"
+ " $classname$_descriptor(), name, value);\n"
"}\n");
- printer->Print(vars,
- "inline bool $classname$_Parse(\n"
- " const ::std::string& name, $classname$* value) {\n"
- " return ::google::protobuf::internal::ParseNamedEnum<$classname$>(\n"
- " $classname$_descriptor(), name, value);\n"
- "}\n");
}
}
-void EnumGenerator::
-GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
- printer->Print(
- "template <> struct is_proto_enum< $classname$> : ::std::true_type "
- "{};\n",
- "classname", ClassName(descriptor_, true));
+void EnumGenerator::GenerateGetEnumDescriptorSpecializations(
+ io::Printer* printer) {
+ Formatter format(printer, variables_);
+ format(
+ "template <> struct is_proto_enum< $classtype$> : ::std::true_type "
+ "{};\n");
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(
- "template <>\n"
- "inline const EnumDescriptor* GetEnumDescriptor< $classname$>() {\n"
- " return $classname$_descriptor();\n"
- "}\n",
- "classname", ClassName(descriptor_, true));
+ format(
+ "template <>\n"
+ "inline const EnumDescriptor* GetEnumDescriptor< $classtype$>() {\n"
+ " return $classtype$_descriptor();\n"
+ "}\n");
}
}
-void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
- std::map<string, string> vars;
- vars["nested_name"] = descriptor_->name();
- vars["classname"] = classname_;
- vars["constexpr"] = options_.proto_h ? "constexpr " : "";
- vars["{"] = "";
- vars["}"] = "";
- printer->Print(vars, "typedef $classname$ $nested_name$;\n");
+void EnumGenerator::GenerateSymbolImports(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("typedef $classname$ $nested_name$;\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
- vars["tag"] = EnumValueName(descriptor_->value(j));
- vars["deprecated_attr"] = descriptor_->value(j)->options().deprecated() ?
- "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
- printer->Print(vars,
- "$deprecated_attr$static $constexpr$const $nested_name$ ${$$tag$$}$ =\n"
- " $classname$_$tag$;\n");
- printer->Annotate("{", "}", descriptor_->value(j));
+ string deprecated_attr = DeprecatedAttribute(
+ options_, descriptor_->value(j)->options().deprecated());
+ format(
+ "$1$static $constexpr $const $nested_name$ ${2$$3$$}$ =\n"
+ " $classname$_$3$;\n",
+ deprecated_attr, descriptor_->value(j),
+ EnumValueName(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");
- printer->Annotate("{", "}", descriptor_);
- printer->Print(vars,
- "static const $nested_name$ ${$$nested_name$_MAX$}$ =\n"
- " $classname$_$nested_name$_MAX;\n");
- printer->Annotate("{", "}", descriptor_);
+ format(
+ "static inline bool $nested_name$_IsValid(int value) {\n"
+ " return $classname$_IsValid(value);\n"
+ "}\n"
+ "static const $nested_name$ ${1$$nested_name$_MIN$}$ =\n"
+ " $classname$_$nested_name$_MIN;\n"
+ "static const $nested_name$ ${1$$nested_name$_MAX$}$ =\n"
+ " $classname$_$nested_name$_MAX;\n",
+ descriptor_);
if (generate_array_size_) {
- printer->Print(vars,
- "static const int ${$$nested_name$_ARRAYSIZE$}$ =\n"
- " $classname$_$nested_name$_ARRAYSIZE;\n");
- printer->Annotate("{", "}", descriptor_);
+ format(
+ "static const int ${1$$nested_name$_ARRAYSIZE$}$ =\n"
+ " $classname$_$nested_name$_ARRAYSIZE;\n",
+ descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(vars,
- "static inline const ::google::protobuf::EnumDescriptor*\n"
- "$nested_name$_descriptor() {\n"
- " return $classname$_descriptor();\n"
- "}\n");
- printer->Print(vars,
- "static inline const ::std::string& "
- "$nested_name$_Name($nested_name$ value) {"
- "\n"
- " return $classname$_Name(value);\n"
- "}\n");
- printer->Print(vars,
- "static inline bool $nested_name$_Parse(const ::std::string& name,\n"
- " $nested_name$* value) {\n"
- " return $classname$_Parse(name, value);\n"
- "}\n");
+ format(
+ "static inline const ::$proto_ns$::EnumDescriptor*\n"
+ "$nested_name$_descriptor() {\n"
+ " return $classname$_descriptor();\n"
+ "}\n");
+ if (options_.opensource_runtime) {
+ // TODO(haberman): consider removing this in favor of the stricter
+ // version below. Would this break our compatibility guarantees?
+ format(
+ "static inline const $string$& "
+ "$nested_name$_Name($nested_name$ value) {"
+ "\n"
+ " return $classname$_Name(value);\n"
+ "}\n");
+ } else {
+ // Support a stricter, type-checked enum-to-string method that
+ // statically checks whether the parameter is the exact enum type or is
+ // an integral type.
+ format(
+ "template<typename T>\n"
+ "static inline const $string$& $nested_name$_Name(T enum_t_value) {\n"
+ " static_assert(::std::is_same<T, $nested_name$>::value ||\n"
+ " ::std::is_integral<T>::value,\n"
+ " \"Incorrect type passed to function $nested_name$_Name.\");\n"
+ " return $classname$_Name(enum_t_value);\n"
+ "}\n");
+ }
+ format(
+ "static inline bool $nested_name$_Parse(const $string$& name,\n"
+ " $nested_name$* value) {\n"
+ " return $classname$_Parse(name, value);\n"
+ "}\n");
}
}
void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
- std::map<string, string> vars;
- vars["classname"] = classname_;
- vars["index_in_metadata"] = SimpleItoa(idx);
- vars["constexpr"] = options_.proto_h ? "constexpr " : "";
- vars["file_namespace"] = FileLevelNamespace(descriptor_->file()->name());
-
+ Formatter format(printer, variables_);
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(
- vars,
- "const ::google::protobuf::EnumDescriptor* $classname$_descriptor() {\n"
- " $file_namespace$::protobuf_AssignDescriptorsOnce();\n"
- " return "
- "$file_namespace$::file_level_enum_descriptors[$index_in_metadata$];\n"
- "}\n");
+ format(
+ "const ::$proto_ns$::EnumDescriptor* $classname$_descriptor() {\n"
+ " ::$proto_ns$::internal::AssignDescriptors(&$assign_desc_table$);\n"
+ " return $file_level_enum_descriptors$[$1$];\n"
+ "}\n",
+ idx);
}
- printer->Print(vars,
- "bool $classname$_IsValid(int value) {\n"
- " switch (value) {\n");
+ format(
+ "bool $classname$_IsValid(int value) {\n"
+ " switch (value) {\n");
// Multiple values may have the same number. Make sure we only cover
// each number once by first constructing a set containing all valid
@@ -280,44 +282,40 @@ void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
numbers.insert(value->number());
}
- for (std::set<int>::iterator iter = numbers.begin();
- iter != numbers.end(); ++iter) {
- printer->Print(
- " case $number$:\n",
- "number", Int32ToString(*iter));
+ for (std::set<int>::iterator iter = numbers.begin(); iter != numbers.end();
+ ++iter) {
+ format(" case $1$:\n", Int32ToString(*iter));
}
- printer->Print(vars,
- " return true;\n"
- " default:\n"
- " return false;\n"
- " }\n"
- "}\n"
- "\n");
+ format(
+ " return true;\n"
+ " default:\n"
+ " return false;\n"
+ " }\n"
+ "}\n"
+ "\n");
if (descriptor_->containing_type() != NULL) {
+ string parent = ClassName(descriptor_->containing_type(), false);
// We need to "define" the static constants which were declared in the
// header, to give the linker a place to put them. Or at least the C++
// standard says we have to. MSVC actually insists that we do _not_ define
// them again in the .cc file, prior to VC++ 2015.
- printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
+ format("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
- vars["parent"] = ClassName(descriptor_->containing_type(), false);
- vars["nested_name"] = descriptor_->name();
for (int i = 0; i < descriptor_->value_count(); i++) {
- vars["value"] = EnumValueName(descriptor_->value(i));
- printer->Print(vars,
- "$constexpr$const $classname$ $parent$::$value$;\n");
+ format("$constexpr $const $classname$ $1$::$2$;\n", parent,
+ EnumValueName(descriptor_->value(i)));
}
- printer->Print(vars,
- "const $classname$ $parent$::$nested_name$_MIN;\n"
- "const $classname$ $parent$::$nested_name$_MAX;\n");
+ format(
+ "const $classname$ $1$::$nested_name$_MIN;\n"
+ "const $classname$ $1$::$nested_name$_MAX;\n",
+ parent);
if (generate_array_size_) {
- printer->Print(vars,
- "const int $parent$::$nested_name$_ARRAYSIZE;\n");
+ format("const int $1$::$nested_name$_ARRAYSIZE;\n", parent);
}
- printer->Print("#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n");
+ format("#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n");
}
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.h b/src/google/protobuf/compiler/cpp/cpp_enum.h
index 0d2488a9..6b9700ae 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.h
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.h
@@ -46,8 +46,10 @@ namespace protobuf {
namespace io {
class Printer; // printer.h
}
-}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
@@ -55,20 +57,10 @@ namespace cpp {
class EnumGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
- EnumGenerator(const EnumDescriptor* descriptor, const Options& options);
+ EnumGenerator(const EnumDescriptor* descriptor,
+ const std::map<std::string, std::string>& vars, const Options& options);
~EnumGenerator();
- // Header stuff.
-
- // Fills the name to use when declaring the enum. This is for use when
- // generating other .proto.h files. This code should be placed within the
- // enum's package namespace, but NOT within any class, even for nested
- // enums. A given key in enum_names will map from an enum class name to the
- // EnumDescriptor that was responsible for its inclusion in the map. This can
- // be used to associate the descriptor with the code generated for it.
- void FillForwardDeclaration(
- std::map<string, const EnumDescriptor*>* enum_names);
-
// Generate header code defining the enum. This code should be placed
// within the enum's package namespace, but NOT within any class, even for
// nested enums.
@@ -82,7 +74,7 @@ class EnumGenerator {
// symbols (e.g. the enum type name, all its values, etc.) into the class's
// namespace. This should be placed inside the class definition in the
// header.
- void GenerateSymbolImports(io::Printer* printer);
+ void GenerateSymbolImports(io::Printer* printer) const;
// Source file stuff.
@@ -93,11 +85,13 @@ class EnumGenerator {
private:
const EnumDescriptor* descriptor_;
- const string classname_;
+ const std::string classname_;
const Options& options_;
// whether to generate the *_ARRAYSIZE constant.
const bool generate_array_size_;
+ std::map<std::string, std::string> variables_;
+
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
@@ -105,6 +99,6 @@ class EnumGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
index 50c7b5f3..a406f2ee 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
@@ -61,457 +61,452 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetEnumVariables(descriptor, &variables_, options);
}
EnumFieldGenerator::~EnumFieldGenerator() {}
-void EnumFieldGenerator::
-GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_, "int $name$_;\n");
+void EnumFieldGenerator::GeneratePrivateMembers(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("int $name$_;\n");
}
-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$void ${$set_$name$$}$($type$ value);\n");
- printer->Annotate("{", "}", descriptor_);
+void EnumFieldGenerator::GenerateAccessorDeclarations(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$$type$ ${1$$name$$}$() const;\n"
+ "$deprecated_attr$void ${1$set_$name$$}$($type$ value);\n",
+ descriptor_);
}
-void EnumFieldGenerator::
-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");
+void EnumFieldGenerator::GenerateInlineAccessorDefinitions(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "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");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- " assert($type$_IsValid(value));\n");
+ format(" assert($type$_IsValid(value));\n");
}
- printer->Print(variables_,
- " $set_hasbit$\n"
- " $name$_ = value;\n"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- "}\n");
+ format(
+ " $set_hasbit$\n"
+ " $name$_ = value;\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n");
}
-void EnumFieldGenerator::
-GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = $default$;\n");
+void EnumFieldGenerator::GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_ = $default$;\n");
}
-void EnumFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "set_$name$(from.$name$());\n");
+void EnumFieldGenerator::GenerateMergingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("set_$name$(from.$name$());\n");
}
-void EnumFieldGenerator::
-GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "swap($name$_, other->$name$_);\n");
+void EnumFieldGenerator::GenerateSwappingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("swap($name$_, other->$name$_);\n");
}
-void EnumFieldGenerator::
-GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = $default$;\n");
+void EnumFieldGenerator::GenerateConstructorCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_ = $default$;\n");
}
-void EnumFieldGenerator::
-GenerateCopyConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = from.$name$_;\n");
+void EnumFieldGenerator::GenerateCopyConstructorCode(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_ = from.$name$_;\n");
}
-void EnumFieldGenerator::
-GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "int value;\n"
- "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
- " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
- " input, &value)));\n");
+void EnumFieldGenerator::GenerateMergeFromCodedStream(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "int value = 0;\n"
+ "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
+ " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
+ " input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- "set_$name$(static_cast< $type$ >(value));\n");
+ format("set_$name$(static_cast< $type$ >(value));\n");
} else {
- printer->Print(variables_,
- "if ($type$_IsValid(value)) {\n"
- " set_$name$(static_cast< $type$ >(value));\n");
+ format(
+ "if ($type$_IsValid(value)) {\n"
+ " set_$name$(static_cast< $type$ >(value));\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "} else {\n"
- " mutable_unknown_fields()->AddVarint(\n"
- " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
+ format(
+ "} else {\n"
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast<$uint64$>(value));\n");
} else {
- printer->Print(
- "} else {\n"
- " unknown_fields_stream.WriteVarint32($tag$u);\n"
- " unknown_fields_stream.WriteVarint32(\n"
- " static_cast< ::google::protobuf::uint32>(value));\n",
- "tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_)));
+ format(
+ "} else {\n"
+ " unknown_fields_stream.WriteVarint32($1$u);\n"
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast<$uint32$>(value));\n",
+ internal::WireFormat::MakeTag(descriptor_));
}
- printer->Print(variables_,
- "}\n");
+ format("}\n");
}
}
-void EnumFieldGenerator::
-GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::internal::WireFormatLite::WriteEnum(\n"
- " $number$, this->$name$(), output);\n");
+void EnumFieldGenerator::GenerateSerializeWithCachedSizes(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "::$proto_ns$::internal::WireFormatLite::WriteEnum(\n"
+ " $number$, this->$name$(), output);\n");
}
-void EnumFieldGenerator::
-GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- printer->Print(variables_,
- "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
- " $number$, this->$name$(), target);\n");
+void EnumFieldGenerator::GenerateSerializeWithCachedSizesToArray(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "target = ::$proto_ns$::internal::WireFormatLite::WriteEnumToArray(\n"
+ " $number$, this->$name$(), target);\n");
}
-void EnumFieldGenerator::
-GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::EnumSize(this->$name$());\n");
+void EnumFieldGenerator::GenerateByteSize(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::EnumSize(this->$name$());\n");
}
// ===================================================================
-EnumOneofFieldGenerator::
-EnumOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options)
- : EnumFieldGenerator(descriptor, options) {
+EnumOneofFieldGenerator::EnumOneofFieldGenerator(
+ const FieldDescriptor* descriptor, const Options& options)
+ : EnumFieldGenerator(descriptor, options) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {}
-void EnumOneofFieldGenerator::
-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$ >($field_member$);\n"
- " }\n"
- " return static_cast< $type$ >($default$);\n"
- "}\n"
- "inline void $classname$::set_$name$($type$ value) {\n");
+void EnumOneofFieldGenerator::GenerateInlineAccessorDefinitions(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "inline $type$ $classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " if (has_$name$()) {\n"
+ " return static_cast< $type$ >($field_member$);\n"
+ " }\n"
+ " return static_cast< $type$ >($default$);\n"
+ "}\n"
+ "inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- " assert($type$_IsValid(value));\n");
+ format(" assert($type$_IsValid(value));\n");
}
- printer->Print(variables_,
- " if (!has_$name$()) {\n"
- " clear_$oneof_name$();\n"
- " set_has_$name$();\n"
- " }\n"
- " $field_member$ = value;\n"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- "}\n");
+ format(
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " }\n"
+ " $field_member$ = value;\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n");
}
-void EnumOneofFieldGenerator::
-GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$field_member$ = $default$;\n");
+void EnumOneofFieldGenerator::GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$field_member$ = $default$;\n");
}
-void EnumOneofFieldGenerator::
-GenerateSwappingCode(io::Printer* printer) const {
+void EnumOneofFieldGenerator::GenerateSwappingCode(io::Printer* printer) const {
// Don't print any swapping code. Swapping the union will swap this field.
}
-void EnumOneofFieldGenerator::
-GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
+void EnumOneofFieldGenerator::GenerateConstructorCode(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
// ===================================================================
RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetEnumVariables(descriptor, &variables_, options);
}
RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {}
-void RepeatedEnumFieldGenerator::
-GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::RepeatedField<int> $name$_;\n");
+void RepeatedEnumFieldGenerator::GeneratePrivateMembers(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("::$proto_ns$::RepeatedField<int> $name$_;\n");
if (descriptor_->is_packed() &&
HasGeneratedMethods(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "mutable int _$name$_cached_byte_size_;\n");
+ format("mutable std::atomic<int> _$name$_cached_byte_size_;\n");
}
}
-void RepeatedEnumFieldGenerator::
-GenerateAccessorDeclarations(io::Printer* printer) const {
- printer->Print(variables_,
- "$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$::google::protobuf::RepeatedField<int>* "
- "${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
-}
-
-void RepeatedEnumFieldGenerator::
-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");
+void RepeatedEnumFieldGenerator::GenerateAccessorDeclarations(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$$type$ ${1$$name$$}$(int index) const;\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, $type$ value);\n"
+ "$deprecated_attr$void ${1$add_$name$$}$($type$ value);\n"
+ "$deprecated_attr$const ::$proto_ns$::RepeatedField<int>& "
+ "${1$$name$$}$() const;\n"
+ "$deprecated_attr$::$proto_ns$::RepeatedField<int>* "
+ "${1$mutable_$name$$}$();\n",
+ descriptor_);
+}
+
+void RepeatedEnumFieldGenerator::GenerateInlineAccessorDefinitions(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "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");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- " assert($type$_IsValid(value));\n");
+ format(" assert($type$_IsValid(value));\n");
}
- 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");
+ format(
+ " $name$_.Set(index, value);\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n"
+ "inline void $classname$::add_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- " assert($type$_IsValid(value));\n");
+ format(" assert($type$_IsValid(value));\n");
}
- printer->Print(variables_,
- " $name$_.Add(value);\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\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"
- "$classname$::mutable_$name$() {\n"
- " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- " return &$name$_;\n"
- "}\n");
+ format(
+ " $name$_.Add(value);\n"
+ " // @@protoc_insertion_point(field_add:$full_name$)\n"
+ "}\n"
+ "inline const ::$proto_ns$::RepeatedField<int>&\n"
+ "$classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_list:$full_name$)\n"
+ " return $name$_;\n"
+ "}\n"
+ "inline ::$proto_ns$::RepeatedField<int>*\n"
+ "$classname$::mutable_$name$() {\n"
+ " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
+ " return &$name$_;\n"
+ "}\n");
}
-void RepeatedEnumFieldGenerator::
-GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Clear();\n");
+void RepeatedEnumFieldGenerator::GenerateClearingCode(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_.Clear();\n");
}
-void RepeatedEnumFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+void RepeatedEnumFieldGenerator::GenerateMergingCode(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_.MergeFrom(from.$name$_);\n");
}
-void RepeatedEnumFieldGenerator::
-GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
+void RepeatedEnumFieldGenerator::GenerateSwappingCode(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format("$name$_.InternalSwap(&other->$name$_);\n");
}
-void RepeatedEnumFieldGenerator::
-GenerateConstructorCode(io::Printer* printer) const {
+void RepeatedEnumFieldGenerator::GenerateConstructorCode(
+ io::Printer* printer) const {
// Not needed for repeated fields.
}
-void RepeatedEnumFieldGenerator::
-GenerateMergeFromCodedStream(io::Printer* printer) const {
+void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStream(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
// Don't use ReadRepeatedPrimitive here so that the enum can be validated.
- printer->Print(variables_,
- "int value;\n"
- "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
- " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
- " input, &value)));\n");
+ format(
+ "int value = 0;\n"
+ "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
+ " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
+ " input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- "add_$name$(static_cast< $type$ >(value));\n");
+ format("add_$name$(static_cast< $type$ >(value));\n");
} else {
- printer->Print(variables_,
- "if ($type$_IsValid(value)) {\n"
- " add_$name$(static_cast< $type$ >(value));\n");
+ format(
+ "if ($type$_IsValid(value)) {\n"
+ " add_$name$(static_cast< $type$ >(value));\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "} else {\n"
- " mutable_unknown_fields()->AddVarint(\n"
- " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
+ format(
+ "} else {\n"
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast<$uint64$>(value));\n");
} else {
- printer->Print(
- "} else {\n"
- " unknown_fields_stream.WriteVarint32(tag);\n"
- " unknown_fields_stream.WriteVarint32(\n"
- " static_cast< ::google::protobuf::uint32>(value));\n");
+ format(
+ "} else {\n"
+ " unknown_fields_stream.WriteVarint32(tag);\n"
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast<$uint32$>(value));\n");
}
- printer->Print("}\n");
+ format("}\n");
}
}
-void RepeatedEnumFieldGenerator::
-GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
+void RepeatedEnumFieldGenerator::GenerateMergeFromCodedStreamWithPacking(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (!descriptor_->is_packed()) {
- // This path is rarely executed, so we use a non-inlined implementation.
+ // This path is rarely executed, so we use a non-inlined implementation.
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- "DO_((::google::protobuf::internal::"
- "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n"
- " input,\n"
- " $number$,\n"
- " NULL,\n"
- " NULL,\n"
- " this->mutable_$name$())));\n");
+ format(
+ "DO_((::$proto_ns$::internal::"
+ "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n"
+ " input,\n"
+ " $number$,\n"
+ " NULL,\n"
+ " NULL,\n"
+ " this->mutable_$name$())));\n");
} else if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns(\n"
- " input,\n"
- " $number$,\n"
- " $type$_IsValid,\n"
- " mutable_unknown_fields(),\n"
- " this->mutable_$name$())));\n");
+ format(
+ "DO_((::$proto_ns$::internal::WireFormat::"
+ "ReadPackedEnumPreserveUnknowns(\n"
+ " input,\n"
+ " $number$,\n"
+ " $type$_IsValid,\n"
+ " mutable_unknown_fields(),\n"
+ " this->mutable_$name$())));\n");
} else {
- printer->Print(variables_,
- "DO_((::google::protobuf::internal::"
- "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n"
- " input,\n"
- " $number$,\n"
- " $type$_IsValid,\n"
- " &unknown_fields_stream,\n"
- " this->mutable_$name$())));\n");
+ format(
+ "DO_((::$proto_ns$::internal::"
+ "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n"
+ " input,\n"
+ " $number$,\n"
+ " $type$_IsValid,\n"
+ " &unknown_fields_stream,\n"
+ " this->mutable_$name$())));\n");
}
} else {
- printer->Print(variables_,
- "::google::protobuf::uint32 length;\n"
- "DO_(input->ReadVarint32(&length));\n"
- "::google::protobuf::io::CodedInputStream::Limit limit = "
- "input->PushLimit(static_cast<int>(length));\n"
- "while (input->BytesUntilLimit() > 0) {\n"
- " int value;\n"
- " DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
- " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n"
- " input, &value)));\n");
+ format(
+ "$uint32$ length;\n"
+ "DO_(input->ReadVarint32(&length));\n"
+ "::$proto_ns$::io::CodedInputStream::Limit limit = "
+ "input->PushLimit(static_cast<int>(length));\n"
+ "while (input->BytesUntilLimit() > 0) {\n"
+ " int value = 0;\n"
+ " DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
+ " int, ::$proto_ns$::internal::WireFormatLite::TYPE_ENUM>(\n"
+ " input, &value)));\n");
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
- printer->Print(variables_,
- " add_$name$(static_cast< $type$ >(value));\n");
+ format(" add_$name$(static_cast< $type$ >(value));\n");
} else {
- printer->Print(variables_,
- " if ($type$_IsValid(value)) {\n"
- " add_$name$(static_cast< $type$ >(value));\n"
- " } else {\n");
+ format(
+ " if ($type$_IsValid(value)) {\n"
+ " add_$name$(static_cast< $type$ >(value));\n"
+ " } else {\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(variables_,
- " mutable_unknown_fields()->AddVarint(\n"
- " $number$, static_cast< ::google::protobuf::uint64>(value));\n");
+ format(
+ " mutable_unknown_fields()->AddVarint(\n"
+ " $number$, static_cast<$uint64$>(value));\n");
} else {
- printer->Print(variables_,
- " unknown_fields_stream.WriteVarint32(tag);\n"
- " unknown_fields_stream.WriteVarint32(\n"
- " static_cast< ::google::protobuf::uint32>(value));\n");
+ format(
+ " unknown_fields_stream.WriteVarint32(tag);\n"
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast<$uint32$>(value));\n");
}
- printer->Print(
- " }\n");
+ format(" }\n");
}
- printer->Print(variables_,
- "}\n"
- "input->PopLimit(limit);\n");
+ format(
+ "}\n"
+ "input->PopLimit(limit);\n");
}
}
-void RepeatedEnumFieldGenerator::
-GenerateSerializeWithCachedSizes(io::Printer* printer) const {
+void RepeatedEnumFieldGenerator::GenerateSerializeWithCachedSizes(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->is_packed()) {
// Write the tag and the size.
- printer->Print(variables_,
- "if (this->$name$_size() > 0) {\n"
- " ::google::protobuf::internal::WireFormatLite::WriteTag(\n"
- " $number$,\n"
- " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
- " output);\n"
- " output->WriteVarint32(\n"
- " static_cast< ::google::protobuf::uint32>(_$name$_cached_byte_size_));\n"
- "}\n");
+ format(
+ "if (this->$name$_size() > 0) {\n"
+ " ::$proto_ns$::internal::WireFormatLite::WriteTag(\n"
+ " $number$,\n"
+ " "
+ "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
+ " output);\n"
+ " output->WriteVarint32(_$name$_cached_byte_size_.load(\n"
+ " std::memory_order_relaxed));\n"
+ "}\n");
}
- printer->Print(variables_,
- "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
+ format("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"
- " this->$name$(i), output);\n");
+ format(
+ " ::$proto_ns$::internal::WireFormatLite::WriteEnumNoTag(\n"
+ " this->$name$(i), output);\n");
} else {
- printer->Print(variables_,
- " ::google::protobuf::internal::WireFormatLite::WriteEnum(\n"
- " $number$, this->$name$(i), output);\n");
+ format(
+ " ::$proto_ns$::internal::WireFormatLite::WriteEnum(\n"
+ " $number$, this->$name$(i), output);\n");
}
- printer->Print("}\n");
+ format("}\n");
}
-void RepeatedEnumFieldGenerator::
-GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
+void RepeatedEnumFieldGenerator::GenerateSerializeWithCachedSizesToArray(
+ io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->is_packed()) {
// Write the tag and the size.
- printer->Print(variables_,
- "if (this->$name$_size() > 0) {\n"
- " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n"
- " $number$,\n"
- " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
- " target);\n"
- " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray("
- " static_cast< ::google::protobuf::uint32>(\n"
- " _$name$_cached_byte_size_), target);\n"
- " target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n"
- " this->$name$_, target);\n"
- "}\n");
+ format(
+ "if (this->$name$_size() > 0) {\n"
+ " target = ::$proto_ns$::internal::WireFormatLite::WriteTagToArray(\n"
+ " $number$,\n"
+ " "
+ "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
+ " target);\n"
+ " target = ::$proto_ns$::io::CodedOutputStream::WriteVarint32ToArray("
+ " _$name$_cached_byte_size_.load(std::memory_order_relaxed),\n"
+ " target);\n"
+ " target = "
+ "::$proto_ns$::internal::WireFormatLite::WriteEnumNoTagToArray(\n"
+ " this->$name$_, target);\n"
+ "}\n");
} else {
- printer->Print(variables_,
- "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n"
- " $number$, this->$name$_, target);\n");
+ format(
+ "target = ::$proto_ns$::internal::WireFormatLite::WriteEnumToArray(\n"
+ " $number$, this->$name$_, target);\n");
}
}
-void RepeatedEnumFieldGenerator::
-GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "{\n"
- " size_t data_size = 0;\n"
- " unsigned int count = static_cast<unsigned int>(this->$name$_size());");
- printer->Indent();
- printer->Print(variables_,
+void RepeatedEnumFieldGenerator::GenerateByteSize(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ format(
+ "{\n"
+ " size_t data_size = 0;\n"
+ " unsigned int count = static_cast<unsigned int>(this->$name$_size());");
+ format.Indent();
+ format(
"for (unsigned int i = 0; i < count; i++) {\n"
- " data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n"
+ " data_size += ::$proto_ns$::internal::WireFormatLite::EnumSize(\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(\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"
- "_$name$_cached_byte_size_ = cached_size;\n"
- "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
- "total_size += data_size;\n");
+ format(
+ "if (data_size > 0) {\n"
+ " total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::Int32Size(\n"
+ " static_cast<$int32$>(data_size));\n"
+ "}\n"
+ "int cached_size = ::$proto_ns$::internal::ToCachedSize(data_size);\n"
+ "_$name$_cached_byte_size_.store(cached_size,\n"
+ " std::memory_order_relaxed);\n"
+ "total_size += data_size;\n");
} else {
- printer->Print(variables_,
- "total_size += ($tag_size$UL * count) + data_size;\n");
+ format("total_size += ($tag_size$UL * count) + data_size;\n");
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.h b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
index d0e87b79..b43d402b 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
@@ -63,10 +63,6 @@ class EnumFieldGenerator : public FieldGenerator {
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
- protected:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
};
@@ -109,15 +105,12 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc
index c416ba10..f866eb6e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc
@@ -84,86 +84,98 @@ ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor,
break;
default:
type_traits_.append("PrimitiveTypeTraits< ");
- type_traits_.append(PrimitiveTypeName(descriptor_->cpp_type()));
+ type_traits_.append(PrimitiveTypeName(options_, descriptor_->cpp_type()));
type_traits_.append(" >");
break;
}
+ SetCommonVars(options, &variables_);
+ variables_["extendee"] = ExtendeeClassName(descriptor_);
+ variables_["type_traits"] = type_traits_;
+ string name = descriptor_->name();
+ variables_["name"] = name;
+ variables_["constant_name"] = FieldConstantName(descriptor_);
+ variables_["field_type"] =
+ SimpleItoa(static_cast<int>(descriptor_->type()));
+ variables_["packed"] = descriptor_->options().packed() ? "true" : "false";
+
+ string scope =
+ IsScoped() ? ClassName(descriptor_->extension_scope(), false) + "::" : "";
+ variables_["scope"] = scope;
+ string scoped_name = scope + name;
+ variables_["scoped_name"] = scoped_name;
+ variables_["number"] = SimpleItoa(descriptor_->number());
}
ExtensionGenerator::~ExtensionGenerator() {}
-void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) {
- std::map<string, string> vars;
- vars["extendee" ] = ExtendeeClassName(descriptor_);
- vars["number" ] = SimpleItoa(descriptor_->number());
- vars["type_traits" ] = type_traits_;
- vars["name" ] = descriptor_->name();
- vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
- vars["packed" ] = descriptor_->options().packed() ? "true" : "false";
- vars["constant_name"] = FieldConstantName(descriptor_);
+bool ExtensionGenerator::IsScoped() const {
+ return descriptor_->extension_scope() != nullptr;
+}
+
+void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// If this is a class member, it needs to be declared "static". Otherwise,
// it needs to be "extern". In the latter case, it also needs the DLL
// export/import specifier.
- if (descriptor_->extension_scope() == NULL) {
- vars["qualifier"] = "extern";
+ string qualifier;
+ if (!IsScoped()) {
+ qualifier = "extern";
if (!options_.dllexport_decl.empty()) {
- vars["qualifier"] = options_.dllexport_decl + " " + vars["qualifier"];
+ qualifier = options_.dllexport_decl + " " + qualifier;
}
} else {
- vars["qualifier"] = "static";
+ qualifier = "static";
}
- printer->Print(vars,
- "static const int $constant_name$ = $number$;\n"
- "$qualifier$ ::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n"
- " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
- " $name$;\n"
- );
+ format(
+ "static const int $constant_name$ = $number$;\n"
+ "$1$ ::$proto_ns$::internal::ExtensionIdentifier< $extendee$,\n"
+ " ::$proto_ns$::internal::$type_traits$, $field_type$, $packed$ >\n"
+ " $name$;\n",
+ qualifier);
}
void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
- // If this is a class member, it needs to be declared in its class scope.
- string scope = (descriptor_->extension_scope() == NULL) ? "" :
- ClassName(descriptor_->extension_scope(), false) + "::";
- string name = scope + descriptor_->name();
-
- std::map<string, string> vars;
- vars["extendee" ] = ExtendeeClassName(descriptor_);
- vars["type_traits" ] = type_traits_;
- vars["name" ] = name;
- vars["constant_name"] = FieldConstantName(descriptor_);
- vars["default" ] = DefaultValue(descriptor_);
- vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
- vars["packed" ] = descriptor_->options().packed() ? "true" : "false";
- vars["scope" ] = scope;
+ // If we are building for lite with implicit weak fields, we want to skip over
+ // any custom options (i.e. extensions of messages from descriptor.proto).
+ // This prevents the creation of any unnecessary linker references to the
+ // descriptor messages.
+ if (options_.lite_implicit_weak_fields &&
+ descriptor_->containing_type()->file()->name() ==
+ "net/proto2/proto/descriptor.proto") {
+ return;
+ }
+ Formatter format(printer, variables_);
+ string default_str;
+ // If this is a class member, it needs to be declared in its class scope.
if (descriptor_->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
// We need to declare a global string which will contain the default value.
// We cannot declare it at class scope because that would require exposing
// it in the header which would be annoying for other reasons. So we
// replace :: with _ in the name and declare it as a global.
- string global_name = StringReplace(name, "::", "_", true);
- vars["global_name"] = global_name;
- printer->Print(vars,
- "const ::std::string $global_name$_default($default$);\n");
-
- // Update the default to refer to the string global.
- vars["default"] = global_name + "_default";
+ default_str =
+ StringReplace(variables_["scoped_name"], "::", "_", true) + "_default";
+ format("const ::std::string $1$($2$);\n", default_str,
+ DefaultValue(options_, descriptor_));
+ } else {
+ default_str = DefaultValue(options_, descriptor_);
}
// Likewise, class members need to declare the field constant variable.
- if (descriptor_->extension_scope() != NULL) {
- printer->Print(vars,
- "#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"
- "const int $scope$$constant_name$;\n"
- "#endif\n");
+ if (IsScoped()) {
+ format(
+ "#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"
+ "const int $scope$$constant_name$;\n"
+ "#endif\n");
}
- printer->Print(vars,
- "::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n"
- " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
- " $name$($constant_name$, $default$);\n");
+ format(
+ "::$proto_ns$::internal::ExtensionIdentifier< $extendee$,\n"
+ " ::$proto_ns$::internal::$type_traits$, $field_type$, $packed$ >\n"
+ " $scoped_name$($constant_name$, $1$);\n",
+ default_str);
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.h b/src/google/protobuf/compiler/cpp/cpp_extension.h
index 30236d71..72413f6b 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.h
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.h
@@ -35,18 +35,22 @@
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__
+#include <map>
#include <string>
+
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
namespace google {
namespace protobuf {
- class FieldDescriptor; // descriptor.h
- namespace io {
- class Printer; // printer.h
- }
+class FieldDescriptor; // descriptor.h
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
@@ -62,22 +66,26 @@ class ExtensionGenerator {
~ExtensionGenerator();
// Header stuff.
- void GenerateDeclaration(io::Printer* printer);
+ void GenerateDeclaration(io::Printer* printer) const;
// Source file stuff.
void GenerateDefinition(io::Printer* printer);
+ bool IsScoped() const;
+
private:
const FieldDescriptor* descriptor_;
- string type_traits_;
+ std::string type_traits_;
Options options_;
+ std::map<std::string, std::string> variables_;
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/cpp_field.cc
index 0de20f84..582da4ae 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_field.cc
@@ -38,6 +38,7 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_primitive_field.h>
#include <google/protobuf/compiler/cpp/cpp_string_field.h>
+
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_enum_field.h>
@@ -58,6 +59,7 @@ using internal::WireFormat;
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
+ SetCommonVars(options, variables);
(*variables)["ns"] = Namespace(descriptor);
(*variables)["name"] = FieldName(descriptor);
(*variables)["index"] = SimpleItoa(descriptor->index());
@@ -67,20 +69,17 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["field_member"] = FieldName(descriptor) + "_";
(*variables)["tag_size"] = SimpleItoa(
- WireFormat::TagSize(descriptor->number(), descriptor->type()));
- (*variables)["deprecation"] = descriptor->options().deprecated()
- ? " PROTOBUF_DEPRECATED" : "";
- (*variables)["deprecated_attr"] = descriptor->options().deprecated()
- ? "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
+ WireFormat::TagSize(descriptor->number(), descriptor->type()));
+ (*variables)["deprecated_attr"] =
+ DeprecatedAttribute(options, descriptor->options().deprecated());
+ (*variables)["set_hasbit"] = "";
+ (*variables)["clear_hasbit"] = "";
if (HasFieldPresence(descriptor->file())) {
- (*variables)["set_hasbit"] =
- "set_has_" + FieldName(descriptor) + "();";
- (*variables)["clear_hasbit"] =
- "clear_has_" + FieldName(descriptor) + "();";
+ (*variables)["set_hasbit_io"] =
+ "HasBitSetters::set_has_" + FieldName(descriptor) + "(this);";
} else {
- (*variables)["set_hasbit"] = "";
- (*variables)["clear_hasbit"] = "";
+ (*variables)["set_hasbit_io"] = "";
}
// These variables are placeholders to pick out the beginning and ends of
@@ -91,11 +90,24 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["}"] = "";
}
+void FieldGenerator::SetHasBitIndex(int32 has_bit_index) {
+ if (!HasFieldPresence(descriptor_->file()) || has_bit_index == -1) {
+ return;
+ }
+ variables_["set_hasbit"] = StrCat(
+ "_has_bits_[", has_bit_index / 32, "] |= 0x",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8), "u;");
+ variables_["clear_hasbit"] = StrCat(
+ "_has_bits_[", has_bit_index / 32, "] &= ~0x",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8), "u;");
+}
+
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
const string prefix = descriptor->containing_oneof()->name() + "_.";
(*variables)["oneof_name"] = descriptor->containing_oneof()->name();
- (*variables)["field_member"] = StrCat(prefix, (*variables)["name"], "_");
+ (*variables)["field_member"] =
+ StrCat(prefix, (*variables)["name"], "_");
}
FieldGenerator::~FieldGenerator() {}
@@ -114,7 +126,7 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
const Options& options,
- SCCAnalyzer* scc_analyzer)
+ MessageSCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
options_(options),
field_generators_(descriptor->field_count()) {
@@ -125,9 +137,22 @@ FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
}
}
-FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
- const Options& options,
- SCCAnalyzer* scc_analyzer) {
+FieldGenerator* FieldGeneratorMap::MakeGoogleInternalGenerator(
+ const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer) {
+
+ return nullptr;
+}
+
+FieldGenerator* FieldGeneratorMap::MakeGenerator(
+ const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer) {
+ FieldGenerator* generator =
+ MakeGoogleInternalGenerator(field, options, scc_analyzer);
+ if (generator) {
+ return generator;
+ }
+
if (field->is_repeated()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
@@ -138,11 +163,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
scc_analyzer);
}
case FieldDescriptor::CPPTYPE_STRING:
- switch (field->options().ctype()) {
- default: // RepeatedStringFieldGenerator handles unknown ctypes.
- case FieldOptions::STRING:
- return new RepeatedStringFieldGenerator(field, options);
- }
+ return new RepeatedStringFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_ENUM:
return new RepeatedEnumFieldGenerator(field, options);
default:
@@ -153,11 +174,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageOneofFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
- switch (field->options().ctype()) {
- default: // StringOneofFieldGenerator handles unknown ctypes.
- case FieldOptions::STRING:
- return new StringOneofFieldGenerator(field, options);
- }
+ return new StringOneofFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_ENUM:
return new EnumOneofFieldGenerator(field, options);
default:
@@ -168,11 +185,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
- switch (field->options().ctype()) {
- default: // StringFieldGenerator handles unknown ctypes.
- case FieldOptions::STRING:
- return new StringFieldGenerator(field, options);
- }
+ return new StringFieldGenerator(field, options);
case FieldDescriptor::CPPTYPE_ENUM:
return new EnumFieldGenerator(field, options);
default:
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h
index 8cdbe886..43a3e367 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_field.h
@@ -45,11 +45,13 @@
namespace google {
namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
@@ -59,15 +61,17 @@ namespace cpp {
// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size',
// 'deprecation'].
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
- std::map<string, string>* variables,
+ std::map<std::string, std::string>* variables,
const Options& options);
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
- std::map<string, string>* variables);
+ std::map<std::string, std::string>* variables);
class FieldGenerator {
public:
- explicit FieldGenerator(const Options& options) : options_(options) {}
+ explicit FieldGenerator(const FieldDescriptor* descriptor,
+ const Options& options)
+ : descriptor_(descriptor), options_(options) {}
virtual ~FieldGenerator();
// Generate lines of code declaring members fields of the message class
@@ -95,17 +99,27 @@ class FieldGenerator {
virtual void GenerateNonInlineAccessorDefinitions(
io::Printer* /*printer*/) const {}
+ // Generate declarations of accessors that are for internal purposes only.
+ // Most field types don't need this, so the default implementation is empty.
+ virtual void GenerateInternalAccessorDefinitions(
+ io::Printer* /*printer*/) const {}
+
+ // Generate definitions of accessors that are for internal purposes only.
+ // Most field types don't need this, so the default implementation is empty.
+ virtual void GenerateInternalAccessorDeclarations(
+ io::Printer* /*printer*/) const {}
+
// Generate lines of code (statements, not declarations) which clear the
// field. This is used to define the clear_$name$() method
virtual void GenerateClearingCode(io::Printer* printer) const = 0;
- // Generate lines of code (statements, not declarations) which clear the field
- // as part of the Clear() method for the whole message. For message types
- // which have field presence bits, MessageGenerator::GenerateClear will have
- // already checked the presence bits.
+ // Generate lines of code (statements, not declarations) which clear the
+ // field as part of the Clear() method for the whole message. For message
+ // types which have field presence bits, MessageGenerator::GenerateClear
+ // will have already checked the presence bits.
//
- // Since most field types can re-use GenerateClearingCode, this method is not
- // pure virtual.
+ // Since most field types can re-use GenerateClearingCode, this method is
+ // not pure virtual.
virtual void GenerateMessageClearingCode(io::Printer* printer) const {
GenerateClearingCode(printer);
}
@@ -140,17 +154,17 @@ class FieldGenerator {
// Generate a manual destructor invocation for use when the message is on an
// arena. The code that this method generates will be executed inside a
- // shared-for-the-whole-message-class method registered with OwnDestructor().
- // The method should return |true| if it generated any code that requires a
- // call; this allows the message generator to eliminate the OwnDestructor()
- // registration if no fields require it.
+ // shared-for-the-whole-message-class method registered with
+ // OwnDestructor(). The method should return |true| if it generated any code
+ // that requires a call; this allows the message generator to eliminate the
+ // OwnDestructor() registration if no fields require it.
virtual bool GenerateArenaDestructorCode(io::Printer* printer) const {
return false;
}
// Generate code that allocates the fields's default instance.
- virtual void GenerateDefaultInstanceAllocator(io::Printer* /*printer*/)
- const {}
+ virtual void GenerateDefaultInstanceAllocator(
+ io::Printer* /*printer*/) const {}
// Generate lines to decode this field, which will be placed inside the
// message's MergeFromCodedStream() method.
@@ -162,8 +176,8 @@ class FieldGenerator {
// Generate lines to decode this field from a packed value, which will be
// placed inside the message's MergeFromCodedStream() method.
- virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer)
- const;
+ virtual void GenerateMergeFromCodedStreamWithPacking(
+ io::Printer* printer) const;
// Generate lines to serialize this field, which are placed within the
// message's SerializeWithCachedSizes() method.
@@ -184,8 +198,12 @@ class FieldGenerator {
virtual uint32 CalculateFieldTag() const { return 0; }
virtual bool IsInlined() const { return false; }
+ void SetHasBitIndex(int32 has_bit_index);
+
protected:
+ const FieldDescriptor* descriptor_;
const Options& options_;
+ std::map<std::string, std::string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
@@ -195,19 +213,28 @@ class FieldGenerator {
class FieldGeneratorMap {
public:
FieldGeneratorMap(const Descriptor* descriptor, const Options& options,
- SCCAnalyzer* scc_analyzer);
+ MessageSCCAnalyzer* scc_analyzer);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
+ void SetHasBitIndices(const std::vector<int>& has_bit_indices_) {
+ for (int i = 0; i < descriptor_->field_count(); ++i) {
+ field_generators_[i]->SetHasBitIndex(has_bit_indices_[i]);
+ }
+ }
+
private:
const Descriptor* descriptor_;
const Options& options_;
std::vector<std::unique_ptr<FieldGenerator>> field_generators_;
+ static FieldGenerator* MakeGoogleInternalGenerator(
+ const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer);
static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
const Options& options,
- SCCAnalyzer* scc_analyzer);
+ MessageSCCAnalyzer* scc_analyzer);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
@@ -215,6 +242,6 @@ class FieldGeneratorMap {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc
index 42525687..1e80715d 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_file.cc
@@ -44,72 +44,79 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_message.h>
#include <google/protobuf/compiler/cpp/cpp_service.h>
+#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
- : file_(file),
- options_(options),
- scc_analyzer_(options),
- enum_generators_owner_(
- new std::unique_ptr<EnumGenerator>[file->enum_type_count()]),
- service_generators_owner_(
- new std::unique_ptr<ServiceGenerator>[file->service_count()]),
- extension_generators_owner_(
- new std::unique_ptr<ExtensionGenerator>[file->extension_count()]) {
+ : file_(file), options_(options), scc_analyzer_(options) {
+ // These variables are the same on a file level
+ SetCommonVars(options, &variables_);
+ variables_["dllexport_decl"] = options.dllexport_decl;
+ variables_["tablename"] = UniqueName("TableStruct", file_, options_);
+ variables_["assign_desc_table"] =
+ UniqueName("assign_descriptors_table", file_, options_);
+ variables_["file_level_metadata"] =
+ UniqueName("file_level_metadata", file_, options_);
+ variables_["file_level_enum_descriptors"] =
+ UniqueName("file_level_enum_descriptors", file_, options_);
+ variables_["file_level_service_descriptors"] =
+ UniqueName("file_level_service_descriptors", file_, options_);
+ variables_["add_descriptors"] = UniqueName("AddDescriptors", file_, options_);
+ variables_["filename"] = file_->name();
+ variables_["package_ns"] = Namespace(file_);
+ variables_["init_defaults"] = UniqueName("InitDefaults", file_, options_);
+
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);
+ new MessageGenerator(msgs[i], variables_, i, options, &scc_analyzer_);
+ message_generators_.emplace_back(msg_gen);
msg_gen->AddGenerators(&enum_generators_, &extension_generators_);
}
for (int i = 0; i < file->enum_type_count(); i++) {
- enum_generators_owner_[i].reset(
- new EnumGenerator(file->enum_type(i), options));
- enum_generators_.push_back(enum_generators_owner_[i].get());
+ enum_generators_.emplace_back(
+ new EnumGenerator(file->enum_type(i), variables_, options));
}
for (int i = 0; i < file->service_count(); i++) {
- service_generators_owner_[i].reset(
- new ServiceGenerator(file->service(i), options));
- service_generators_.push_back(service_generators_owner_[i].get());
+ service_generators_.emplace_back(
+ new ServiceGenerator(file->service(i), variables_, options));
}
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(
+ extension_generators_.emplace_back(
new ExtensionGenerator(file->extension(i), options));
- extension_generators_.push_back(extension_generators_owner_[i].get());
}
-
-
- package_parts_ = Split(file_->package(), ".", true);
-}
-
-FileGenerator::~FileGenerator() {
- for (int i = 0; i < message_generators_.size(); i++) {
- delete message_generators_[i];
+ for (int i = 0; i < file->weak_dependency_count(); ++i) {
+ weak_deps_.insert(file->weak_dependency(i));
}
}
+FileGenerator::~FileGenerator() = default;
+
void FileGenerator::GenerateMacroUndefs(io::Printer* printer) {
+ Formatter format(printer, variables_);
// 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") {
+ if (file_->name() != "net/proto2/compiler/proto/plugin.proto" &&
+ file_->name() != "google/protobuf/compiler/plugin.proto") {
return;
}
std::vector<string> names_to_undef;
@@ -126,70 +133,89 @@ void FileGenerator::GenerateMacroUndefs(io::Printer* printer) {
}
}
for (int i = 0; i < names_to_undef.size(); ++i) {
- printer->Print(
- "#ifdef $name$\n"
- "#undef $name$\n"
+ format(
+ "#ifdef $1$\n"
+ "#undef $1$\n"
"#endif\n",
- "name", names_to_undef[i]);
+ names_to_undef[i]);
}
}
void FileGenerator::GenerateHeader(io::Printer* printer) {
- printer->Print(
- "// @@protoc_insertion_point(includes)\n");
+ Formatter format(printer, variables_);
- printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n",
- "filename", FileLevelNamespace(file_),
- "export", options_.dllexport_decl);
+ // port_def.inc must be included after all other includes.
+ IncludeFile("net/proto2/public/port_def.inc", printer);
+ format("#define $1$$ dllexport_decl$\n",
+ UniqueName("PROTOBUF_INTERNAL_EXPORT", file_, options_));
GenerateMacroUndefs(printer);
+ if (IsProto2MessageSetFile(file_, options_)) {
+ // Proto2 MessageSet overrides GetMapper() so we forward declare TagMapper
+ // to avoid inclusion of "tagmapper.h".
+ format("class TagMapper;\n");
+ }
+
+ if (!options_.opensource_runtime) {
+ // EmbeddedMessageHolder is a proxy class to provide access into arena
+ // constructors for proto1 message objects.
+ // See net/proto/proto_arena_internal.h
+ format(
+ "namespace proto {\n"
+ "namespace internal {\n"
+ "template <typename T> struct EmbeddedMessageHolder;\n"
+ "} // namespace internal\n"
+ "} // namespace proto\n");
+ }
GenerateGlobalStateFunctionDeclarations(printer);
GenerateForwardDeclarations(printer);
{
- NamespaceOpener ns(Namespace(file_), printer);
+ NamespaceOpener ns(Namespace(file_), format);
- printer->Print("\n");
+ format("\n");
GenerateEnumDefinitions(printer);
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ format(kThickSeparator);
+ format("\n");
GenerateMessageDefinitions(printer);
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThickSeparator);
+ format("\n");
GenerateServiceDefinitions(printer);
GenerateExtensionIdentifiers(printer);
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThickSeparator);
+ format("\n");
GenerateInlineFunctionDefinitions(printer);
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n"
- "\n");
+ format(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n"
+ "\n");
}
// We need to specialize some templates in the ::google::protobuf namespace:
GenerateProto2NamespaceEnumSpecializations(printer);
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(global_scope)\n"
- "\n");
+ format(
+ "\n"
+ "// @@protoc_insertion_point(global_scope)\n"
+ "\n");
+ IncludeFile("net/proto2/public/port_undef.inc", printer);
}
void FileGenerator::GenerateProtoHeader(io::Printer* printer,
const string& info_path) {
+ Formatter format(printer, variables_);
if (!options_.proto_h) {
return;
}
@@ -197,99 +223,187 @@ void FileGenerator::GenerateProtoHeader(io::Printer* printer,
string filename_identifier = FilenameIdentifier(file_->name());
GenerateTopHeaderGuard(printer, filename_identifier);
+ if (!options_.opensource_runtime) {
+ format(
+ "#ifdef SWIG\n"
+ "#error \"Do not SWIG-wrap protobufs.\"\n"
+ "#endif // SWIG\n"
+ "\n");
+ }
+
+ if (IsBootstrapProto(options_, file_)) {
+ format("// IWYU pragma: private, include \"$1$.proto.h\"\n\n",
+ StripProto(file_->name()));
+ }
GenerateLibraryIncludes(printer);
for (int i = 0; i < file_->public_dependency_count(); i++) {
const FileDescriptor* dep = file_->public_dependency(i);
const char* extension = ".proto.h";
+ // The proto1 compiler only generates .pb.h files, so even if we are
+ // running in proto-h mode, we can only use the .pb.h.
+ if (IsProto1(dep, options_)) {
+ extension = ".pb.h";
+ }
string dependency = StripProto(dep->name()) + extension;
- printer->Print(
- "#include \"$dependency$\" // IWYU pragma: export\n",
- "dependency", dependency);
+ format("#include \"$1$\"\n", dependency);
}
+ format("// @@protoc_insertion_point(includes)\n");
+
GenerateMetadataPragma(printer, info_path);
GenerateHeader(printer);
+ IncludeFile("net/proto2/public/port_undef.inc", printer);
+
GenerateBottomHeaderGuard(printer, filename_identifier);
}
void FileGenerator::GeneratePBHeader(io::Printer* printer,
const string& info_path) {
+ Formatter format(printer, variables_);
string filename_identifier =
FilenameIdentifier(file_->name() + (options_.proto_h ? ".pb.h" : ""));
GenerateTopHeaderGuard(printer, filename_identifier);
if (options_.proto_h) {
string target_basename = StripProto(file_->name());
- printer->Print("#include \"$basename$.proto.h\" // IWYU pragma: export\n",
- "basename", target_basename);
+ if (!options_.opensource_runtime) {
+ GetBootstrapBasename(options_, target_basename, &target_basename);
+ }
+ format("#include \"$1$.proto.h\" // IWYU pragma: export\n",
+ target_basename);
} else {
GenerateLibraryIncludes(printer);
}
- GenerateDependencyIncludes(printer);
+ if (options_.transitive_pb_h) {
+ GenerateDependencyIncludes(printer);
+ }
+
+ // This is unfortunately necessary for some plugins. I don't see why we
+ // need two of the same insertion points.
+ // TODO(gerbens) remove this.
+ format("// @@protoc_insertion_point(includes)\n");
+
GenerateMetadataPragma(printer, info_path);
if (!options_.proto_h) {
GenerateHeader(printer);
} else {
- // This is unfortunately necessary for some plugins. I don't see why we
- // need two of the same insertion points.
- // TODO(gerbens) remove this.
- printer->Print(
- "// @@protoc_insertion_point(includes)\n");
{
- NamespaceOpener ns(Namespace(file_), printer);
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n");
+ NamespaceOpener ns(Namespace(file_), format);
+ format(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n");
}
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(global_scope)\n"
- "\n");
+ format(
+ "\n"
+ "// @@protoc_insertion_point(global_scope)\n"
+ "\n");
}
GenerateBottomHeaderGuard(printer, filename_identifier);
}
+void FileGenerator::DoIncludeFile(const string& google3_name, bool do_export,
+ io::Printer* printer) {
+ Formatter format(printer, variables_);
+ const string prefix = "net/proto2/";
+ GOOGLE_CHECK(google3_name.find(prefix) == 0) << google3_name;
+
+ if (options_.opensource_runtime) {
+ string path = google3_name.substr(prefix.size());
+
+ path = StringReplace(path, "internal/", "", false);
+ path = StringReplace(path, "proto/", "", false);
+ path = StringReplace(path, "public/", "", false);
+ if (options_.opensource_include_paths) {
+ format("#include <google/protobuf/$1$>", path);
+ } else {
+ format(
+ "#include "
+ "\"third_party/protobuf/testing/extracted/src/google/protobuf/$1$\"",
+ path);
+ }
+ } else {
+ format("#include \"$1$\"", google3_name);
+ }
+
+ if (do_export) {
+ format(" // IWYU pragma: export");
+ }
+
+ format("\n");
+}
+
+string FileGenerator::CreateHeaderInclude(const string& basename,
+ const FileDescriptor* file) {
+ bool use_system_include = false;
+ string name = basename;
+
+ if (options_.opensource_runtime) {
+ if (IsWellKnownMessage(file)) {
+ if (options_.opensource_include_paths) {
+ use_system_include = true;
+ } else {
+ name = "third_party/protobuf/testing/extracted/src/" + basename;
+ }
+ }
+ }
+
+ string left = "\"";
+ string right = "\"";
+ if (use_system_include) {
+ left = "<";
+ right = ">";
+ }
+ return left + name + right;
+}
+
void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
+ Formatter format(printer, variables_);
string target_basename = StripProto(file_->name());
- const bool use_system_include = IsWellKnownMessage(file_);
-
- string header = target_basename + (options_.proto_h ? ".proto.h" : ".pb.h");
- printer->Print(
- "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
- "// source: $filename$\n"
- "\n"
- "#include $left$$header$$right$\n"
- "\n"
- "#include <algorithm>\n" // for swap()
- "\n"
- "#include <google/protobuf/stubs/common.h>\n"
- "#include <google/protobuf/stubs/port.h>\n"
- "#include <google/protobuf/io/coded_stream.h>\n"
- "#include <google/protobuf/wire_format_lite_inl.h>\n",
- "filename", file_->name(),
- "header", header,
- "left", use_system_include ? "<" : "\"",
- "right", use_system_include ? ">" : "\"");
+ if (!options_.opensource_runtime) {
+ GetBootstrapBasename(options_, target_basename, &target_basename);
+ }
+ target_basename += options_.proto_h ? ".proto.h" : ".pb.h";
+ format(
+ "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
+ "// source: $filename$\n"
+ "\n"
+ "#include $1$\n"
+ "\n"
+ "#include <algorithm>\n" // for swap()
+ "\n",
+ CreateHeaderInclude(target_basename, file_));
+
+ if (options_.opensource_runtime) {
+ DoIncludeFile("net/proto2/public/stubs/common.h", false, printer);
+ }
+
+ IncludeFile("net/proto2/io/public/coded_stream.h", printer);
+ // TODO(gerbens) This is to include parse_context.h, we need a better way
+ IncludeFile("net/proto2/public/extension_set.h", printer);
+ IncludeFile("net/proto2/public/wire_format_lite_inl.h", printer);
// Unknown fields implementation in lite mode uses StringOutputStream
if (!UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) {
- printer->Print(
- "#include <google/protobuf/io/zero_copy_stream_impl_lite.h>\n");
+ IncludeFile("net/proto2/io/public/zero_copy_stream_impl_lite.h", printer);
}
if (HasDescriptorMethods(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/descriptor.h>\n"
- "#include <google/protobuf/generated_message_reflection.h>\n"
- "#include <google/protobuf/reflection_ops.h>\n"
- "#include <google/protobuf/wire_format.h>\n");
+ IncludeFile("net/proto2/public/descriptor.h", printer);
+ IncludeFile("net/proto2/public/generated_message_reflection.h", printer);
+ IncludeFile("net/proto2/public/reflection_ops.h", printer);
+ IncludeFile("net/proto2/public/wire_format.h", printer);
+ }
+ if (IsProto2MessageSetFile(file_, options_)) {
+ format(
+ // Implementation of proto1 MessageSet API methods.
+ "#include \"net/proto2/bridge/internal/message_set_util.h\"\n");
}
if (options_.proto_h) {
@@ -298,104 +412,100 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
const FileDescriptor* dep = file_->dependency(i);
const char* extension = ".proto.h";
string basename = StripProto(dep->name());
+ // Do not import weak deps.
+ if (!options_.opensource_runtime && IsDepWeak(dep)) continue;
+ // The proto1 compiler only generates .pb.h files, so even if we are
+ // running in proto-h mode, we can only use the .pb.h.
+ if (IsProto1(dep, options_)) {
+ extension = ".pb.h";
+ }
+ if (IsBootstrapProto(options_, file_)) {
+ GetBootstrapBasename(options_, basename, &basename);
+ }
string dependency = basename + extension;
- printer->Print(
- "#include \"$dependency$\"\n",
- "dependency", dependency);
+ format("#include \"$1$\"\n", dependency);
}
}
- // 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");
+ format("// @@protoc_insertion_point(includes)\n");
+ IncludeFile("net/proto2/public/port_def.inc", printer);
}
void FileGenerator::GenerateSourceDefaultInstance(int idx,
io::Printer* printer) {
- printer->Print(
- "class $classname$DefaultTypeInternal {\n"
+ Formatter format(printer, variables_);
+ format(
+ "class $1$DefaultTypeInternal {\n"
" public:\n"
- " ::google::protobuf::internal::ExplicitlyConstructed<$classname$>\n"
- " _instance;\n",
- "classname", message_generators_[idx]->classname_);
- printer->Indent();
+ " ::$proto_ns$::internal::ExplicitlyConstructed<$1$> _instance;\n",
+ message_generators_[idx]->classname_);
+ format.Indent();
message_generators_[idx]->GenerateExtraDefaultFields(printer);
- printer->Outdent();
- printer->Print("} _$classname$_default_instance_;\n", "classname",
- message_generators_[idx]->classname_);
+ format.Outdent();
+ format("} _$1$_default_instance_;\n", message_generators_[idx]->classname_);
}
-namespace {
-
// Generates weak symbol declarations for types that are to be considered weakly
// referenced.
-void GenerateInternalForwardDeclarations(
+void FileGenerator::GenerateInternalForwardDeclarations(
const std::vector<const FieldDescriptor*>& fields, const Options& options,
- SCCAnalyzer* scc_analyzer, io::Printer* printer) {
+ MessageSCCAnalyzer* scc_analyzer, io::Printer* printer) {
+ Formatter format(printer);
// To ensure determinism and minimize the number of namespace statements,
// we output the forward declarations sorted on namespace and type / function
// name.
+ std::set<string> global_namespace_decls;
+ // weak defaults
std::set<std::pair<string, string> > messages;
- std::set<std::pair<string, string> > sccs;
- std::set<std::pair<string, string> > inits;
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
const Descriptor* msg = field->message_type();
if (msg == nullptr) continue;
bool is_weak = IsImplicitWeakField(field, options, scc_analyzer);
- string flns = FileLevelNamespace(msg);
- auto scc = scc_analyzer->GetSCC(msg);
- string repr = ClassName(scc->GetRepresentative());
+ if (field->options().weak()) {
+ GOOGLE_CHECK(!options_.opensource_runtime);
+ is_weak = true;
+ }
string weak_attr;
if (is_weak) {
- inits.insert(std::make_pair(flns, "AddDescriptors"));
+ global_namespace_decls.insert(
+ "void " + UniqueName("AddDescriptors", msg, options_) +
+ "() __attribute__((weak))");
messages.insert(std::make_pair(Namespace(msg), ClassName(msg)));
weak_attr = " __attribute__((weak))";
}
- string dllexport = "PROTOBUF_INTERNAL_EXPORT_" + FileLevelNamespace(msg);
- sccs.insert(std::make_pair(flns, "extern " + dllexport + weak_attr +
- " ::google::protobuf::internal::SCCInfo<" +
- SimpleItoa(scc->children.size()) +
- "> scc_info_" + repr + ";\n"));
- }
-
- 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(
- "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);
- }
- for (const auto& p : sccs) {
- ns.ChangeTo(p.first);
- printer->Print(p.second.c_str());
+ string dllexport = UniqueName("PROTOBUF_INTERNAL_EXPORT", msg, options_);
+ if (IsProto1(msg->file(), options_) || IsWeak(field, options_)) {
+ dllexport = "";
+ }
+ auto scc = scc_analyzer->GetSCC(msg);
+ string repr =
+ UniqueName(ClassName(scc->GetRepresentative()), msg, options_);
+ global_namespace_decls.insert(
+ "extern " + dllexport + weak_attr + " ::" + ProtobufNamespace(options) +
+ "::internal::SCCInfo<" + SimpleItoa(scc->children.size()) +
+ "> scc_info_" + repr);
+ }
+
+ format("\n");
+
+ for (const string& decl : global_namespace_decls) {
+ format("$1$;\n", decl);
}
-}
-} // namespace
+ // Weak external fields
+ NamespaceOpener ns(format);
+ for (const auto& pair : messages) {
+ ns.ChangeTo(pair.first);
+ format(
+ "extern __attribute__((weak)) $1$DefaultTypeInternal "
+ "_$1$_default_instance_;\n",
+ pair.second);
+ }
+}
void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
+ Formatter format(printer, variables_);
GenerateSourceIncludes(printer);
// Generate weak declarations. We do this for the whole strongly-connected
@@ -411,45 +521,43 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
printer);
if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) {
- NamespaceOpener ns(FileLevelNamespace(file_), printer);
GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer);
}
{ // package namespace
- NamespaceOpener ns(Namespace(file_), printer);
+ NamespaceOpener ns(Namespace(file_), format);
// Define default instances
GenerateSourceDefaultInstance(idx, printer);
if (options_.lite_implicit_weak_fields) {
- printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
- message_generators_[idx]->classname_);
+ format("void $1$_ReferenceStrong() {}\n",
+ message_generators_[idx]->classname_);
}
// Generate classes.
- printer->Print("\n");
+ format("\n");
message_generators_[idx]->GenerateClassMethods(printer);
- printer->Print(
+ format(
"\n"
"// @@protoc_insertion_point(namespace_scope)\n");
} // end package namespace
- printer->Print(
- "namespace google {\nnamespace protobuf {\n");
- message_generators_[idx]->GenerateSourceInProto2Namespace(printer);
- printer->Print(
- "} // namespace protobuf\n} // namespace google\n");
+ {
+ NamespaceOpener proto_ns(ProtobufNamespace(options_), format);
+ message_generators_[idx]->GenerateSourceInProto2Namespace(printer);
+ }
- printer->Print(
+ format(
"\n"
"// @@protoc_insertion_point(global_scope)\n");
}
void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
+ Formatter format(printer, variables_);
GenerateSourceIncludes(printer);
{
- NamespaceOpener ns(FileLevelNamespace(file_), printer);
GenerateTables(printer);
// Define the code to initialize reflection. This code uses a global
@@ -459,7 +567,7 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
}
}
- NamespaceOpener ns(Namespace(file_), printer);
+ NamespaceOpener ns(Namespace(file_), format);
// Generate enums.
for (int i = 0; i < enum_generators_.size(); i++) {
@@ -474,15 +582,16 @@ void FileGenerator::GenerateGlobalSource(io::Printer* 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");
+ if (i == 0) format("\n");
+ format(kThickSeparator);
+ format("\n");
service_generators_[i]->GenerateImplementation(printer);
}
}
}
void FileGenerator::GenerateSource(io::Printer* printer) {
+ Formatter format(printer, variables_);
GenerateSourceIncludes(printer);
std::vector<const FieldDescriptor*> fields;
ListAllFields(file_, &fields);
@@ -490,20 +599,19 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
printer);
{
- NamespaceOpener ns(Namespace(file_), printer);
+ NamespaceOpener ns(Namespace(file_), format);
// Define default instances
for (int i = 0; i < message_generators_.size(); i++) {
GenerateSourceDefaultInstance(i, printer);
if (options_.lite_implicit_weak_fields) {
- printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
- message_generators_[i]->classname_);
+ format("void $1$_ReferenceStrong() {}\n",
+ message_generators_[i]->classname_);
}
}
}
{
- NamespaceOpener ns(FileLevelNamespace(file_), printer);
GenerateTables(printer);
// Now generate the InitDefaults for each SCC.
@@ -514,26 +622,28 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
}
}
- printer->Print("void InitDefaults() {\n");
- 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(
- " ::google::protobuf::internal::InitSCC(&scc_info_$scc_name$.base);\n",
- "scc_name", scc_name);
- }
- printer->Print("}\n\n");
-
- // 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_)) {
+ // TODO(gerbens) This is for proto1 interoperability. Remove when proto1
+ // is gone.
+ format("void $init_defaults$() {\n");
+ for (int i = 0; i < message_generators_.size(); i++) {
+ if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
+ string scc_name =
+ UniqueName(ClassName(message_generators_[i]->descriptor_),
+ message_generators_[i]->descriptor_, options_);
+ format(" ::$proto_ns$::internal::InitSCC(&scc_info_$1$.base);\n",
+ scc_name);
+ }
+ format("}\n\n");
+
+ // Define the code to initialize reflection. This code uses a global
+ // constructor to register reflection data with the runtime pre-main.
GenerateReflectionInitializationCode(printer);
}
}
-
{
- NamespaceOpener ns(Namespace(file_), printer);
+ NamespaceOpener ns(Namespace(file_), format);
// Actually implement the protos
@@ -544,18 +654,18 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
// Generate classes.
for (int i = 0; i < message_generators_.size(); i++) {
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThickSeparator);
+ format("\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");
+ if (i == 0) format("\n");
+ format(kThickSeparator);
+ format("\n");
service_generators_[i]->GenerateImplementation(printer);
}
}
@@ -565,144 +675,28 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
extension_generators_[i]->GenerateDefinition(printer);
}
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(namespace_scope)\n");
- }
-
- printer->Print(
- "namespace google {\nnamespace protobuf {\n");
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->GenerateSourceInProto2Namespace(printer);
- }
- printer->Print(
- "} // namespace protobuf\n} // namespace google\n");
-
- printer->Print(
- "\n"
- "// @@protoc_insertion_point(global_scope)\n");
-}
-
-class FileGenerator::ForwardDeclarations {
- public:
- ~ForwardDeclarations() {
- for (std::map<string, ForwardDeclarations*>::iterator
- it = namespaces_.begin(),
- end = namespaces_.end();
- it != end; ++it) {
- delete it->second;
- }
- namespaces_.clear();
- }
-
- ForwardDeclarations* AddOrGetNamespace(const string& ns_name) {
- ForwardDeclarations*& ns = namespaces_[ns_name];
- if (ns == nullptr) {
- ns = new ForwardDeclarations;
- }
- return ns;
- }
-
- std::map<string, const Descriptor*>& classes() { return classes_; }
- std::map<string, const EnumDescriptor*>& enums() { return enums_; }
-
- void PrintForwardDeclarations(io::Printer* printer,
- const Options& options) const {
- PrintNestedDeclarations(printer, options);
- PrintTopLevelDeclarations(printer, options);
- }
-
-
- private:
- void PrintNestedDeclarations(io::Printer* printer,
- const Options& options) const {
- PrintDeclarationsInsideNamespace(printer, options);
- for (std::map<string, ForwardDeclarations *>::const_iterator
- it = namespaces_.begin(),
- end = namespaces_.end();
- it != end; ++it) {
- printer->Print("namespace $nsname$ {\n",
- "nsname", it->first);
- it->second->PrintNestedDeclarations(printer, options);
- printer->Print("} // namespace $nsname$\n",
- "nsname", it->first);
- }
- }
-
- void PrintTopLevelDeclarations(io::Printer* printer,
- const Options& options) const {
- PrintDeclarationsOutsideNamespace(printer, options);
- for (std::map<string, ForwardDeclarations *>::const_iterator
- it = namespaces_.begin(),
- end = namespaces_.end();
- it != end; ++it) {
- it->second->PrintTopLevelDeclarations(printer, options);
- }
+ format(
+ "\n"
+ "// @@protoc_insertion_point(namespace_scope)\n");
}
- void PrintDeclarationsInsideNamespace(io::Printer* printer,
- const Options& options) const {
- for (std::map<string, const EnumDescriptor *>::const_iterator
- it = enums_.begin(),
- end = enums_.end();
- it != end; ++it) {
- printer->Print("enum $enumname$ : int;\n", "enumname", it->first);
- printer->Annotate("enumname", it->second);
- printer->Print("bool $enumname$_IsValid(int value);\n", "enumname",
- it->first);
- }
- for (std::map<string, const Descriptor*>::const_iterator
- it = classes_.begin(),
- end = classes_.end();
- it != end; ++it) {
- printer->Print("class $classname$;\n", "classname", it->first);
- printer->Annotate("classname", it->second);
-
- printer->Print(
- "class $classname$DefaultTypeInternal;\n"
- "$dllexport_decl$"
- "extern $classname$DefaultTypeInternal "
- "_$classname$_default_instance_;\n", // NOLINT
- "dllexport_decl",
- 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);
- }
+ {
+ NamespaceOpener proto_ns(ProtobufNamespace(options_), format);
+ for (int i = 0; i < message_generators_.size(); i++) {
+ message_generators_[i]->GenerateSourceInProto2Namespace(printer);
}
}
- void PrintDeclarationsOutsideNamespace(io::Printer* printer,
- const Options& options) const {
- if (classes_.size() == 0) return;
-
- printer->Print(
- "namespace google {\nnamespace protobuf {\n");
- for (std::map<string, const Descriptor*>::const_iterator
- it = classes_.begin(),
- end = classes_.end();
- it != end; ++it) {
- const Descriptor* d = it->second;
- printer->Print(
- "template<> "
- "$dllexport_decl$"
- "$classname$* Arena::CreateMaybeMessage<$classname$>"
- "(Arena*);\n",
- "classname", QualifiedClassName(d), "dllexport_decl",
- options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ");
- }
- printer->Print(
- "} // namespace protobuf\n} // namespace google\n");
- }
+ format(
+ "\n"
+ "// @@protoc_insertion_point(global_scope)\n");
- std::map<string, ForwardDeclarations*> namespaces_;
- std::map<string, const Descriptor*> classes_;
- std::map<string, const EnumDescriptor*> enums_;
-};
+ IncludeFile("net/proto2/public/port_undef.inc", printer);
+}
void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
// 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 ordinarily runs at
@@ -716,39 +710,50 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// in the file.
if (!message_generators_.empty()) {
- printer->Print("::google::protobuf::Metadata file_level_metadata[$size$];\n", "size",
- SimpleItoa(message_generators_.size()));
+ format("::$proto_ns$::Metadata $file_level_metadata$[$1$];\n",
+ message_generators_.size());
+ } else {
+ format(
+ "constexpr ::$proto_ns$::Metadata* $file_level_metadata$ = nullptr;\n");
}
if (!enum_generators_.empty()) {
- printer->Print(
- "const ::google::protobuf::EnumDescriptor* "
- "file_level_enum_descriptors[$size$];\n",
- "size", SimpleItoa(enum_generators_.size()));
+ format(
+ "const ::$proto_ns$::EnumDescriptor* "
+ "$file_level_enum_descriptors$[$1$];\n",
+ enum_generators_.size());
+ } else {
+ format(
+ "constexpr ::$proto_ns$::EnumDescriptor const** "
+ "$file_level_enum_descriptors$ = nullptr;\n");
}
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()));
+ format(
+ "const ::$proto_ns$::ServiceDescriptor* "
+ "$file_level_service_descriptors$[$1$];\n",
+ file_->service_count());
+ } else {
+ format(
+ "constexpr ::$proto_ns$::ServiceDescriptor const** "
+ "$file_level_service_descriptors$ = nullptr;\n");
}
if (!message_generators_.empty()) {
- printer->Print(
+ format(
"\n"
- "const ::google::protobuf::uint32 TableStruct::offsets[] "
- "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
- printer->Indent();
+ "const $uint32$ $tablename$::offsets[] "
+ "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n");
+ format.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(
+ format.Outdent();
+ format(
"};\n"
- "static const ::google::protobuf::internal::MigrationSchema schemas[] "
- "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
- printer->Indent();
+ "static const ::$proto_ns$::internal::MigrationSchema schemas[] "
+ "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n");
+ format.Indent();
{
int offset = 0;
for (int i = 0; i < message_generators_.size(); i++) {
@@ -757,30 +762,33 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
offset += pairs[i].first;
}
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
"\nstatic "
- "::google::protobuf::Message const * const file_default_instances[] = {\n");
- printer->Indent();
+ "::$proto_ns$::Message const * const file_default_instances[] = {\n");
+ format.Indent();
for (int i = 0; i < message_generators_.size(); i++) {
const Descriptor* descriptor = message_generators_[i]->descriptor_;
- printer->Print(
+ format(
"reinterpret_cast<const "
- "::google::protobuf::Message*>(&$ns$::_$classname$_default_instance_),\n",
- "classname", ClassName(descriptor), "ns", Namespace(descriptor));
+ "::$proto_ns$::Message*>(&$1$::_$2$_default_instance_),\n",
+ Namespace(descriptor), // 1
+ ClassName(descriptor)); // 2
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
"\n");
} else {
// we still need these symbols to exist
- printer->Print(
+ format(
// 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* "
+ "const $uint32$ $tablename$::offsets[1] = {};\n"
+ "static constexpr ::$proto_ns$::internal::MigrationSchema* schemas = "
+ "NULL;"
+ "\n"
+ "static constexpr ::$proto_ns$::Message* const* "
"file_default_instances = NULL;\n"
"\n");
}
@@ -790,161 +798,90 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// protobuf_AssignDescriptorsOnce(): The first time it is called, calls
// AssignDescriptors(). All later times, waits for the first call to
// complete and then returns.
- printer->Print(
- "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.
- " AddDescriptors();\n"
- " AssignDescriptors(\n"
- " \"$filename$\", schemas, file_default_instances, "
- "TableStruct::offsets,\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");
- printer->Print(
- "}\n"
- "\n"
- "void protobuf_AssignDescriptorsOnce() {\n"
- " static ::google::protobuf::internal::once_flag once;\n"
- " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n"
- "}\n"
- "\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");
-
- // Only here because of useless string reference that we don't want in
- // protobuf_AssignDescriptorsOnce, because that is called from all the
- // GetMetadata member methods.
- printer->Print(
- "void protobuf_RegisterTypes(const ::std::string&) "
- "GOOGLE_PROTOBUF_ATTRIBUTE_COLD;\n"
- "void protobuf_RegisterTypes(const ::std::string&) {\n"
- " protobuf_AssignDescriptorsOnce();\n");
- printer->Indent();
-
- // All normal messages can be done generically
- if (!message_generators_.empty()) {
- printer->Print(
- "::google::protobuf::internal::RegisterAllTypes(file_level_metadata, $size$);\n",
- "size", SimpleItoa(message_generators_.size()));
- }
+ format(
+ "::$proto_ns$::internal::AssignDescriptorsTable $assign_desc_table$ = "
+ "{\n"
+ " {}, $add_descriptors$, \"$filename$\", schemas,\n"
+ " file_default_instances, $tablename$::offsets,\n"
+ " $file_level_metadata$, $1$, $file_level_enum_descriptors$, "
+ "$file_level_service_descriptors$,\n"
+ "};\n"
+ "\n",
+ message_generators_.size());
+
+ // Now generate the AddDescriptors() function.
+ format(
+ "::$proto_ns$::internal::DescriptorTable $1$ = {\n"
+ " false, $init_defaults$, \n",
+ UniqueName("descriptor_table", file_, options_));
+ format.Indent();
+
+ // Embed the descriptor. We simply serialize the entire
+ // FileDescriptorProto
+ // and embed it as a string literal, which is parsed and built into real
+ // descriptors at initialization time.
+ FileDescriptorProto file_proto;
+ file_->CopyTo(&file_proto);
+ string file_data;
+ file_proto.SerializeToString(&file_data);
- printer->Outdent();
- printer->Print(
- "}\n"
- "\n");
-
- // Now generate the AddDescriptors() function.
- printer->Print(
- "void AddDescriptorsImpl() {\n"
- " InitDefaults();\n");
- printer->Indent();
-
- // Embed the descriptor. We simply serialize the entire
- // FileDescriptorProto
- // and embed it as a string literal, which is parsed and built into real
- // descriptors at initialization time.
- FileDescriptorProto file_proto;
- file_->CopyTo(&file_proto);
- string file_data;
- file_proto.SerializeToString(&file_data);
-
- printer->Print("static const char descriptor[] "
- "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) "
- "= {\n");
- printer->Indent();
-
- 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.
- static const int kBytesPerLine = 25;
- for (int i = 0; i < file_data.size();) {
- for (int j = 0; j < kBytesPerLine && i < file_data.size(); ++i, ++j) {
- printer->Print("'$char$', ", "char",
- CEscape(file_data.substr(i, 1)));
- }
- printer->Print("\n");
- }
- } else {
- // Only write 40 bytes per line.
- static const int kBytesPerLine = 40;
- for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
- printer->Print(" \"$data$\"\n", "data",
- EscapeTrigraphs(CEscape(
- file_data.substr(i, kBytesPerLine))));
- }
+ {
+ // Only write 40 bytes per line.
+ static const int kBytesPerLine = 40;
+ for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
+ format(
+ "\"$1$\"\n",
+ EscapeTrigraphs(CEscape(file_data.substr(i, kBytesPerLine))));
}
-
- printer->Outdent();
- printer->Print("};\n");
- printer->Print(
- "::google::protobuf::DescriptorPool::InternalAddGeneratedFile(\n"
- " descriptor, $size$);\n",
- "size", SimpleItoa(file_data.size()));
-
- // Call MessageFactory::InternalRegisterGeneratedFile().
- printer->Print(
- "::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 file_namespace = FileLevelNamespace(dependency);
- // Call its AddDescriptors function.
- printer->Print("::$file_namespace$::AddDescriptors();\n", "file_namespace",
- file_namespace);
}
- printer->Outdent();
- printer->Print(
- "}\n"
- "\n"
- "void AddDescriptors() {\n"
- " static ::google::protobuf::internal::once_flag once;\n"
- " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n"
- "}\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");
+ format.Outdent();
+ const int num_deps = file_->dependency_count();
+ format(
+ ",\n \"$filename$\", &$assign_desc_table$, $1$,\n"
+ "};\n\n"
+ "void $add_descriptors$() {\n"
+ " static constexpr ::$proto_ns$::internal::InitFunc deps[$2$] =\n"
+ " {\n",
+ file_data.size(), std::max(num_deps, 1));
+ for (int i = 0; i < num_deps; i++) {
+ const FileDescriptor* dependency = file_->dependency(i);
+ format(" ::$1$,\n", UniqueName("AddDescriptors", dependency, options_));
+ }
+ format(
+ " };\n"
+ " ::$proto_ns$::internal::AddDescriptors(&$1$, deps, $2$);\n"
+ "}\n\n",
+ UniqueName("descriptor_table", file_, options_), // 1
+ num_deps); // 2
+ format(
+ "// Force running AddDescriptors() at dynamic initialization time.\n"
+ "static bool $1$ = []() { $add_descriptors$(); return true; }();\n",
+ UniqueName("dynamic_init_dummy", file_, options_));
}
void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
+ Formatter format(printer, variables_);
const string scc_name = ClassName(scc->GetRepresentative());
// We use static and not anonymous namespace because symbol names are
// substantially shorter.
- printer->Print(
- "static void InitDefaults$scc_name$() {\n"
- " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"
- , // awkward comma due to macro
- "scc_name", scc_name);
+ format("static void InitDefaults$1$() {\n",
+ UniqueName(scc_name, scc->GetRepresentative(), options_));
- printer->Indent();
+ if (options_.opensource_runtime) {
+ format(" GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n");
+ }
+ format.Indent();
+
+ if (!options_.opensource_runtime) {
+ for (int i = 0; i < scc->children.size(); i++) {
+ const SCC* child_scc = scc->children[i];
+ const FileDescriptor* dependency = child_scc->GetRepresentative()->file();
+ if (!IsProto1(dependency, options_)) continue;
+ format("$1$();\n", UniqueName("InitDefaults", dependency, options_));
+ }
+ }
// First construct all the necessary default instances.
for (int i = 0; i < message_generators_.size(); i++) {
@@ -954,17 +891,18 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
// TODO(gerbens) This requires this function to be friend. Remove
// the need for this.
message_generators_[i]->GenerateFieldDefaultInstances(printer);
- printer->Print(
+ format(
"{\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(
+ " void* ptr = &$1$::_$2$_default_instance_;\n"
+ " new (ptr) $1$::$2$();\n",
+ Namespace(message_generators_[i]->descriptor_), // 1
+ ClassName(message_generators_[i]->descriptor_)); // 2
+ if (options_.opensource_runtime &&
+ !IsMapEntryMessage(message_generators_[i]->descriptor_)) {
+ format(
" ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);\n");
}
- printer->Print("}\n");
+ format("}\n");
}
// TODO(gerbens) make default instances be the same as normal instances.
@@ -974,37 +912,44 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
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(
- "$dllexport_decl$::google::protobuf::internal::SCCInfo<$size$> "
- "scc_info_$scc_name$ =\n"
- " {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), "
- "$size$, InitDefaults$scc_name$}, {",
- "size", SimpleItoa(scc->children.size()), "scc_name",
- ClassName(scc->GetRepresentative()), "dllexport_decl",
- options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
+ format("$1$::InitAsDefaultInstance();\n",
+ QualifiedClassName(message_generators_[i]->descriptor_));
+ }
+ format.Outdent();
+ format("}\n\n");
+
+ format(
+ "$dllexport_decl $::$proto_ns$::internal::SCCInfo<$1$> "
+ "scc_info_$2$ =\n"
+ " "
+ "{{ATOMIC_VAR_INIT(::$proto_ns$::internal::SCCInfoBase::kUninitialized), "
+ "$1$, InitDefaults$2$}, {",
+ scc->children.size(), // 1
+ UniqueName(ClassName(scc->GetRepresentative()), scc->GetRepresentative(),
+ options_));
for (const SCC* child : scc->children) {
auto repr = child->GetRepresentative();
- printer->Print("\n &$ns$::scc_info_$child$.base,", "ns",
- FileLevelNamespace(repr), "child", ClassName(repr));
+ if (IsProto1(repr->file(), options_)) {
+ GOOGLE_CHECK(!options_.opensource_runtime);
+ format("\n nullptr,");
+ continue;
+ }
+ format("\n &scc_info_$1$.base,",
+ UniqueName(ClassName(repr), repr, options_));
}
- printer->Print("}};\n\n");
+ format("}};\n\n");
}
void FileGenerator::GenerateTables(io::Printer* printer) {
+ Formatter format(printer, variables_);
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();
+ format(
+ "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTableField\n"
+ " const $tablename$::entries[] "
+ "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n");
+ format.Indent();
std::vector<size_t> entries;
size_t count = 0;
@@ -1016,17 +961,18 @@ void FileGenerator::GenerateTables(io::Printer* printer) {
// 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");
+ format("{0, 0, 0, ::$proto_ns$::internal::kInvalidMask, 0, 0},\n");
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
"\n"
- "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField\n"
- " const TableStruct::aux[] "
- "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
- printer->Indent();
+ "PROTOBUF_CONSTEXPR_VAR "
+ "::$proto_ns$::internal::AuxillaryParseTableField\n"
+ " const $tablename$::aux[] "
+ "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n");
+ format.Indent();
std::vector<size_t> aux_entries;
count = 0;
@@ -1037,16 +983,16 @@ void FileGenerator::GenerateTables(io::Printer* printer) {
}
if (count == 0) {
- printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
- "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const\n"
- " TableStruct::schema[] "
- "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n");
- printer->Indent();
+ "PROTOBUF_CONSTEXPR_VAR ::$proto_ns$::internal::ParseTable const\n"
+ " $tablename$::schema[] "
+ "PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {\n");
+ format.Indent();
size_t offset = 0;
size_t aux_offset = 0;
@@ -1057,20 +1003,21 @@ void FileGenerator::GenerateTables(io::Printer* printer) {
}
if (message_generators_.empty()) {
- printer->Print("{ NULL, NULL, 0, -1, -1, false },\n");
+ format("{ NULL, NULL, 0, -1, -1, false },\n");
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
"\n");
}
if (!message_generators_.empty() && options_.table_driven_serialization) {
- printer->Print(
- "const ::google::protobuf::internal::FieldMetadata TableStruct::field_metadata[] "
+ format(
+ "const ::$proto_ns$::internal::FieldMetadata "
+ "$tablename$::field_metadata[] "
"= {\n");
- printer->Indent();
+ format.Indent();
std::vector<int> field_metadata_offsets;
int idx = 0;
for (int i = 0; i < message_generators_.size(); i++) {
@@ -1078,12 +1025,12 @@ void FileGenerator::GenerateTables(io::Printer* printer) {
idx += message_generators_[i]->GenerateFieldMetadata(printer);
}
field_metadata_offsets.push_back(idx);
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
- "const ::google::protobuf::internal::SerializationTable "
- "TableStruct::serialization_table[] = {\n");
- printer->Indent();
+ "const ::$proto_ns$::internal::SerializationTable "
+ "$tablename$::serialization_table[] = {\n");
+ format.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.
@@ -1092,235 +1039,327 @@ void FileGenerator::GenerateTables(io::Printer* printer) {
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]));
+ format("{$1$, $tablename$::field_metadata + $2$},\n",
+ field_metadata_offsets[i + 1] - field_metadata_offsets[i], // 1
+ field_metadata_offsets[i]); // 2
}
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"};\n"
"\n");
}
}
-void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
- ForwardDeclarations decls;
- FillForwardDeclarations(&decls);
- decls.PrintForwardDeclarations(printer, options_);
+class FileGenerator::ForwardDeclarations {
+ public:
+ void AddMessage(const Descriptor* d) { classes_[ClassName(d)] = d; }
+ void AddEnum(const EnumDescriptor* d) { enums_[ClassName(d)] = d; }
+
+ void Print(const Formatter& format, const Options& options) const {
+ for (const auto& p : enums_) {
+ const string& enumname = p.first;
+ const EnumDescriptor* enum_desc = p.second;
+ format(
+ "enum ${1$$2$$}$ : int;\n"
+ "bool $2$_IsValid(int value);\n",
+ enum_desc, enumname);
+ }
+ for (const auto& p : classes_) {
+ const string& classname = p.first;
+ const Descriptor* class_desc = p.second;
+ format(
+ "class ${1$$2$$}$;\n"
+ "class $2$DefaultTypeInternal;\n"
+ "$dllexport_decl $extern "
+ "$2$DefaultTypeInternal _$2$_default_instance_;\n",
+ class_desc, classname);
+ if (options.lite_implicit_weak_fields) {
+ format("void $1$_ReferenceStrong();\n", classname);
+ }
+ }
+ }
+
+ void PrintTopLevelDecl(const Formatter& format) const {
+ for (const auto& pair : classes_) {
+ format(
+ "template<> $dllexport_decl $"
+ "$1$* Arena::CreateMaybeMessage<$1$>(Arena*);\n",
+ QualifiedClassName(pair.second));
+ }
+ }
+
+ private:
+ std::map<string, const Descriptor*> classes_;
+ std::map<string, const EnumDescriptor*> enums_;
+};
+
+static void PublicImportDFS(const FileDescriptor* fd,
+ std::unordered_set<const FileDescriptor*>* fd_set) {
+ for (int i = 0; i < fd->public_dependency_count(); i++) {
+ const FileDescriptor* dep = fd->public_dependency(i);
+ if (fd_set->insert(dep).second) PublicImportDFS(dep, fd_set);
+ }
}
-void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) {
- for (int i = 0; i < package_parts_.size(); i++) {
- decls = decls->AddOrGetNamespace(package_parts_[i]);
+void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
+ Formatter format(printer, variables_);
+ std::vector<const Descriptor*> classes;
+ std::vector<const EnumDescriptor*> enums;
+
+ FlattenMessagesInFile(file_, &classes); // All messages need forward decls.
+
+ if (options_.proto_h) { // proto.h needs extra forward declarations.
+ // All classes / enums refered to as field members
+ std::vector<const FieldDescriptor*> fields;
+ ListAllFields(file_, &fields);
+ for (int i = 0; i < fields.size(); i++) {
+ classes.push_back(fields[i]->containing_type());
+ classes.push_back(fields[i]->message_type());
+ enums.push_back(fields[i]->enum_type());
+ }
+ ListAllTypesForServices(file_, &classes);
}
- // Generate enum definitions.
- for (int i = 0; i < enum_generators_.size(); i++) {
- enum_generators_[i]->FillForwardDeclaration(&decls->enums());
+
+ // Calculate the set of files whose definitions we get through include.
+ // No need to forward declare types that are defined in these.
+ std::unordered_set<const FileDescriptor*> public_set;
+ PublicImportDFS(file_, &public_set);
+
+ std::map<string, ForwardDeclarations> decls;
+ for (int i = 0; i < classes.size(); i++) {
+ const Descriptor* d = classes[i];
+ if (d && !public_set.count(d->file())) decls[Namespace(d)].AddMessage(d);
}
- // Generate forward declarations of classes.
- for (int i = 0; i < message_generators_.size(); i++) {
- message_generators_[i]->FillMessageForwardDeclarations(
- &decls->classes());
+ for (int i = 0; i < enums.size(); i++) {
+ const EnumDescriptor* d = enums[i];
+ if (d && !public_set.count(d->file())) decls[Namespace(d)].AddEnum(d);
+ }
+
+
+ NamespaceOpener ns(format);
+ for (const auto& pair : decls) {
+ ns.ChangeTo(pair.first);
+ pair.second.Print(format, options_);
+ }
+ ns.ChangeTo(variables_["proto_ns"]);
+ for (const auto& pair : decls) {
+ pair.second.PrintTopLevelDecl(format);
}
}
void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
const string& filename_identifier) {
+ Formatter format(printer, variables_);
// Generate top of header.
- printer->Print(
+ format(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
- "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n"
- "#define PROTOBUF_INCLUDED_$filename_identifier$\n"
+ "#ifndef PROTOBUF_INCLUDED_$1$\n"
+ "#define PROTOBUF_INCLUDED_$1$\n"
"\n"
+ "#include <limits>\n"
"#include <string>\n",
- "filename", file_->name(), "filename_identifier", filename_identifier);
- printer->Print("\n");
+ filename_identifier);
+ if (!options_.opensource_runtime && !enum_generators_.empty()) {
+ // Add header to provide std::is_integral for safe Enum_Name() function.
+ format("#include <type_traits>\n");
+ }
+ format("\n");
}
void FileGenerator::GenerateBottomHeaderGuard(
io::Printer* printer, const string& filename_identifier) {
- printer->Print(
- "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n",
- "filename_identifier", filename_identifier);
+ Formatter format(printer, variables_);
+ format("#endif // PROTOBUF_INCLUDED_$1$\n", filename_identifier);
}
void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (UsingImplicitWeakFields(file_, options_)) {
- printer->Print("#include <google/protobuf/implicit_weak_message.h>\n");
- }
-
- printer->Print(
- "#include <google/protobuf/stubs/common.h>\n"
- "\n");
-
- // Verify the protobuf library header version is compatible with the protoc
- // version before going any further.
- printer->Print(
- "#if GOOGLE_PROTOBUF_VERSION < $min_header_version$\n"
- "#error This file was generated by a newer version of protoc which is\n"
- "#error incompatible with your Protocol Buffer headers. Please update\n"
- "#error your headers.\n"
- "#endif\n"
- "#if $protoc_version$ < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION\n"
- "#error This file was generated by an older version of protoc which is\n"
- "#error incompatible with your Protocol Buffer headers. Please\n"
- "#error regenerate this file with a newer version of protoc.\n"
- "#endif\n"
- "\n",
- "min_header_version",
- SimpleItoa(protobuf::internal::kMinHeaderVersionForProtoc),
- "protoc_version", SimpleItoa(GOOGLE_PROTOBUF_VERSION));
+ IncludeFile("net/proto2/public/implicit_weak_message.h", printer);
+ }
+ if (HasWeakFields(file_, options_)) {
+ GOOGLE_CHECK(!options_.opensource_runtime);
+ IncludeFile("net/proto2/public/weak_field_map.h", printer);
+ }
+ if (HasLazyFields(file_, options_)) {
+ GOOGLE_CHECK(!options_.opensource_runtime);
+ IncludeFile("net/proto2/public/lazy_field.h", printer);
+ }
+
+ if (options_.opensource_runtime) {
+ // Verify the protobuf library header version is compatible with the protoc
+ // version before going any further.
+ IncludeFile("net/proto2/public/port_def.inc", printer);
+ format(
+ "#if PROTOBUF_VERSION < $1$\n"
+ "#error This file was generated by a newer version of protoc which is\n"
+ "#error incompatible with your Protocol Buffer headers. Please update\n"
+ "#error your headers.\n"
+ "#endif\n"
+ "#if $2$ < PROTOBUF_MIN_PROTOC_VERSION\n"
+ "#error This file was generated by an older version of protoc which "
+ "is\n"
+ "#error incompatible with your Protocol Buffer headers. Please\n"
+ "#error regenerate this file with a newer version of protoc.\n"
+ "#endif\n"
+ "\n",
+ PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC, // 1
+ PROTOBUF_VERSION); // 2
+ IncludeFile("net/proto2/public/port_undef.inc", printer);
+ }
// OK, it's now safe to #include other files.
- printer->Print(
- "#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"
- "#include <google/protobuf/inlined_string_field.h>\n");
-
+ IncludeFile("net/proto2/io/public/coded_stream.h", printer);
+ IncludeFile("net/proto2/public/arena.h", printer);
+ IncludeFile("net/proto2/public/arenastring.h", printer);
+ IncludeFile("net/proto2/public/generated_message_table_driven.h", printer);
+ IncludeFile("net/proto2/public/generated_message_util.h", printer);
+ IncludeFile("net/proto2/public/inlined_string_field.h", printer);
if (HasDescriptorMethods(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/metadata.h>\n");
+ IncludeFile("net/proto2/public/metadata.h", printer);
} else {
- printer->Print(
- "#include <google/protobuf/metadata_lite.h>\n");
+ IncludeFile("net/proto2/public/metadata_lite.h", printer);
}
if (!message_generators_.empty()) {
if (HasDescriptorMethods(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/message.h>\n");
+ IncludeFile("net/proto2/public/message.h", printer);
} else {
- printer->Print(
- "#include <google/protobuf/message_lite.h>\n");
+ IncludeFile("net/proto2/public/message_lite.h", printer);
+ }
+ }
+ if (options_.opensource_runtime) {
+ // Open-source relies on unconditional includes of these.
+ IncludeFileAndExport("net/proto2/public/repeated_field.h", printer);
+ IncludeFileAndExport("net/proto2/public/extension_set.h", printer);
+ } else {
+ // Google3 includes these files only when they are necessary.
+ if (HasExtensionsOrExtendableMessage(file_)) {
+ IncludeFileAndExport("net/proto2/public/extension_set.h", printer);
+ }
+ if (HasRepeatedFields(file_)) {
+ IncludeFileAndExport("net/proto2/public/repeated_field.h", printer);
+ }
+ if (HasStringPieceFields(file_, options_)) {
+ IncludeFile("net/proto2/public/string_piece_field_support.h", printer);
+ }
+ if (HasCordFields(file_, options_)) {
+ format("#include \"third_party/absl/strings/cord.h\"\n");
}
}
- printer->Print(
- "#include <google/protobuf/repeated_field.h>"
- " // IWYU pragma: export\n"
- "#include <google/protobuf/extension_set.h>"
- " // IWYU pragma: export\n");
if (HasMapFields(file_)) {
- printer->Print(
- "#include <google/protobuf/map.h>"
- " // IWYU pragma: export\n");
+ IncludeFileAndExport("net/proto2/public/map.h", printer);
if (HasDescriptorMethods(file_, options_)) {
- printer->Print("#include <google/protobuf/map_entry.h>\n");
- printer->Print("#include <google/protobuf/map_field_inl.h>\n");
+ IncludeFile("net/proto2/public/map_entry.h", printer);
+ IncludeFile("net/proto2/public/map_field_inl.h", printer);
} else {
- printer->Print("#include <google/protobuf/map_entry_lite.h>\n");
- printer->Print("#include <google/protobuf/map_field_lite.h>\n");
+ IncludeFile("net/proto2/public/map_entry_lite.h", printer);
+ IncludeFile("net/proto2/public/map_field_lite.h", printer);
}
}
if (HasEnumDefinitions(file_)) {
if (HasDescriptorMethods(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/generated_enum_reflection.h>\n");
+ IncludeFile("net/proto2/public/generated_enum_reflection.h", printer);
} else {
- printer->Print(
- "#include <google/protobuf/generated_enum_util.h>\n");
+ IncludeFile("net/proto2/public/generated_enum_util.h", printer);
}
}
if (HasGenericServices(file_, options_)) {
- printer->Print(
- "#include <google/protobuf/service.h>\n");
+ IncludeFile("net/proto2/public/service.h", printer);
}
if (UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) {
- printer->Print(
- "#include <google/protobuf/unknown_field_set.h>\n");
+ IncludeFile("net/proto2/public/unknown_field_set.h", printer);
}
-
if (IsAnyMessage(file_)) {
- printer->Print(
- "#include <google/protobuf/any.h>\n");
+ IncludeFile("net/proto2/internal/any.h", printer);
}
}
void FileGenerator::GenerateMetadataPragma(io::Printer* printer,
const string& info_path) {
+ Formatter format(printer, variables_);
if (!info_path.empty() && !options_.annotation_pragma_name.empty() &&
!options_.annotation_guard_name.empty()) {
- printer->Print(
+ format.Set("guard", options_.annotation_guard_name);
+ format.Set("pragma", options_.annotation_pragma_name);
+ format.Set("info_path", info_path);
+ format(
"#ifdef $guard$\n"
"#pragma $pragma$ \"$info_path$\"\n"
- "#endif // $guard$\n",
- "guard", options_.annotation_guard_name, "pragma",
- options_.annotation_pragma_name, "info_path", info_path);
+ "#endif // $guard$\n");
}
}
void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) {
- 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());
- }
-
+ Formatter format(printer, variables_);
for (int i = 0; i < file_->dependency_count(); i++) {
- const bool use_system_include = IsWellKnownMessage(file_->dependency(i));
- const string& name = file_->dependency(i)->name();
- bool public_import = (public_import_names.count(name) != 0);
- string basename = StripProto(name);
+ string basename = StripProto(file_->dependency(i)->name());
+
+ // Do not import weak deps.
+ if (IsDepWeak(file_->dependency(i))) continue;
+ if (IsBootstrapProto(options_, file_)) {
+ GetBootstrapBasename(options_, basename, &basename);
+ }
- printer->Print(
- "#include $left$$dependency$.pb.h$right$$iwyu$\n",
- "dependency", basename,
- "iwyu", (public_import) ? " // IWYU pragma: export" : "",
- "left", use_system_include ? "<" : "\"",
- "right", use_system_include ? ">" : "\"");
+ format("#include $1$\n",
+ CreateHeaderInclude(basename + ".pb.h", file_->dependency(i)));
}
}
void FileGenerator::GenerateGlobalStateFunctionDeclarations(
io::Printer* printer) {
-// Forward-declare the AddDescriptors, InitDefaults because these are called
-// by .pb.cc files depending on this file.
- printer->Print(
+ Formatter format(printer, variables_);
+ // Forward-declare the AddDescriptors, InitDefaults because these are called
+ // by .pb.cc files depending on this file.
+ //
+ // The TableStruct is also outputted in weak_message_field.cc, because the
+ // weak fields must refer to table struct but cannot include the header.
+ // Also it annotates extra weak attributes.
+ // TODO(gerbens) make sure this situation is handled better.
+ format(
"\n"
- "namespace $file_namespace$ {\n"
"// Internal implementation detail -- do not use these members.\n"
- "struct $dllexport_decl$TableStruct {\n"
+ "struct $dllexport_decl $$tablename$ {\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 "
+ " static const ::$proto_ns$::internal::ParseTableField entries[]\n"
+ " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n"
+ " static const ::$proto_ns$::internal::AuxillaryParseTableField aux[]\n"
+ " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n"
+ " static const ::$proto_ns$::internal::ParseTable schema[$1$]\n"
+ " PROTOBUF_SECTION_VARIABLE(protodesc_cold);\n"
+ " static const ::$proto_ns$::internal::FieldMetadata field_metadata[];\n"
+ " static const ::$proto_ns$::internal::SerializationTable "
"serialization_table[];\n"
- " static const ::google::protobuf::uint32 offsets[];\n"
+ " static const $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())));
+ 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 + " ");
+ format("void $dllexport_decl $$add_descriptors$();\n");
+ if (!options_.opensource_runtime) {
+ // TODO(gerbens) This is for proto1 interoperability. Remove when proto1
+ // is gone.
+ format("void $dllexport_decl $$init_defaults$();\n");
+ }
}
- printer->Print(
- "} // namespace $file_namespace$\n",
- "file_namespace", FileLevelNamespace(file_));
}
void FileGenerator::GenerateMessageDefinitions(io::Printer* printer) {
+ Formatter format(printer, variables_);
// Generate class definitions.
for (int i = 0; i < message_generators_.size(); i++) {
if (i > 0) {
- printer->Print("\n");
- printer->Print(kThinSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThinSeparator);
+ format("\n");
}
message_generators_[i]->GenerateClassDefinition(printer);
}
@@ -1334,74 +1373,77 @@ void FileGenerator::GenerateEnumDefinitions(io::Printer* printer) {
}
void FileGenerator::GenerateServiceDefinitions(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (HasGenericServices(file_, options_)) {
// Generate service definitions.
for (int i = 0; i < service_generators_.size(); i++) {
if (i > 0) {
- printer->Print("\n");
- printer->Print(kThinSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThinSeparator);
+ format("\n");
}
service_generators_[i]->GenerateDeclarations(printer);
}
- printer->Print("\n");
- printer->Print(kThickSeparator);
- printer->Print("\n");
+ format("\n");
+ format(kThickSeparator);
+ format("\n");
}
}
void FileGenerator::GenerateExtensionIdentifiers(io::Printer* printer) {
// Declare extension identifiers. These are in global scope and so only
// the global scope extensions.
- for (int i = 0; i < file_->extension_count(); i++) {
- extension_generators_owner_[i]->GenerateDeclaration(printer);
+ for (auto& extension_generator : extension_generators_) {
+ if (extension_generator->IsScoped()) continue;
+ extension_generator->GenerateDeclaration(printer);
}
}
void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) {
+ Formatter format(printer, variables_);
// 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");
+ format(
+ "#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");
+ format(kThinSeparator);
+ format("\n");
}
message_generators_[i]->GenerateInlineMethods(printer);
}
- printer->Print(
- "#ifdef __GNUC__\n"
- " #pragma GCC diagnostic pop\n"
- "#endif // __GNUC__\n");
+ format(
+ "#ifdef __GNUC__\n"
+ " #pragma GCC diagnostic pop\n"
+ "#endif // __GNUC__\n");
for (int i = 0; i < message_generators_.size(); i++) {
if (i > 0) {
- printer->Print(kThinSeparator);
- printer->Print("\n");
+ format(kThinSeparator);
+ format("\n");
}
}
}
void FileGenerator::GenerateProto2NamespaceEnumSpecializations(
io::Printer* printer) {
+ Formatter format(printer, variables_);
// Emit GetEnumDescriptor specializations into google::protobuf namespace:
if (HasEnumDefinitions(file_)) {
- printer->Print(
- "\n"
- "namespace google {\nnamespace protobuf {\n"
- "\n");
- for (int i = 0; i < enum_generators_.size(); i++) {
- enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
+ format("\n");
+ {
+ NamespaceOpener proto_ns(ProtobufNamespace(options_), format);
+ format("\n");
+ for (int i = 0; i < enum_generators_.size(); i++) {
+ enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
+ }
+ format("\n");
}
- printer->Print(
- "\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 94da9a14..315cf139 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.h
+++ b/src/google/protobuf/compiler/cpp/cpp_file.h
@@ -44,23 +44,26 @@
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/compiler/scc.h>
namespace google {
namespace protobuf {
- class FileDescriptor; // descriptor.h
- namespace io {
- class Printer; // printer.h
- }
+class FileDescriptor; // descriptor.h
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
-class EnumGenerator; // enum.h
-class MessageGenerator; // message.h
-class ServiceGenerator; // service.h
-class ExtensionGenerator; // extension.h
+class EnumGenerator; // enum.h
+class MessageGenerator; // message.h
+class ServiceGenerator; // service.h
+class ExtensionGenerator; // extension.h
class FileGenerator {
public:
@@ -71,14 +74,12 @@ class FileGenerator {
// Shared code between the two header generators below.
void GenerateHeader(io::Printer* printer);
- // info_path, if non-empty, should be the path (relative to printer's output)
- // to the metadata file describing this proto header.
- void GenerateProtoHeader(io::Printer* printer,
- const string& info_path);
- // info_path, if non-empty, should be the path (relative to printer's output)
- // to the metadata file describing this PB header.
- void GeneratePBHeader(io::Printer* printer,
- const string& info_path);
+ // info_path, if non-empty, should be the path (relative to printer's
+ // output) to the metadata file describing this proto header.
+ void GenerateProtoHeader(io::Printer* printer, const std::string& info_path);
+ // info_path, if non-empty, should be the path (relative to printer's
+ // output) to the metadata file describing this PB header.
+ void GeneratePBHeader(io::Printer* printer, const std::string& info_path);
void GenerateSource(io::Printer* printer);
int NumMessages() const { return message_generators_.size(); }
@@ -90,6 +91,20 @@ class FileGenerator {
// Internal type used by GenerateForwardDeclarations (defined in file.cc).
class ForwardDeclarations;
+ void IncludeFile(const std::string& google3_name, io::Printer* printer) {
+ DoIncludeFile(google3_name, false, printer);
+ }
+ void IncludeFileAndExport(const std::string& google3_name, io::Printer* printer) {
+ DoIncludeFile(google3_name, true, printer);
+ }
+ void DoIncludeFile(const std::string& google3_name, bool do_export,
+ io::Printer* printer);
+
+ std::string CreateHeaderInclude(const std::string& basename,
+ const FileDescriptor* file);
+ void GenerateInternalForwardDeclarations(
+ const std::vector<const FieldDescriptor*>& fields, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer, io::Printer* printer);
void GenerateSourceIncludes(io::Printer* printer);
void GenerateSourceDefaultInstance(int idx, io::Printer* printer);
@@ -100,16 +115,11 @@ class FileGenerator {
// For other imports, generates their forward-declarations.
void GenerateForwardDeclarations(io::Printer* printer);
- // Internal helper used by GenerateForwardDeclarations: fills 'decls'
- // with all necessary forward-declarations for this file and its
- // transient depednencies.
- void FillForwardDeclarations(ForwardDeclarations* decls);
-
// Generates top or bottom of a header file.
void GenerateTopHeaderGuard(io::Printer* printer,
- const string& filename_identifier);
+ const std::string& filename_identifier);
void GenerateBottomHeaderGuard(io::Printer* printer,
- const string& filename_identifier);
+ const std::string& filename_identifier);
// Generates #include directives.
void GenerateLibraryIncludes(io::Printer* printer);
@@ -117,7 +127,7 @@ class FileGenerator {
// Generate a pragma to pull in metadata using the given info_path (if
// non-empty). info_path should be relative to printer's output.
- void GenerateMetadataPragma(io::Printer* printer, const string& info_path);
+ void GenerateMetadataPragma(io::Printer* printer, const std::string& info_path);
// Generates a couple of different pieces before definitions:
void GenerateGlobalStateFunctionDeclarations(io::Printer* printer);
@@ -138,13 +148,13 @@ 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.
+ // 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) {
@@ -157,30 +167,29 @@ class FileGenerator {
return scc_analyzer_.GetSCC(d);
}
+ bool IsDepWeak(const FileDescriptor* dep) const {
+ if (weak_deps_.count(dep) != 0) {
+ GOOGLE_CHECK(!options_.opensource_runtime);
+ return true;
+ }
+ return false;
+ }
+
+ std::set<const FileDescriptor*> weak_deps_;
const FileDescriptor* file_;
const Options options_;
- SCCAnalyzer scc_analyzer_;
+ MessageSCCAnalyzer scc_analyzer_;
+ std::map<std::string, std::string> variables_;
// 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_;
- std::vector<EnumGenerator*> enum_generators_;
- std::vector<ServiceGenerator*> service_generators_;
- std::vector<ExtensionGenerator*> extension_generators_;
-
- // These members are just for owning (and thus proper deleting).
- // Nested (enum/extension)_generators are owned by child messages.
- std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_owner_;
- std::unique_ptr<std::unique_ptr<ServiceGenerator> []>
- service_generators_owner_;
- std::unique_ptr<std::unique_ptr<ExtensionGenerator> []>
- extension_generators_owner_;
-
- // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
- std::vector<string> package_parts_;
+ std::vector<std::unique_ptr<MessageGenerator>> message_generators_;
+ std::vector<std::unique_ptr<EnumGenerator>> enum_generators_;
+ std::vector<std::unique_ptr<ServiceGenerator>> service_generators_;
+ std::vector<std::unique_ptr<ExtensionGenerator>> extension_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator);
};
@@ -188,6 +197,6 @@ class FileGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/cpp_generator.cc
index 20bb8a1a..0e7e4dfd 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.cc
@@ -77,6 +77,21 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// __declspec(dllimport) depending on what is being compiled.
//
Options file_options;
+
+ switch (runtime_) {
+ case Runtime::kGoogle3:
+ file_options.opensource_runtime = false;
+ break;
+ case Runtime::kOpensource:
+ file_options.opensource_runtime = true;
+ file_options.opensource_include_paths = true;
+ break;
+ case Runtime::kOpensourceGoogle3:
+ file_options.opensource_runtime = true;
+ file_options.opensource_include_paths = false;
+ break;
+ }
+
for (int i = 0; i < options.size(); i++) {
if (options[i].first == "dllexport_decl") {
file_options.dllexport_decl = options[i].second;
@@ -108,7 +123,7 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// The safe_boundary_check option controls behavior for Google-internal
// protobuf APIs.
- if (file_options.safe_boundary_check) {
+ if (file_options.safe_boundary_check && file_options.opensource_runtime) {
*error =
"The safe_boundary_check option is not supported outside of Google.";
return false;
@@ -119,6 +134,10 @@ bool CppGenerator::Generate(const FileDescriptor* file,
string basename = StripProto(file->name());
+ if (MaybeBootstrap(file_options, generator_context, file_options.bootstrap,
+ &basename)) {
+ return true;
+ }
FileGenerator file_generator(file, file_options);
@@ -163,32 +182,41 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// Generate cc file(s).
if (UsingImplicitWeakFields(file, file_options)) {
- {
- // This is the global .cc file, containing enum/services/tables/reflection
+ if (file->name() == "net/proto2/proto/descriptor.proto") {
+ // If we are building with implicit weak fields then we do not want to
+ // produce any symbols for descriptor.proto, so we just create an empty
+ // pb.cc file.
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.cc"));
- io::Printer printer(output.get(), '$');
- file_generator.GenerateGlobalSource(&printer);
- }
+ } else {
+ {
+ // This is the global .cc file, containing
+ // enum/services/tables/reflection
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(basename + ".pb.cc"));
+ io::Printer printer(output.get(), '$');
+ file_generator.GenerateGlobalSource(&printer);
+ }
- int num_cc_files = file_generator.NumMessages();
+ int num_cc_files = file_generator.NumMessages();
- // If we're using implicit weak fields then we allow the user to optionally
- // specify how many files to generate, not counting the global pb.cc file.
- // If we have more files than messages, then some files will be generated as
- // empty placeholders.
- if (file_options.num_cc_files > 0) {
- GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files)
- << "There must be at least as many numbered .cc files as messages.";
- num_cc_files = file_options.num_cc_files;
- }
- for (int i = 0; i < num_cc_files; i++) {
- // TODO(gerbens) Agree on naming scheme.
- std::unique_ptr<io::ZeroCopyOutputStream> output(
- generator_context->Open(basename + "." + SimpleItoa(i) + ".cc"));
- io::Printer printer(output.get(), '$');
- if (i < file_generator.NumMessages()) {
- file_generator.GenerateSourceForMessage(i, &printer);
+ // If we're using implicit weak fields then we allow the user to
+ // optionally specify how many files to generate, not counting the global
+ // pb.cc file. If we have more files than messages, then some files will
+ // be generated as empty placeholders.
+ if (file_options.num_cc_files > 0) {
+ GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files)
+ << "There must be at least as many numbered .cc files as messages.";
+ num_cc_files = file_options.num_cc_files;
+ }
+ for (int i = 0; i < num_cc_files; i++) {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(basename + ".out/" +
+ SimpleItoa(i) + ".cc"));
+ io::Printer printer(output.get(), '$');
+ if (i < file_generator.NumMessages()) {
+ file_generator.GenerateSourceForMessage(i, &printer);
+ }
}
}
} else {
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.h b/src/google/protobuf/compiler/cpp/cpp_generator.h
index 3d517cf4..30363e73 100644
--- a/src/google/protobuf/compiler/cpp/cpp_generator.h
+++ b/src/google/protobuf/compiler/cpp/cpp_generator.h
@@ -40,6 +40,8 @@
#include <string>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -49,24 +51,41 @@ namespace cpp {
// header. If you create your own protocol compiler binary and you want
// it to support C++ output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator {
+class PROTOC_EXPORT CppGenerator : public CodeGenerator {
public:
CppGenerator();
~CppGenerator();
+ enum class Runtime {
+ kGoogle3, // Use the internal google3 runtime.
+ kOpensource, // Use the open-source runtime.
+
+ // Use the open-source runtime with google3 #include paths. We make these
+ // absolute to avoid ambiguity, so the runtime will be #included like:
+ // #include "third_party/protobuf/<...>/google/protobuf/message.h"
+ kOpensourceGoogle3
+ };
+
+ void set_runtime(Runtime runtime) {
+ runtime_ = runtime;
+ }
+
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* generator_context,
- string* error) const;
+ std::string* error) const;
private:
+ Runtime runtime_ = Runtime::kOpensource;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CppGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
index 163dac0a..472c55f4 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
@@ -32,22 +32,28 @@
// 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 <unordered_set>
#include <vector>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
+#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/wire_format.h>
+#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/hash.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -83,15 +89,15 @@ const char* const kKeywordList[] = {
"while", "xor", "xor_eq"
};
-hash_set<string> MakeKeywordsMap() {
- hash_set<string> result;
+std::unordered_set<string> MakeKeywordsMap() {
+ std::unordered_set<string> result;
for (int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) {
result.insert(kKeywordList[i]);
}
return result;
}
-hash_set<string> kKeywords = MakeKeywordsMap();
+std::unordered_set<string> kKeywords = MakeKeywordsMap();
// Returns whether the provided descriptor has an extension. This includes its
// nested types.
@@ -131,8 +137,55 @@ string Base63(I n, int k) {
return res;
}
+string IntTypeName(const Options& options, const string& type) {
+ if (options.opensource_runtime) {
+ return "::google::protobuf::" + type;
+ } else {
+ return "::" + type;
+ }
+}
+
+string StringTypeName(const Options& options) {
+ return options.opensource_runtime ? "::std::string" : "::std::string";
+}
+
+void SetIntVar(const Options& options, const string& type,
+ std::map<string, string>* variables) {
+ (*variables)[type] = IntTypeName(options, type);
+}
+
} // namespace
+void SetCommonVars(const Options& options,
+ std::map<string, string>* variables) {
+ (*variables)["proto_ns"] = ProtobufNamespace(options);
+
+ // Warning: there is some clever naming/splitting here to avoid extract script
+ // rewrites. The names of these variables must not be things that the extract
+ // script will rewrite. That's why we use "CHK" (for example) instead of
+ // "GOOGLE_CHECK".
+ if (options.opensource_runtime) {
+ (*variables)["GOOGLE_PROTOBUF"] = "GOOGLE_PROTOBUF";
+ (*variables)["CHK"] = "GOOGLE_CHECK";
+ (*variables)["DCHK"] = "GOOGLE_DCHECK";
+ } else {
+ // These values are things the extract script would rewrite if we did not
+ // split them. It might not strictly matter since we don't generate google3
+ // code in open-source. But it's good to prevent surprising things from
+ // happening.
+ (*variables)["GOOGLE_PROTOBUF"] = "GOOGLE3" "_PROTOBUF";
+ (*variables)["CHK"] = "CH" "ECK";
+ (*variables)["DCHK"] = "DCH" "ECK";
+ }
+
+ SetIntVar(options, "uint8", variables);
+ SetIntVar(options, "uint32", variables);
+ SetIntVar(options, "uint64", variables);
+ SetIntVar(options, "int32", variables);
+ SetIntVar(options, "int64", variables);
+ (*variables)["string"] = StringTypeName(options);
+}
+
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
string result;
// Note: I distrust ctype.h due to locales.
@@ -205,11 +258,25 @@ string ClassName(const EnumDescriptor* enum_descriptor) {
}
}
+string QualifiedClassName(const Descriptor* d) {
+ return Namespace(d) + "::" + ClassName(d);
+}
+
+string QualifiedClassName(const EnumDescriptor* d) {
+ return Namespace(d) + "::" + ClassName(d);
+}
+
string Namespace(const string& package) {
if (package.empty()) return "";
return "::" + DotsToColons(package);
}
+string Namespace(const Descriptor* d) { return Namespace(d->file()); }
+
+string Namespace(const FieldDescriptor* d) { return Namespace(d->file()); }
+
+string Namespace(const EnumDescriptor* d) { return Namespace(d->file()); }
+
string DefaultInstanceName(const Descriptor* descriptor) {
string prefix = descriptor->file()->package().empty() ? "" : "::";
return prefix + DotsToColons(descriptor->file()->package()) + "::_" +
@@ -221,9 +288,9 @@ string ReferenceFunctionName(const Descriptor* descriptor) {
}
string SuperClassName(const Descriptor* descriptor, const Options& options) {
- return HasDescriptorMethods(descriptor->file(), options)
- ? "::google::protobuf::Message"
- : "::google::protobuf::MessageLite";
+ return "::" + ProtobufNamespace(options) +
+ (HasDescriptorMethods(descriptor->file(), options) ? "::Message"
+ : "::MessageLite");
}
string FieldName(const FieldDescriptor* field) {
@@ -318,6 +385,38 @@ const char* PrimitiveTypeName(FieldDescriptor::CppType type) {
return NULL;
}
+string PrimitiveTypeName(const Options& options,
+ FieldDescriptor::CppType type) {
+ switch (type) {
+ case FieldDescriptor::CPPTYPE_INT32:
+ return IntTypeName(options, "int32");
+ case FieldDescriptor::CPPTYPE_INT64:
+ return IntTypeName(options, "int64");
+ case FieldDescriptor::CPPTYPE_UINT32:
+ return IntTypeName(options, "uint32");
+ case FieldDescriptor::CPPTYPE_UINT64:
+ return IntTypeName(options, "uint64");
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ return "double";
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ return "float";
+ case FieldDescriptor::CPPTYPE_BOOL:
+ return "bool";
+ case FieldDescriptor::CPPTYPE_ENUM:
+ return "int";
+ case FieldDescriptor::CPPTYPE_STRING:
+ return StringTypeName(options);
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ return "";
+
+ // No default because we want the compiler to complain if any new
+ // CppTypes are added.
+ }
+
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return "";
+}
+
const char* DeclaredTypeMethodName(FieldDescriptor::Type type) {
switch (type) {
case FieldDescriptor::TYPE_INT32 : return "Int32";
@@ -349,44 +448,58 @@ const char* DeclaredTypeMethodName(FieldDescriptor::Type type) {
}
string Int32ToString(int number) {
- // gcc rejects the decimal form of kint32min.
if (number == kint32min) {
- GOOGLE_COMPILE_ASSERT(kint32min == (~0x7fffffff), kint32min_value_error);
- return "(~0x7fffffff)";
+ // This needs to be special-cased, see explanation here:
+ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
+ return SimpleItoa(number + 1) + " - 1";
} else {
return SimpleItoa(number);
}
}
-string Int64ToString(int64 number) {
- // gcc rejects the decimal form of kint64min
+string Int64ToString(const string& macro_prefix, int64 number) {
if (number == kint64min) {
- // Make sure we are in a 2's complement system.
- GOOGLE_COMPILE_ASSERT(kint64min == GOOGLE_LONGLONG(~0x7fffffffffffffff),
- kint64min_value_error);
- return "GOOGLE_LONGLONG(~0x7fffffffffffffff)";
+ // This needs to be special-cased, see explanation here:
+ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52661
+ return macro_prefix + "_LONGLONG(" + SimpleItoa(number + 1) +
+ ") - 1";
}
- return "GOOGLE_LONGLONG(" + SimpleItoa(number) + ")";
+ return macro_prefix + "_LONGLONG(" + SimpleItoa(number) + ")";
+}
+
+string UInt64ToString(const string& macro_prefix, uint64 number) {
+ return macro_prefix + "_ULONGLONG(" + SimpleItoa(number) + ")";
}
string DefaultValue(const FieldDescriptor* field) {
switch (field->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_INT64:
+ return Int64ToString("GG", field->default_value_int64());
+ case FieldDescriptor::CPPTYPE_UINT64:
+ return UInt64ToString("GG", field->default_value_uint64());
+ default:
+ return DefaultValue(Options(), field);
+ }
+}
+
+string DefaultValue(const Options& options, const FieldDescriptor* field) {
+ switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return Int32ToString(field->default_value_int32());
case FieldDescriptor::CPPTYPE_UINT32:
return SimpleItoa(field->default_value_uint32()) + "u";
case FieldDescriptor::CPPTYPE_INT64:
- return Int64ToString(field->default_value_int64());
+ return Int64ToString("PROTOBUF", field->default_value_int64());
case FieldDescriptor::CPPTYPE_UINT64:
- return "GOOGLE_ULONGLONG(" + SimpleItoa(field->default_value_uint64())+ ")";
+ return UInt64ToString("PROTOBUF", field->default_value_uint64());
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value = field->default_value_double();
if (value == std::numeric_limits<double>::infinity()) {
- return "::google::protobuf::internal::Infinity()";
+ return "std::numeric_limits<double>::infinity()";
} else if (value == -std::numeric_limits<double>::infinity()) {
- return "-::google::protobuf::internal::Infinity()";
+ return "-std::numeric_limits<double>::infinity()";
} else if (value != value) {
- return "::google::protobuf::internal::NaN()";
+ return "std::numeric_limits<double>::quiet_NaN()";
} else {
return SimpleDtoa(value);
}
@@ -395,11 +508,11 @@ string DefaultValue(const FieldDescriptor* field) {
{
float value = field->default_value_float();
if (value == std::numeric_limits<float>::infinity()) {
- return "static_cast<float>(::google::protobuf::internal::Infinity())";
+ return "std::numeric_limits<float>::infinity()";
} else if (value == -std::numeric_limits<float>::infinity()) {
- return "static_cast<float>(-::google::protobuf::internal::Infinity())";
+ return "-std::numeric_limits<float>::infinity()";
} else if (value != value) {
- return "static_cast<float>(::google::protobuf::internal::NaN())";
+ return "std::numeric_limits<float>::quiet_NaN()";
} else {
string float_value = SimpleFtoa(value);
// If floating point value contains a period (.) or an exponent
@@ -450,8 +563,9 @@ string FilenameIdentifier(const string& filename) {
return result;
}
-string FileLevelNamespace(const string& filename) {
- return "protobuf_" + FilenameIdentifier(filename);
+string UniqueName(const string& name, const string& filename,
+ const Options& options) {
+ return name + "_" + FilenameIdentifier(filename);
}
// Return the qualified C++ name for a file level symbol.
@@ -487,6 +601,126 @@ string SafeFunctionName(const Descriptor* descriptor,
return function_name;
}
+static bool HasLazyFields(const Descriptor* descriptor,
+ const Options& options) {
+ for (int field_idx = 0; field_idx < descriptor->field_count(); field_idx++) {
+ if (IsLazy(descriptor->field(field_idx), options)) {
+ return true;
+ }
+ }
+ for (int idx = 0; idx < descriptor->extension_count(); idx++) {
+ if (IsLazy(descriptor->extension(idx), options)) {
+ return true;
+ }
+ }
+ for (int idx = 0; idx < descriptor->nested_type_count(); idx++) {
+ if (HasLazyFields(descriptor->nested_type(idx), options)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Does the given FileDescriptor use lazy fields?
+bool HasLazyFields(const FileDescriptor* file, const Options& options) {
+ for (int i = 0; i < file->message_type_count(); i++) {
+ const Descriptor* descriptor(file->message_type(i));
+ if (HasLazyFields(descriptor, options)) {
+ return true;
+ }
+ }
+ for (int field_idx = 0; field_idx < file->extension_count(); field_idx++) {
+ if (IsLazy(file->extension(field_idx), options)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool HasRepeatedFields(const Descriptor* descriptor) {
+ for (int i = 0; i < descriptor->field_count(); ++i) {
+ if (descriptor->field(i)->label() == FieldDescriptor::LABEL_REPEATED) {
+ return true;
+ }
+ }
+ for (int i = 0; i < descriptor->nested_type_count(); ++i) {
+ if (HasRepeatedFields(descriptor->nested_type(i))) return true;
+ }
+ return false;
+}
+
+bool HasRepeatedFields(const FileDescriptor* file) {
+ for (int i = 0; i < file->message_type_count(); ++i) {
+ if (HasRepeatedFields(file->message_type(i))) return true;
+ }
+ return false;
+}
+
+static bool IsStringPieceField(const FieldDescriptor* field,
+ const Options& options) {
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
+ EffectiveStringCType(field, options) == FieldOptions::STRING_PIECE;
+}
+
+static bool HasStringPieceFields(const Descriptor* descriptor,
+ const Options& options) {
+ for (int i = 0; i < descriptor->field_count(); ++i) {
+ if (IsStringPieceField(descriptor->field(i), options)) return true;
+ }
+ for (int i = 0; i < descriptor->nested_type_count(); ++i) {
+ if (HasStringPieceFields(descriptor->nested_type(i), options)) return true;
+ }
+ return false;
+}
+
+bool HasStringPieceFields(const FileDescriptor* file, const Options& options) {
+ for (int i = 0; i < file->message_type_count(); ++i) {
+ if (HasStringPieceFields(file->message_type(i), options)) return true;
+ }
+ return false;
+}
+
+static bool IsCordField(const FieldDescriptor* field, const Options& options) {
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
+ EffectiveStringCType(field, options) == FieldOptions::CORD;
+}
+
+static bool HasCordFields(const Descriptor* descriptor,
+ const Options& options) {
+ for (int i = 0; i < descriptor->field_count(); ++i) {
+ if (IsCordField(descriptor->field(i), options)) return true;
+ }
+ for (int i = 0; i < descriptor->nested_type_count(); ++i) {
+ if (HasCordFields(descriptor->nested_type(i), options)) return true;
+ }
+ return false;
+}
+
+bool HasCordFields(const FileDescriptor* file, const Options& options) {
+ for (int i = 0; i < file->message_type_count(); ++i) {
+ if (HasCordFields(file->message_type(i), options)) return true;
+ }
+ return false;
+}
+
+static bool HasExtensionsOrExtendableMessage(const Descriptor* descriptor) {
+ if (descriptor->extension_range_count() > 0) return true;
+ if (descriptor->extension_count() > 0) return true;
+ for (int i = 0; i < descriptor->nested_type_count(); ++i) {
+ if (HasExtensionsOrExtendableMessage(descriptor->nested_type(i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool HasExtensionsOrExtendableMessage(const FileDescriptor* file) {
+ if (file->extension_count() > 0) return true;
+ for (int i = 0; i < file->message_type_count(); ++i) {
+ if (HasExtensionsOrExtendableMessage(file->message_type(i))) return true;
+ }
+ return false;
+}
static bool HasMapFields(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); ++i) {
@@ -543,11 +777,16 @@ bool IsStringOrMessage(const FieldDescriptor* field) {
return false;
}
-FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field) {
+FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field,
+ const Options& options) {
GOOGLE_DCHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_STRING);
- // Open-source protobuf release only supports STRING ctype.
- return FieldOptions::STRING;
-
+ if (options.opensource_runtime) {
+ // Open-source protobuf release only supports STRING ctype.
+ return FieldOptions::STRING;
+ } else {
+ // Google-internal supports all ctypes.
+ return field->options().ctype();
+ }
}
bool IsAnyMessage(const FileDescriptor* descriptor) {
@@ -569,62 +808,81 @@ enum Utf8CheckMode {
NONE = 2, // No UTF-8 check.
};
+static bool FieldEnforceUtf8(const FieldDescriptor* field,
+ const Options& options) {
+ return true;
+}
+
+static bool FileUtf8Verification(const FileDescriptor* file,
+ const Options& options) {
+ return true;
+}
+
// Which level of UTF-8 enforcemant is placed on this file.
static Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field,
const Options& options) {
- if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
+ FieldEnforceUtf8(field, options)) {
return STRICT;
} else if (GetOptimizeFor(field->file(), options) !=
- FileOptions::LITE_RUNTIME) {
+ FileOptions::LITE_RUNTIME &&
+ FileUtf8Verification(field->file(), options)) {
return VERIFY;
} else {
return NONE;
}
}
+string GetUtf8Suffix(const FieldDescriptor* field, const Options& options) {
+ switch (GetUtf8CheckMode(field, options)) {
+ case STRICT:
+ return "UTF8";
+ case VERIFY:
+ return "UTF8Verify";
+ case NONE:
+ default: // Some build configs warn on missing return without default.
+ return "";
+ }
+}
+
static void GenerateUtf8CheckCode(const FieldDescriptor* field,
const Options& options, bool for_parse,
- const std::map<string, string>& variables,
const char* parameters,
const char* strict_function,
const char* verify_function,
- io::Printer* printer) {
+ const Formatter& format) {
switch (GetUtf8CheckMode(field, options)) {
case STRICT: {
if (for_parse) {
- printer->Print("DO_(");
+ format("DO_(");
}
- printer->Print(
- "::google::protobuf::internal::WireFormatLite::$function$(\n",
- "function", strict_function);
- printer->Indent();
- printer->Print(variables, parameters);
+ format("::$proto_ns$::internal::WireFormatLite::$1$(\n", strict_function);
+ format.Indent();
+ format(parameters);
if (for_parse) {
- printer->Print("::google::protobuf::internal::WireFormatLite::PARSE,\n");
+ format("::$proto_ns$::internal::WireFormatLite::PARSE,\n");
} else {
- printer->Print("::google::protobuf::internal::WireFormatLite::SERIALIZE,\n");
+ format("::$proto_ns$::internal::WireFormatLite::SERIALIZE,\n");
}
- printer->Print("\"$full_name$\")", "full_name", field->full_name());
+ format("\"$1$\")", field->full_name());
if (for_parse) {
- printer->Print(")");
+ format(")");
}
- printer->Print(";\n");
- printer->Outdent();
+ format(";\n");
+ format.Outdent();
break;
}
case VERIFY: {
- printer->Print(
- "::google::protobuf::internal::WireFormat::$function$(\n",
- "function", verify_function);
- printer->Indent();
- printer->Print(variables, parameters);
+ format("::$proto_ns$::internal::WireFormat::$1$(\n", verify_function);
+ format.Indent();
+ format(parameters);
if (for_parse) {
- printer->Print("::google::protobuf::internal::WireFormat::PARSE,\n");
+ format("::$proto_ns$::internal::WireFormat::PARSE,\n");
} else {
- printer->Print("::google::protobuf::internal::WireFormat::SERIALIZE,\n");
+ format("::$proto_ns$::internal::WireFormat::SERIALIZE,\n");
}
- printer->Print("\"$full_name$\");\n", "full_name", field->full_name());
- printer->Outdent();
+ format("\"$1$\");\n", field->full_name());
+ format.Outdent();
break;
}
case NONE:
@@ -634,21 +892,19 @@ static void GenerateUtf8CheckCode(const FieldDescriptor* field,
void GenerateUtf8CheckCodeForString(const FieldDescriptor* field,
const Options& options, bool for_parse,
- const std::map<string, string>& variables,
const char* parameters,
- io::Printer* printer) {
- GenerateUtf8CheckCode(field, options, for_parse, variables, parameters,
+ const Formatter& format) {
+ GenerateUtf8CheckCode(field, options, for_parse, parameters,
"VerifyUtf8String", "VerifyUTF8StringNamedField",
- printer);
+ format);
}
void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field,
const Options& options, bool for_parse,
- const std::map<string, string>& variables,
const char* parameters,
- io::Printer* printer) {
- GenerateUtf8CheckCode(field, options, for_parse, variables, parameters,
- "VerifyUtf8Cord", "VerifyUTF8CordNamedField", printer);
+ const Formatter& format) {
+ GenerateUtf8CheckCode(field, options, for_parse, parameters, "VerifyUtf8Cord",
+ "VerifyUTF8CordNamedField", format);
}
namespace {
@@ -669,11 +925,17 @@ void FlattenMessagesInFile(const FileDescriptor* file,
}
}
-bool HasWeakFields(const Descriptor* descriptor) {
+bool HasWeakFields(const Descriptor* descriptor, const Options& options) {
+ for (int i = 0; i < descriptor->field_count(); i++) {
+ if (IsWeak(descriptor->field(i), options)) return true;
+ }
return false;
}
-bool HasWeakFields(const FileDescriptor* file) {
+bool HasWeakFields(const FileDescriptor* file, const Options& options) {
+ for (int i = 0; i < file->message_type_count(); ++i) {
+ if (HasWeakFields(file->message_type(i), options)) return true;
+ }
return false;
}
@@ -684,7 +946,7 @@ bool UsingImplicitWeakFields(const FileDescriptor* file,
}
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options,
- SCCAnalyzer* scc_analyzer) {
+ MessageSCCAnalyzer* scc_analyzer) {
return UsingImplicitWeakFields(field->file(), options) &&
field->type() == FieldDescriptor::TYPE_MESSAGE &&
!field->is_required() && !field->is_map() &&
@@ -696,85 +958,18 @@ bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options,
scc_analyzer->GetSCC(field->message_type());
}
-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) {
+MessageAnalysis MessageSCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
if (analysis_cache_.count(scc)) return analysis_cache_[scc];
- MessageAnalysis result = MessageAnalysis();
+ MessageAnalysis result{};
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;
+ // Extensions are found by looking up default_instance and extension
+ // number in a map. So you'd maybe expect here
+ // result.constructor_requires_initialization = true;
+ // However the extension registration mechanism already makes sure
+ // the default will be initialized.
}
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
@@ -784,6 +979,7 @@ MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
switch (field->type()) {
case FieldDescriptor::TYPE_STRING:
case FieldDescriptor::TYPE_BYTES: {
+ result.constructor_requires_initialization = true;
if (field->options().ctype() == FieldOptions::CORD) {
result.contains_cord = true;
}
@@ -791,7 +987,8 @@ MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
}
case FieldDescriptor::TYPE_GROUP:
case FieldDescriptor::TYPE_MESSAGE: {
- const SCC* child = GetSCC(field->message_type());
+ result.constructor_requires_initialization = true;
+ const SCC* child = analyzer_.GetSCC(field->message_type());
if (child != scc) {
MessageAnalysis analysis = GetSCCAnalysis(child);
result.contains_cord |= analysis.contains_cord;
@@ -860,6 +1057,597 @@ void ListAllTypesForServices(const FileDescriptor* fd,
}
}
+bool GetBootstrapBasename(const Options& options, const string& basename,
+ string* bootstrap_basename) {
+ if (options.opensource_runtime || options.lite_implicit_weak_fields) {
+ return false;
+ }
+
+ std::unordered_map<string, string> bootstrap_mapping{
+ {"net/proto2/proto/descriptor",
+ "net/proto2/internal/descriptor"},
+ {"net/proto2/compiler/proto/plugin",
+ "net/proto2/compiler/proto/plugin"},
+ {"net/proto2/compiler/proto/profile",
+ "net/proto2/compiler/proto/profile_bootstrap"},
+ };
+ auto iter = bootstrap_mapping.find(basename);
+ if (iter == bootstrap_mapping.end()) {
+ *bootstrap_basename = basename;
+ return false;
+ } else {
+ *bootstrap_basename = iter->second;
+ return true;
+ }
+}
+
+bool IsBootstrapProto(const Options& options, const FileDescriptor* file) {
+ string my_name = StripProto(file->name());
+ return GetBootstrapBasename(options, my_name, &my_name);
+}
+
+bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context,
+ bool bootstrap_flag, string* basename) {
+ string bootstrap_basename;
+ if (!GetBootstrapBasename(options, *basename, &bootstrap_basename)) {
+ return false;
+ }
+
+ if (bootstrap_flag) {
+ // Adjust basename, but don't abort code generation.
+ *basename = bootstrap_basename;
+ return false;
+ } else {
+ string forward_to_basename = bootstrap_basename;
+
+ // Generate forwarding headers and empty .pb.cc.
+ {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(*basename + ".pb.h"));
+ io::Printer printer(output.get(), '$', nullptr);
+ printer.Print(
+ "#ifndef PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n"
+ "#define PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n"
+ "#include \"$forward_to_basename$.pb.h\" // IWYU pragma: export\n"
+ "#endif // PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PB_H\n",
+ "forward_to_basename", forward_to_basename,
+ "filename_identifier", FilenameIdentifier(*basename));
+
+ if (!options.opensource_runtime) {
+ // HACK HACK HACK, tech debt from the deeps of proto1 and SWIG
+ // protocoltype is SWIG'ed and we need to forward
+ if (*basename == "net/proto/protocoltype") {
+ printer.Print(
+ "#ifdef SWIG\n"
+ "%include \"$forward_to_basename$.pb.h\"\n"
+ "#endif // SWIG\n",
+ "forward_to_basename", forward_to_basename);
+ }
+ }
+ }
+
+ {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(*basename + ".proto.h"));
+ io::Printer printer(output.get(), '$', nullptr);
+ printer.Print(
+ "#ifndef PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n"
+ "#define PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n"
+ "#include \"$forward_to_basename$.proto.h\" // IWYU pragma: "
+ "export\n"
+ "#endif // "
+ "PROTOBUF_INCLUDED_$filename_identifier$_FORWARD_PROTO_H\n",
+ "forward_to_basename", forward_to_basename,
+ "filename_identifier", FilenameIdentifier(*basename));
+ }
+
+ {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(*basename + ".pb.cc"));
+ io::Printer printer(output.get(), '$', nullptr);
+ printer.Print("\n");
+ }
+
+ {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(*basename + ".pb.h.meta"));
+ }
+
+ {
+ std::unique_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(*basename + ".proto.h.meta"));
+ }
+
+ // Abort code generation.
+ return true;
+ }
+}
+
+bool ShouldRepeat(const FieldDescriptor* descriptor,
+ internal::WireFormatLite::WireType wiretype) {
+ return descriptor->is_repeated() &&
+ (!descriptor->is_packable() ||
+ wiretype != internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
+}
+
+void GenerateLengthDelim(
+ const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer,
+ const Formatter& format) {
+ format(
+ "ptr = Varint::Parse32Inline(ptr, &size);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n");
+ if (!IsProto1(field->file(), options) && field->is_packable()) {
+ if (!HasPreservingUnknownEnumSemantics(field->file()) &&
+ field->type() == FieldDescriptor::TYPE_ENUM) {
+ format(
+ "ctx->extra_parse_data().SetEnumValidator($1$_IsValid, "
+ "msg->mutable_unknown_fields(), $2$);\n"
+ "parser_till_end = "
+ "::$proto_ns$::internal::PackedValidEnumParser$3$;\n"
+ "object = msg->mutable_$4$();\n",
+ QualifiedClassName(field->enum_type()), field->number(),
+ UseUnknownFieldSet(field->file(), options) ? "" : "Lite",
+ FieldName(field));
+ } else {
+ format(
+ "parser_till_end = ::$proto_ns$::internal::Packed$1$Parser;\n"
+ "object = msg->mutable_$2$();\n",
+ DeclaredTypeMethodName(field->type()), FieldName(field));
+ }
+ format(
+ "if (size > end - ptr) goto len_delim_till_end;\n"
+ "auto newend = ptr + size;\n"
+ "if (size) ptr = parser_till_end(ptr, newend, object, ctx);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr == newend);\n");
+ } else {
+ auto field_type = field->type();
+ if (IsProto1(field->file(), options)) {
+ if (field->is_packable()) {
+ // Sigh ... packed fields endup as a string in proto1
+ field_type = FieldDescriptor::TYPE_BYTES;
+ }
+ if (field_type == FieldDescriptor::TYPE_STRING) {
+ // In proto1 strings are treated as bytes
+ field_type = FieldDescriptor::TYPE_BYTES;
+ }
+ }
+ string utf8 = "";
+ switch (field_type) {
+ case FieldDescriptor::TYPE_STRING:
+ utf8 = GetUtf8Suffix(field, options);
+ if (!utf8.empty()) {
+ string name = "nullptr";
+ if (HasDescriptorMethods(field->file(), options)) {
+ name = "\"" + field->full_name() + "\"";
+ }
+ format("ctx->extra_parse_data().SetFieldName($1$);\n", name);
+ }
+ PROTOBUF_FALLTHROUGH_INTENDED;
+ case FieldDescriptor::TYPE_BYTES: {
+ if (field->options().ctype() == FieldOptions::STRING ||
+ (IsProto1(field->file(), options) &&
+ field->options().ctype() == FieldOptions::STRING_PIECE)) {
+ format(
+ "parser_till_end = ::$proto_ns$::internal::StringParser$1$;\n"
+ "$string$* str = msg->$2$_$3$();\n"
+ "str->clear();\n",
+ utf8,
+ field->is_repeated() && !field->is_map() &&
+ !field->is_packable()
+ ? "add"
+ : "mutable",
+ FieldName(field));
+ if (utf8.empty()) {
+ // special case if there is no utf8 verification.
+ format(
+ "object = str;\n"
+ "if (size > end - ptr) goto len_delim_till_end;\n"
+ "str->append(ptr, size);\n"
+ "ptr += size;\n");
+ return;
+ }
+ } else if (field->options().ctype() == FieldOptions::CORD) {
+ string cord_parser = "CordParser" + utf8;
+ format(
+ "parser_till_end = ::$proto_ns$::internal::$1$;\n"
+ "auto* str = msg->$2$_$3$();\n"
+ "str->Clear();\n",
+ cord_parser,
+ field->is_repeated() && !field->is_map() ? "add" : "mutable",
+ FieldName(field));
+ } else if (field->options().ctype() == FieldOptions::STRING_PIECE) {
+ format(
+ "parser_till_end = "
+ "::$proto_ns$::internal::StringPieceParser$1$;\n"
+ "::$proto_ns$::internal::StringPieceField* str = "
+ "msg->$2$_$3$();\n"
+ "str->Clear();\n",
+ utf8,
+ field->is_repeated() && !field->is_map() ? "add" : "mutable",
+ FieldName(field));
+ }
+ format(
+ "object = str;\n"
+ "if (size > end - ptr) goto len_delim_till_end;\n"
+ "auto newend = ptr + size;\n"
+ "if (size) ptr = parser_till_end(ptr, newend, object, ctx);\n");
+ if (!utf8.empty()) {
+ // If utf8 verification is on this can fail.
+ format("$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr == newend);\n");
+ }
+ break;
+ }
+ case FieldDescriptor::TYPE_MESSAGE: {
+ GOOGLE_CHECK(field->message_type());
+ if (!IsProto1(field->file(), options) && field->is_map()) {
+ const FieldDescriptor* val =
+ field->message_type()->FindFieldByName("value");
+ GOOGLE_CHECK(val);
+ if (HasFieldPresence(field->file()) &&
+ val->type() == FieldDescriptor::TYPE_ENUM) {
+ format(
+ "ctx->extra_parse_data().field_number = $1$;\n"
+ "ctx->extra_parse_data().unknown_fields = "
+ "&msg->_internal_metadata_;\n",
+ field->number());
+ }
+ format(
+ "parser_till_end = ::$proto_ns$::internal::SlowMapEntryParser;\n"
+ "auto parse_map = $1$::_ParseMap;\n"
+ "ctx->extra_parse_data().payload.clear();\n"
+ "ctx->extra_parse_data().parse_map = parse_map;\n"
+ "object = &msg->$2$_;\n"
+ "if (size > end - ptr) goto len_delim_till_end;\n"
+ "auto newend = ptr + size;\n"
+ "GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, "
+ "object, ctx));\n"
+ "ptr = newend;\n",
+ QualifiedClassName(field->message_type()), FieldName(field));
+ break;
+ }
+ if (IsImplicitWeakField(field, options, scc_analyzer)) {
+ if (!field->is_repeated()) {
+ format("object = HasBitSetters::mutable_$1$(msg);\n",
+ FieldName(field));
+ } else {
+ format(
+ "object = "
+ "CastToBase(&msg->$1$_)->AddWeak(reinterpret_cast<const "
+ "::google::protobuf::MessageLite*>(&$2$::_$3$_default_instance_));\n",
+ FieldName(field), Namespace(field->message_type()),
+ ClassName(field->message_type()));
+ }
+ format(
+ "parser_till_end = static_cast<::$proto_ns$::MessageLite*>("
+ "object)->_ParseFunc();\n");
+ } else if (IsWeak(field, options)) {
+ if (IsProto1(field->file(), options)) {
+ format("object = msg->internal_mutable_$1$();\n",
+ FieldName(field));
+ } else {
+ format(
+ "object = msg->_weak_field_map_.MutableMessage($1$, "
+ "_$classname$_default_instance_.$2$_);\n",
+ field->number(), FieldName(field));
+ }
+ format(
+ "parser_till_end = static_cast<::$proto_ns$::MessageLite*>("
+ "object)->_ParseFunc();\n");
+ } else {
+ format(
+ "parser_till_end = $1$::_InternalParse;\n"
+ "object = msg->$2$_$3$();\n",
+ QualifiedClassName(field->message_type()),
+ field->is_repeated() ? "add" : "mutable", FieldName(field));
+ }
+ format(
+ "if (size > end - ptr) goto len_delim_till_end;\n"
+ "auto newend = ptr + size;\n"
+ "bool ok = ctx->ParseExactRange({parser_till_end, object},\n"
+ " ptr, newend);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n"
+ "ptr = newend;\n");
+ break;
+ }
+ default:
+ GOOGLE_LOG(FATAL) << "Illegal combination for length delimited wiretype "
+ << " filed type is " << field->type();
+ }
+ }
+}
+
+void GenerateCaseBody(internal::WireFormatLite::WireType wiretype,
+ const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer,
+ const Formatter& format) {
+ using internal::WireFormat;
+ using internal::WireFormatLite;
+
+ if (ShouldRepeat(field, wiretype)) {
+ format("do {\n");
+ format.Indent();
+ }
+ switch (wiretype) {
+ case WireFormatLite::WIRETYPE_VARINT: {
+ format(
+ "$uint64$ val;\n"
+ "ptr = Varint::Parse64(ptr, &val);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n");
+ string type = PrimitiveTypeName(options, field->cpp_type());
+ if ((field->type() == FieldDescriptor::TYPE_SINT32 ||
+ field->type() == FieldDescriptor::TYPE_SINT64) &&
+ !IsProto1(field->file(), options)) {
+ int size = EstimateAlignmentSize(field) * 8;
+ format(
+ "$1$ value = "
+ "::$proto_ns$::internal::WireFormatLite::ZigZagDecode$2$(val);\n",
+ type, size);
+ } else if (field->type() == FieldDescriptor::TYPE_ENUM &&
+ !IsProto1(field->file(), options)) {
+ if (!HasPreservingUnknownEnumSemantics(field->file())) {
+ format(
+ "if (!$1$_IsValid(val)) {\n"
+ " ::$proto_ns$::internal::WriteVarint($2$, val, "
+ "msg->mutable_unknown_fields());\n"
+ " break;\n"
+ "}\n",
+ QualifiedClassName(field->enum_type()), field->number());
+ }
+ format("$1$ value = static_cast<$1$>(val);\n",
+ QualifiedClassName(field->enum_type()));
+ } else {
+ format("$1$ value = val;\n", type);
+ }
+ if (field->is_repeated()) {
+ format("msg->add_$1$(value);\n", FieldName(field));
+ } else {
+ format("msg->set_$1$(value);\n", FieldName(field));
+ }
+ break;
+ }
+ case WireFormatLite::WIRETYPE_FIXED64: {
+ string type = PrimitiveTypeName(options, field->cpp_type());
+ format(
+ "$1$ val;\n"
+ "::std::memcpy(&val, ptr, 8);\n"
+ "ptr += 8;\n",
+ type);
+ if (field->is_repeated()) {
+ format("msg->add_$1$(val);\n", FieldName(field));
+ } else {
+ format("msg->set_$1$(val);\n", FieldName(field));
+ }
+ break;
+ }
+ case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: {
+ GenerateLengthDelim(field, options, scc_analyzer, format);
+ break;
+ }
+ case WireFormatLite::WIRETYPE_START_GROUP: {
+ format(
+ "parser_till_end = $1$::_InternalParse;\n"
+ "object = msg->$2$_$3$();\n"
+ "bool ok = ctx->PrepareGroup(tag, &depth);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n"
+ "ptr = parser_till_end(ptr, end, object, ctx);\n"
+ "$GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n"
+ "if (ctx->GroupContinues(depth)) goto group_continues;\n",
+ QualifiedClassName(field->message_type()),
+ field->is_repeated() ? "add" : "mutable", FieldName(field));
+ break;
+ }
+ case WireFormatLite::WIRETYPE_END_GROUP: {
+ GOOGLE_LOG(FATAL) << "Can't have end group field\n";
+ break;
+ }
+ case WireFormatLite::WIRETYPE_FIXED32: {
+ string type = PrimitiveTypeName(options, field->cpp_type());
+ format(
+ "$1$ val;\n"
+ "std::memcpy(&val, ptr, 4);\n"
+ "ptr += 4;\n",
+ type);
+ if (field->is_repeated()) {
+ format("msg->add_$1$(val);\n", FieldName(field));
+ } else {
+ format("msg->set_$1$(val);\n", FieldName(field));
+ }
+ break;
+ }
+ } // switch (wire_type)
+
+ if (ShouldRepeat(field, wiretype)) {
+ format("if (ptr >= end) break;\n");
+ uint32 x = field->number() * 8 + wiretype;
+ uint64 y = 0;
+ int cnt = 0;
+ do {
+ y += static_cast<uint64>((x & 0x7F) + (x >= 128 ? 128 : 0))
+ << (cnt++ * 8);
+ x >>= 7;
+ } while (x);
+ uint64 mask = (1ull << (cnt * 8)) - 1;
+ format.Outdent();
+ format(
+ "} while ((::$proto_ns$::io::UnalignedLoad<$uint64$>(ptr) & $1$) == "
+ "$2$ && (ptr += $3$));\n",
+ mask, y, cnt);
+ }
+ format("break;\n");
+}
+
+void GenerateCaseBody(const FieldDescriptor* field, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer,
+ const Formatter& format) {
+ using internal::WireFormat;
+ using internal::WireFormatLite;
+
+ if (!IsProto1(field->file(), options) && field->is_packable()) {
+ auto expected_wiretype = WireFormat::WireTypeForFieldType(field->type());
+ GOOGLE_CHECK(expected_wiretype != WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
+ uint32 expected_tag =
+ WireFormatLite::MakeTag(field->number(), expected_wiretype);
+ auto fallback_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
+ uint32 fallback_tag =
+ WireFormatLite::MakeTag(field->number(), fallback_wiretype);
+
+ if (field->is_packed()) {
+ std::swap(expected_tag, fallback_tag);
+ std::swap(expected_wiretype, fallback_wiretype);
+ }
+
+ format("if (static_cast<$uint8$>(tag) == $1$) {\n", expected_tag & 0xFF);
+ format.Indent();
+ GenerateCaseBody(expected_wiretype, field, options, scc_analyzer, format);
+ format.Outdent();
+ format(
+ "} else if (static_cast<$uint8$>(tag) != $1$) goto handle_unusual;\n",
+ fallback_tag & 0xFF);
+ GenerateCaseBody(fallback_wiretype, field, options, scc_analyzer, format);
+ } else {
+ auto wiretype = WireFormat::WireTypeForField(field);
+ format("if (static_cast<$uint8$>(tag) != $1$) goto handle_unusual;\n",
+ WireFormat::MakeTag(field) & 0xFF);
+ GenerateCaseBody(wiretype, field, options, scc_analyzer, format);
+ }
+}
+
+void GenerateParserLoop(const Descriptor* descriptor, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer,
+ io::Printer* printer) {
+ using internal::WireFormat;
+ using internal::WireFormatLite;
+
+ Formatter format(printer);
+ format.Set("classname", ClassName(descriptor));
+ format.Set("proto_ns", ProtobufNamespace(options));
+ std::map<string, string> vars;
+ SetCommonVars(options, &vars);
+ format.AddMap(vars);
+
+ std::vector<const FieldDescriptor*> ordered_fields;
+ for (auto field : FieldRange(descriptor)) {
+ ordered_fields.push_back(field);
+ }
+ std::sort(ordered_fields.begin(), ordered_fields.end(),
+ [](const FieldDescriptor* a, const FieldDescriptor* b) {
+ return a->number() < b->number();
+ });
+
+ format(
+ "const char* $classname$::_InternalParse(const char* begin, const char* "
+ "end, void* object,\n"
+ " ::$proto_ns$::internal::ParseContext* ctx) {\n"
+ " auto msg = static_cast<$classname$*>(object);\n"
+ " $uint32$ size; (void)size;\n"
+ " int depth; (void)depth;\n"
+ " ::$proto_ns$::internal::ParseFunc parser_till_end; "
+ "(void)parser_till_end;\n"
+ " auto ptr = begin;\n"
+ " while (ptr < end) {\n"
+ " $uint32$ tag;\n"
+ " ptr = Varint::Parse32Inline(ptr, &tag);\n"
+ " $GOOGLE_PROTOBUF$_PARSER_ASSERT(ptr);\n"
+ " switch (tag >> 3) {\n");
+
+ format.Indent();
+ format.Indent();
+ format.Indent();
+
+ for (const auto* field : ordered_fields) {
+ if (IsProto1(descriptor->file(), options)) {
+ if (field->number() >= (1 << 14)) continue;
+ }
+ // Print the field's (or oneof's) proto-syntax definition as a comment.
+ // We don't want to print group bodies so we cut off after the first
+ // line.
+ string def;
+ {
+ DebugStringOptions options;
+ options.elide_group_body = true;
+ options.elide_oneof_body = true;
+ def = field->DebugStringWithOptions(options);
+ def = def.substr(0, def.find_first_of('\n'));
+ }
+ format(
+ "// $1$\n"
+ "case $2$: {\n",
+ def, field->number());
+ format.Indent();
+ GenerateCaseBody(field, options, scc_analyzer, format);
+ format.Outdent();
+ format("}\n"); // case
+ } // for fields
+ format(
+ "default: {\n"
+ "handle_unusual: (void)&&handle_unusual;\n"
+ " if ((tag & 7) == 4 || tag == 0) {\n"
+ " bool ok = ctx->ValidEndGroup(tag);\n"
+ " $GOOGLE_PROTOBUF$_PARSER_ASSERT(ok);\n"
+ " return ptr;\n"
+ " }\n");
+ if (IsMapEntryMessage(descriptor)) {
+ format(
+ " break;\n"
+ "}\n");
+ } else {
+ if (descriptor->extension_range_count() > 0) {
+ format("if (");
+ for (int i = 0; i < descriptor->extension_range_count(); i++) {
+ const Descriptor::ExtensionRange* range =
+ descriptor->extension_range(i);
+ if (i > 0) format(" ||\n ");
+
+ uint32 start_tag = WireFormatLite::MakeTag(
+ range->start, static_cast<WireFormatLite::WireType>(0));
+ uint32 end_tag = WireFormatLite::MakeTag(
+ range->end, static_cast<WireFormatLite::WireType>(0));
+
+ if (range->end > FieldDescriptor::kMaxNumber) {
+ format("($1$u <= tag)", start_tag);
+ } else {
+ format("($1$u <= tag && tag < $2$u)", start_tag, end_tag);
+ }
+ }
+ format(") {\n");
+ format(
+ " auto res = msg->_extensions_.ParseField(tag, {_InternalParse, "
+ "msg}, ptr, end,\n"
+ " internal_default_instance(), &msg->_internal_metadata_, "
+ "ctx);\n"
+ " ptr = res.first;\n"
+ " if (res.second) return ptr;\n"
+ " continue;\n"
+ "}\n");
+ }
+ format(
+ " auto res = UnknownFieldParse(tag, {_InternalParse, msg},\n"
+ " ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), "
+ "ctx);\n"
+ " ptr = res.first;\n"
+ " if (res.second) return ptr;\n"
+ "}\n"); // default case
+ }
+ format.Outdent();
+ format.Outdent();
+ format.Outdent();
+ format(
+ " } // switch\n"
+ " } // while\n"
+ " return ptr;\n"
+ "len_delim_till_end: (void)&&len_delim_till_end;\n"
+ " return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},\n"
+ " {parser_till_end, object}, size);\n"
+ "group_continues: (void)&&group_continues;\n"
+ " $DCHK$(ptr >= end);\n"
+ // Group crossed end and must be continued. Either this a parse failure
+ // or we need to resume on the next chunk and thus save the state.
+ " ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, "
+ "depth);\n"
+ " return ptr;\n"
+ "}\n");
+}
} // namespace cpp
} // namespace compiler
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h
index eac65124..b8431aed 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.h
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h
@@ -35,48 +35,76 @@
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
+#include <iterator>
#include <map>
#include <string>
+
#include <google/protobuf/compiler/cpp/cpp_options.h>
+#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
+inline std::string ProtobufNamespace(const Options& options) {
+ return options.opensource_runtime ? "google::protobuf" : "proto2";
+}
+
+inline std::string MacroPrefix(const Options& options) {
+ return options.opensource_runtime ? "GOOGLE_PROTOBUF" : "GOOGLE_PROTOBUF";
+}
+
+inline std::string DeprecatedAttribute(const Options& options, bool deprecated) {
+ return deprecated ? "PROTOBUF_DEPRECATED " : "";
+}
+
// Commonly-used separator comments. Thick is a line of '=', thin is a line
// of '-'.
extern const char kThickSeparator[];
extern const char kThinSeparator[];
+inline bool IsProto1(const FileDescriptor* file, const Options& options) {
+ return false;
+}
+
+void SetCommonVars(const Options& options, std::map<std::string, std::string>* variables);
+
+bool GetBootstrapBasename(const Options& options, const std::string& basename,
+ std::string* bootstrap_basename);
+bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context,
+ bool bootstrap_flag, std::string* basename);
+bool IsBootstrapProto(const Options& options, const FileDescriptor* file);
// 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) {
+std::string Namespace(const std::string& package);
+inline std::string Namespace(const FileDescriptor* d) {
return Namespace(d->package());
}
-template <typename Desc>
-string Namespace(const Desc* d) {
- return Namespace(d->file());
-}
+
+std::string Namespace(const Descriptor* d);
+std::string Namespace(const FieldDescriptor* d);
+std::string Namespace(const EnumDescriptor* d);
// 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);
-}
+std::string ClassName(const Descriptor* descriptor);
+std::string ClassName(const EnumDescriptor* enum_descriptor);
+
+std::string QualifiedClassName(const Descriptor* d);
+std::string QualifiedClassName(const EnumDescriptor* d);
// DEPRECATED just use ClassName or QualifiedClassName, a boolean is very
// unreadable at the callsite.
@@ -88,33 +116,33 @@ string QualifiedClassName(const Desc* d) {
// ::foo::bar::Baz_Qux
// While the non-qualified version would be:
// Baz_Qux
-inline string ClassName(const Descriptor* descriptor, bool qualified) {
+inline std::string ClassName(const Descriptor* descriptor, bool qualified) {
return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
}
-inline string ClassName(const EnumDescriptor* descriptor, bool qualified) {
+inline std::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);
+std::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);
+std::string ReferenceFunctionName(const Descriptor* descriptor);
// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite.
-string SuperClassName(const Descriptor* descriptor, const Options& options);
+std::string SuperClassName(const Descriptor* descriptor, const Options& options);
// Get the (unqualified) name that should be used for this field in C++ code.
// The name is coerced to lower-case to emulate proto1 behavior. People
// should be using lowercase-with-underscores style for proto field names
// anyway, so normally this just returns field->name().
-string FieldName(const FieldDescriptor* field);
+std::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);
+std::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
@@ -124,7 +152,7 @@ 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);
+std::string FieldConstantName(const FieldDescriptor *field);
// Returns the scope where the field was defined (for extensions, this is
// different from the message type to which the field applies).
@@ -135,64 +163,88 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) {
// Returns the fully-qualified type name field->message_type(). Usually this
// is just ClassName(field->message_type(), true);
-string FieldMessageTypeName(const FieldDescriptor* field);
+std::string FieldMessageTypeName(const FieldDescriptor* field);
// Strips ".proto" or ".protodevel" from the end of a filename.
-LIBPROTOC_EXPORT string StripProto(const string& filename);
+PROTOC_EXPORT std::string StripProto(const std::string& filename);
// Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.).
-// Note: non-built-in type names will be qualified, meaning they will start
-// with a ::. If you are using the type as a template parameter, you will
-// need to insure there is a space between the < and the ::, because the
-// ridiculous C++ standard defines "<:" to be a synonym for "[".
const char* PrimitiveTypeName(FieldDescriptor::CppType type);
+std::string PrimitiveTypeName(const Options& options, FieldDescriptor::CppType type);
// Get the declared type name in CamelCase format, as is used e.g. for the
// methods of WireFormat. For example, TYPE_INT32 becomes "Int32".
const char* DeclaredTypeMethodName(FieldDescriptor::Type type);
// Return the code that evaluates to the number when compiled.
-string Int32ToString(int number);
+std::string Int32ToString(int number);
// Return the code that evaluates to the number when compiled.
-string Int64ToString(int64 number);
+std::string Int64ToString(const Options& options, int64 number);
// Get code that evaluates to the field's default value.
-string DefaultValue(const FieldDescriptor* field);
+std::string DefaultValue(const Options& options, const FieldDescriptor* field);
+
+// Compatibility function for callers outside proto2.
+std::string DefaultValue(const FieldDescriptor* field);
// Convert a file name into a valid identifier.
-string FilenameIdentifier(const string& filename);
+std::string FilenameIdentifier(const std::string& filename);
+
+// For each .proto file generates a unique name. To prevent collisions of
+// symbols in the global namespace
+std::string UniqueName(const std::string& name, const std::string& filename,
+ const Options& options);
+inline std::string UniqueName(const std::string& name, const FileDescriptor* d,
+ const Options& options) {
+ return UniqueName(name, d->name(), options);
+}
+inline std::string UniqueName(const std::string& name, const Descriptor* d,
+ const Options& options) {
+ return UniqueName(name, d->file(), options);
+}
+inline std::string UniqueName(const std::string& name, const EnumDescriptor* d,
+ const Options& options) {
+ return UniqueName(name, d->file(), options);
+}
+inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d,
+ const Options& options) {
+ return UniqueName(name, d->file(), options);
+}
-// 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());
+// Versions for call sites that only support the internal runtime (like proto1
+// support).
+inline Options InternalRuntimeOptions() {
+ Options options;
+ options.opensource_runtime = false;
+ return options;
+}
+inline std::string UniqueName(const std::string& name, const std::string& filename) {
+ return UniqueName(name, filename, InternalRuntimeOptions());
+}
+inline std::string UniqueName(const std::string& name, const FileDescriptor* d) {
+ return UniqueName(name, d->name(), InternalRuntimeOptions());
+}
+inline std::string UniqueName(const std::string& name, const Descriptor* d) {
+ return UniqueName(name, d->file(), InternalRuntimeOptions());
}
-inline string FileLevelNamespace(const Descriptor* d) {
- return FileLevelNamespace(d->file());
+inline std::string UniqueName(const std::string& name, const EnumDescriptor* d) {
+ return UniqueName(name, d->file(), InternalRuntimeOptions());
+}
+inline std::string UniqueName(const std::string& name, const ServiceDescriptor* d) {
+ return UniqueName(name, d->file(), InternalRuntimeOptions());
}
// Return the qualified C++ name for a file level symbol.
-string QualifiedFileLevelSymbol(const string& package, const string& name);
+std::string QualifiedFileLevelSymbol(const std::string& package, const std::string& name);
// Escape C++ trigraphs by escaping question marks to \?
-string EscapeTrigraphs(const string& to_escape);
+std::string EscapeTrigraphs(const std::string& to_escape);
// Escaped function name to eliminate naming conflict.
-string SafeFunctionName(const Descriptor* descriptor,
+std::string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
- const string& prefix);
-
-// 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());
-}
+ const std::string& prefix);
// Returns true if generated messages have public unknown fields accessors
inline bool PublicUnknownFieldsAccessors(const Descriptor* message) {
@@ -200,8 +252,8 @@ inline bool PublicUnknownFieldsAccessors(const Descriptor* message) {
}
// Returns the optimize mode for <file>, respecting <options.enforce_lite>.
-::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
- const FileDescriptor* file, const Options& options);
+FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
+ const Options& options);
// Determines whether unknown fields will be stored in an UnknownFieldSet or
// a string.
@@ -210,6 +262,56 @@ inline bool UseUnknownFieldSet(const FileDescriptor* file,
return GetOptimizeFor(file, options) != FileOptions::LITE_RUNTIME;
}
+inline bool IsWeak(const FieldDescriptor* field, const Options& options) {
+ if (field->options().weak()) {
+ GOOGLE_CHECK(!options.opensource_runtime);
+ return true;
+ }
+ return false;
+}
+
+// For a string field, returns the effective ctype. If the actual ctype is
+// not supported, returns the default of STRING.
+FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field,
+ const Options& options);
+
+inline bool IsCord(const FieldDescriptor* field, const Options& options) {
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
+ EffectiveStringCType(field, options) == FieldOptions::CORD;
+}
+
+inline bool IsStringPiece(const FieldDescriptor* field,
+ const Options& options) {
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
+ EffectiveStringCType(field, options) == FieldOptions::STRING_PIECE;
+}
+
+// Does the given FileDescriptor use lazy fields?
+bool HasLazyFields(const FileDescriptor* file, const Options& options);
+
+// Is the given field a supported lazy field?
+inline bool IsLazy(const FieldDescriptor* field, const Options& options) {
+ return field->options().lazy() && !field->is_repeated() &&
+ field->type() == FieldDescriptor::TYPE_MESSAGE &&
+ GetOptimizeFor(field->file(), options) != FileOptions::LITE_RUNTIME &&
+ !options.opensource_runtime;
+}
+
+// Does the file contain any definitions that need extension_set.h?
+bool HasExtensionsOrExtendableMessage(const FileDescriptor* file);
+
+// Does the file have any repeated fields, necessitating the file to include
+// repeated_field.h? This does not include repeated extensions, since those are
+// all stored internally in an ExtensionSet, not a separate RepeatedField*.
+bool HasRepeatedFields(const FileDescriptor* file);
+
+// Does the file have any string/bytes fields with ctype=STRING_PIECE? This
+// does not include extensions, since ctype is ignored for extensions.
+bool HasStringPieceFields(const FileDescriptor* file, const Options& options);
+
+// Does the file have any string/bytes fields with ctype=CORD? This does not
+// include extensions, since ctype is ignored for extensions.
+bool HasCordFields(const FileDescriptor* file, const Options& options);
// Does the file have any map fields, necessitating the file to include
// map_field_inl.h and map.h.
@@ -247,6 +349,22 @@ inline bool HasFastArraySerialization(const FileDescriptor* file,
return GetOptimizeFor(file, options) == FileOptions::SPEED;
}
+inline bool IsProto2MessageSet(const Descriptor* descriptor,
+ const Options& options) {
+ return !options.opensource_runtime &&
+ !options.enforce_lite &&
+ !options.lite_implicit_weak_fields &&
+ descriptor->options().message_set_wire_format() &&
+ descriptor->full_name() == "google.protobuf.bridge.MessageSet";
+}
+
+inline bool IsProto2MessageSetFile(const FileDescriptor* file,
+ const Options& options) {
+ return !options.opensource_runtime &&
+ !options.enforce_lite &&
+ !options.lite_implicit_weak_fields &&
+ file->name() == "net/proto2/bridge/proto/message_set.proto";
+}
inline bool IsMapEntryMessage(const Descriptor* descriptor) {
return descriptor->options().map_entry();
@@ -255,11 +373,7 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) {
// Returns true if the field's CPPTYPE is string or message.
bool IsStringOrMessage(const FieldDescriptor* field);
-// For a string field, returns the effective ctype. If the actual ctype is
-// not supported, returns the default of STRING.
-FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field);
-
-string UnderscoresToCamelCase(const string& input, bool cap_next_letter);
+std::string UnderscoresToCamelCase(const std::string& input, bool cap_next_letter);
inline bool HasFieldPresence(const FileDescriptor* file) {
return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
@@ -288,11 +402,11 @@ inline bool IsCrossFileMessage(const FieldDescriptor* field) {
field->message_type()->file() != field->file();
}
-inline string MessageCreateFunction(const Descriptor* d) {
+inline std::string MessageCreateFunction(const Descriptor* d) {
return SupportsArenas(d) ? "CreateMessage" : "Create";
}
-inline string MakeDefaultName(const FieldDescriptor* field) {
+inline std::string MakeDefaultName(const FieldDescriptor* field) {
return "_i_give_permission_to_break_this_code_default_" + FieldName(field) +
"_";
}
@@ -302,19 +416,8 @@ bool IsAnyMessage(const Descriptor* descriptor);
bool IsWellKnownMessage(const FileDescriptor* descriptor);
-void GenerateUtf8CheckCodeForString(const FieldDescriptor* field,
- const Options& options, bool for_parse,
- const std::map<string, string>& variables,
- const char* parameters,
- io::Printer* printer);
-
-void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field,
- const Options& options, bool for_parse,
- const std::map<string, string>& variables,
- const char* parameters, io::Printer* printer);
-
-inline ::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
- const FileDescriptor* file, const Options& options) {
+inline FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file,
+ const Options& options) {
return options.enforce_lite
? FileOptions::LITE_RUNTIME
: file->options().optimize_for();
@@ -330,27 +433,179 @@ inline std::vector<const Descriptor*> FlattenMessagesInFile(
return result;
}
-bool HasWeakFields(const Descriptor* desc);
-bool HasWeakFields(const FileDescriptor* desc);
+bool HasWeakFields(const Descriptor* desc, const Options& options);
+bool HasWeakFields(const FileDescriptor* desc, 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;
+ // Do not check "required" for lazy fields.
+ return IsLazy(field, options);
}
-class LIBPROTOC_EXPORT NamespaceOpener {
+struct MessageAnalysis {
+ bool is_recursive;
+ bool contains_cord;
+ bool contains_extension;
+ bool contains_required;
+ bool constructor_requires_initialization;
+};
+
+// 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 PROTOC_EXPORT MessageSCCAnalyzer {
+ public:
+ explicit MessageSCCAnalyzer(const Options& options) : options_(options) {}
+
+ MessageAnalysis GetSCCAnalysis(const SCC* scc);
+
+ bool HasRequiredFields(const Descriptor* descriptor) {
+ MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor));
+ return result.contains_required || result.contains_extension;
+ }
+ const SCC* GetSCC(const Descriptor* descriptor) {
+ return analyzer_.GetSCC(descriptor);
+ }
+
+ private:
+ SCCAnalyzer analyzer_;
+ Options options_;
+ std::map<const SCC*, MessageAnalysis> analysis_cache_;
+};
+
+void ListAllFields(const Descriptor* d,
+ std::vector<const FieldDescriptor*>* fields);
+void ListAllFields(const FileDescriptor* d,
+ std::vector<const FieldDescriptor*>* fields);
+void ListAllTypesForServices(const FileDescriptor* fd,
+ std::vector<const Descriptor*>* types);
+
+// 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,
+ MessageSCCAnalyzer* scc_analyzer);
+
+// Formatter is a functor class which acts as a closure around printer and
+// the variable map. It's much like printer->Print except it supports both named
+// variables that are substituted using a key value map and direct arguments. In
+// the format string $1$, $2$, etc... are substituted for the first, second, ...
+// direct argument respectively in the format call, it accepts both strings and
+// integers. The implementation verifies all arguments are used and are "first"
+// used in order of appearance in the argument list. For example,
+//
+// Format("return array[$1$];", 3) -> "return array[3];"
+// Format("array[$2$] = $1$;", "Bla", 3) -> FATAL error (wrong order)
+// Format("array[$1$] = $2$;", 3, "Bla") -> "array[3] = Bla;"
+//
+// The arguments can be used more than once like
+//
+// Format("array[$1$] = $2$; // Index = $1$", 3, "Bla") ->
+// "array[3] = Bla; // Index = 3"
+//
+// If you use more arguments use the following style to help the reader,
+//
+// Format("int $1$() {\n"
+// " array[$2$] = $3$;\n"
+// " return $4$;"
+// "}\n",
+// funname, // 1
+// idx, // 2
+// varname, // 3
+// retval); // 4
+//
+// but consider using named variables. Named variables like $foo$, with some
+// identifier foo, are looked up in the map. One additional feature is that
+// spaces are accepted between the '$' delimiters, $ foo$ will
+// substiture to " bar" if foo stands for "bar", but in case it's empty
+// will substitute to "". Hence, for example,
+//
+// Format(vars, "$dllexport $void fun();") -> "void fun();"
+// "__declspec(export) void fun();"
+//
+// which is convenient to prevent double, leading or trailing spaces.
+class PROTOC_EXPORT Formatter {
public:
- explicit NamespaceOpener(io::Printer* printer) : printer_(printer) {}
- NamespaceOpener(const string& name, io::Printer* printer)
- : printer_(printer) {
+ explicit Formatter(io::Printer* printer) : printer_(printer) {}
+ Formatter(io::Printer* printer, const std::map<std::string, std::string>& vars)
+ : printer_(printer), vars_(vars) {}
+
+ template <typename T>
+ void Set(const std::string& key, const T& value) {
+ vars_[key] = ToString(value);
+ }
+
+ void AddMap(const std::map<std::string, std::string>& vars) {
+ for (const auto& keyval : vars) vars_[keyval.first] = keyval.second;
+ }
+
+ template <typename... Args>
+ void operator()(const char* format, const Args&... args) const {
+ printer_->FormatInternal({ToString(args)...}, vars_, format);
+ }
+
+ void Indent() const { printer_->Indent(); }
+ void Outdent() const { printer_->Outdent(); }
+ io::Printer* printer() const { return printer_; }
+
+ class PROTOC_EXPORT SaveState {
+ public:
+ explicit SaveState(Formatter* format)
+ : format_(format), vars_(format->vars_) {}
+ ~SaveState() { format_->vars_.swap(vars_); }
+
+ private:
+ Formatter* format_;
+ std::map<std::string, std::string> vars_;
+ };
+
+ private:
+ io::Printer* printer_;
+ std::map<std::string, std::string> vars_;
+
+ // Convenience overloads to accept different types as arguments.
+ static std::string ToString(const std::string& s) { return s; }
+ template <typename I, typename = typename std::enable_if<
+ std::is_integral<I>::value>::type>
+ static std::string ToString(I x) {
+ return SimpleItoa(x);
+ }
+ static std::string ToString(strings::Hex x) { return StrCat(x); }
+ static std::string ToString(const FieldDescriptor* d) { return Payload(d); }
+ static std::string ToString(const Descriptor* d) { return Payload(d); }
+ static std::string ToString(const EnumDescriptor* d) { return Payload(d); }
+ static std::string ToString(const EnumValueDescriptor* d) { return Payload(d); }
+
+ template <typename Descriptor>
+ static std::string Payload(const Descriptor* descriptor) {
+ std::vector<int> path;
+ descriptor->GetLocationPath(&path);
+ GeneratedCodeInfo::Annotation annotation;
+ for (int i = 0; i < path.size(); ++i) {
+ annotation.add_path(path[i]);
+ }
+ annotation.set_source_file(descriptor->file()->name());
+ return annotation.SerializeAsString();
+ }
+};
+
+class PROTOC_EXPORT NamespaceOpener {
+ public:
+ explicit NamespaceOpener(const Formatter& format)
+ : printer_(format.printer()) {}
+ NamespaceOpener(const std::string& name, const Formatter& format)
+ : NamespaceOpener(format) {
ChangeTo(name);
}
~NamespaceOpener() { ChangeTo(""); }
- void ChangeTo(const string& name) {
- std::vector<string> new_stack_ =
+ void ChangeTo(const std::string& name) {
+ std::vector<std::string> new_stack_ =
Split(name, "::", true);
int len = std::min(name_stack_.size(), new_stack_.size());
int common_idx = 0;
@@ -369,93 +624,100 @@ class LIBPROTOC_EXPORT NamespaceOpener {
private:
io::Printer* printer_;
- std::vector<string> name_stack_;
+ std::vector<std::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;
+std::string GetUtf8Suffix(const FieldDescriptor* field, const Options& options);
+void GenerateUtf8CheckCodeForString(const FieldDescriptor* field,
+ const Options& options, bool for_parse,
+ const char* parameters,
+ const Formatter& format);
- const Descriptor* GetRepresentative() const { return descriptors[0]; }
-};
+void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field,
+ const Options& options, bool for_parse,
+ const char* parameters,
+ const Formatter& format);
-struct MessageAnalysis {
- bool is_recursive;
- bool contains_cord;
- bool contains_extension;
- bool contains_required;
+template <typename T>
+struct FieldRangeImpl {
+ struct Iterator {
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = const FieldDescriptor*;
+ using difference_type = int;
+
+ value_type operator*() { return descriptor->field(idx); }
+
+ friend bool operator==(const Iterator& a, const Iterator& b) {
+ GOOGLE_DCHECK(a.descriptor == b.descriptor);
+ return a.idx == b.idx;
+ }
+ friend bool operator!=(const Iterator& a, const Iterator& b) {
+ return !(a == b);
+ }
+
+ Iterator& operator++() {
+ idx++;
+ return *this;
+ }
+
+ int idx;
+ const T* descriptor;
+ };
+
+ Iterator begin() const { return {0, descriptor}; }
+ Iterator end() const { return {descriptor->field_count(), descriptor}; }
+
+ const T* descriptor;
};
-// 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];
- }
+template <typename T>
+FieldRangeImpl<T> FieldRange(const T* desc) {
+ return {desc};
+}
- const SCC* GetSCC(const Descriptor* descriptor) {
- if (cache_.count(descriptor)) return cache_[descriptor].scc;
- return DFS(descriptor).scc;
- }
+struct OneOfRangeImpl {
+ struct Iterator {
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = const OneofDescriptor*;
+ using difference_type = int;
- MessageAnalysis GetSCCAnalysis(const SCC* scc);
+ value_type operator*() { return descriptor->oneof_decl(idx); }
- bool HasRequiredFields(const Descriptor* descriptor) {
- MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor));
- return result.contains_required || result.contains_extension;
- }
+ friend bool operator==(const Iterator& a, const Iterator& b) {
+ GOOGLE_DCHECK(a.descriptor == b.descriptor);
+ return a.idx == b.idx;
+ }
+ friend bool operator!=(const Iterator& a, const Iterator& b) {
+ return !(a == b);
+ }
- private:
- struct NodeData {
- const SCC* scc; // if null it means its still on the stack
- int index;
- int lowlink;
- };
+ Iterator& operator++() {
+ idx++;
+ return *this;
+ }
- 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_;
+ int idx;
+ const Descriptor* descriptor;
+ };
- SCC* CreateSCC() {
- garbage_bin_.push_back(new SCC());
- return garbage_bin_.back();
+ Iterator begin() const { return {0, descriptor}; }
+ Iterator end() const {
+ return {descriptor->oneof_decl_count(), descriptor};
}
- // 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);
+ const Descriptor* descriptor;
};
-void ListAllFields(const Descriptor* d,
- std::vector<const FieldDescriptor*>* fields);
-void ListAllFields(const FileDescriptor* d,
- std::vector<const FieldDescriptor*>* fields);
-void ListAllTypesForServices(const FileDescriptor* fd,
- std::vector<const Descriptor*>* types);
+inline OneOfRangeImpl OneOfRange(const Descriptor* desc) { return {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,
- SCCAnalyzer* scc_analyzer);
+void GenerateParserLoop(const Descriptor* descriptor, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer, io::Printer* printer);
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
index 0e485cac..3114bbf7 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
@@ -32,9 +32,9 @@
#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 {
namespace protobuf {
namespace compiler {
@@ -50,8 +50,6 @@ 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)
@@ -63,7 +61,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
descriptor->message_type()->FindFieldByName("key");
const FieldDescriptor* val =
descriptor->message_type()->FindFieldByName("value");
- (*variables)["key_cpp"] = PrimitiveTypeName(key->cpp_type());
+ (*variables)["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
(*variables)["val_cpp"] = FieldMessageTypeName(val);
@@ -74,18 +72,17 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
(*variables)["wrapper"] = "EnumEntryWrapper";
break;
default:
- (*variables)["val_cpp"] = PrimitiveTypeName(val->cpp_type());
+ (*variables)["val_cpp"] = PrimitiveTypeName(options, val->cpp_type());
(*variables)["wrapper"] = "EntryWrapper";
}
(*variables)["key_wire_type"] =
- "::google::protobuf::internal::WireFormatLite::TYPE_" +
- ToUpper(DeclaredTypeMethodName(key->type()));
+ "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type()));
(*variables)["val_wire_type"] =
- "::google::protobuf::internal::WireFormatLite::TYPE_" +
- ToUpper(DeclaredTypeMethodName(val->type()));
+ "TYPE_" + ToUpper(DeclaredTypeMethodName(val->type()));
(*variables)["map_classname"] = ClassName(descriptor->message_type(), false);
(*variables)["number"] = SimpleItoa(descriptor->number());
- (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
+ (*variables)["tag"] =
+ SimpleItoa(internal::WireFormat::MakeTag(descriptor));
if (HasDescriptorMethods(descriptor->file(), options)) {
(*variables)["lite"] = "";
@@ -104,7 +101,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetMessageVariables(descriptor, &variables_, options);
}
@@ -112,37 +109,37 @@ MapFieldGenerator::~MapFieldGenerator() {}
void MapFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "::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");
+ Formatter format(printer, variables_);
+ format(
+ "::$proto_ns$::internal::MapField$lite$<\n"
+ " $map_classname$,\n"
+ " $key_cpp$, $val_cpp$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
+ " $default_enum_value$ > $name$_;\n");
}
void MapFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- printer->Print(
- variables_,
- "$deprecated_attr$const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\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_);
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$const ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >&\n"
+ " ${1$$name$$}$() const;\n"
+ "$deprecated_attr$::$proto_ns$::Map< $key_cpp$, $val_cpp$ >*\n"
+ " ${1$mutable_$name$$}$();\n",
+ descriptor_);
}
void MapFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- printer->Print(variables_,
- "inline const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
+ Formatter format(printer, variables_);
+ format(
+ "inline const ::$proto_ns$::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 ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_map:$full_name$)\n"
" return $name$_.MutableMap();\n"
@@ -151,17 +148,20 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
void MapFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Clear();\n");
+ Formatter format(printer, variables_);
+ format("$name$_.Clear();\n");
}
void MapFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.MergeFrom(from.$name$_);\n");
}
void MapFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.Swap(&other->$name$_);\n");
}
void MapFieldGenerator::
@@ -172,147 +172,138 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
void MapFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- const FieldDescriptor* key_field =
- descriptor_->message_type()->FindFieldByName("key");
+ Formatter format(printer, variables_);
+ const FieldDescriptor* key_field =
+ descriptor_->message_type()->FindFieldByName("key");
const FieldDescriptor* value_field =
descriptor_->message_type()->FindFieldByName("value");
- bool using_entry = false;
string key;
string value;
+ format(
+ "$map_classname$::Parser< ::$proto_ns$::internal::MapField$lite$<\n"
+ " $map_classname$,\n"
+ " $key_cpp$, $val_cpp$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
+ " $default_enum_value$ >,\n"
+ " ::$proto_ns$::Map< $key_cpp$, $val_cpp$ > >"
+ " parser(&$name$_);\n");
if (IsProto3Field(descriptor_) ||
value_field->type() != FieldDescriptor::TYPE_ENUM) {
- printer->Print(
- variables_,
- "$map_classname$::Parser< ::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$ >,\n"
- " ::google::protobuf::Map< $key_cpp$, $val_cpp$ > >"
- " parser(&$name$_);\n"
- "DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n"
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessageNoVirtual(\n"
" input, &parser));\n");
key = "parser.key()";
value = "parser.value()";
} else {
- using_entry = true;
key = "entry->key()";
value = "entry->value()";
- printer->Print(variables_,
- "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n");
- printer->Print(variables_,
- "{\n"
- " ::std::string data;\n"
- " DO_(::google::protobuf::internal::WireFormatLite::ReadString(input, &data));\n"
- " DO_(entry->ParseFromString(data));\n"
- " if ($val_cpp$_IsValid(*entry->mutable_value())) {\n"
- " (*mutable_$name$())[entry->key()] =\n"
- " static_cast< $val_cpp$ >(*entry->mutable_value());\n"
- " } else {\n");
+ format("auto entry = parser.NewEntry();\n");
+ format(
+ "::std::string data;\n"
+ "DO_(::$proto_ns$::internal::WireFormatLite::ReadString(input, "
+ "&data));\n"
+ "DO_(entry->ParseFromString(data));\n"
+ "if ($val_cpp$_IsValid(*entry->mutable_value())) {\n"
+ " (*mutable_$name$())[entry->key()] =\n"
+ " static_cast< $val_cpp$ >(*entry->mutable_value());\n"
+ "} else {\n");
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(variables_,
- " mutable_unknown_fields()"
+ format(
+ " mutable_unknown_fields()"
"->AddLengthDelimited($number$, data);\n");
} else {
- printer->Print(variables_,
- " unknown_fields_stream.WriteVarint32($tag$u);\n"
- " unknown_fields_stream.WriteVarint32(\n"
- " static_cast< ::google::protobuf::uint32>(data.size()));\n"
- " unknown_fields_stream.WriteString(data);\n");
+ format(
+ " unknown_fields_stream.WriteVarint32($tag$u);\n"
+ " unknown_fields_stream.WriteVarint32(\n"
+ " static_cast< ::google::protobuf::uint32>(data.size()));\n"
+ " unknown_fields_stream.WriteString(data);\n");
}
-
- printer->Print(variables_,
- " }\n"
- "}\n");
+ format("}\n");
}
if (key_field->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- key_field, options_, true, variables_,
- StrCat(key, ".data(), static_cast<int>(", key, ".length()),\n").data(),
- printer);
+ key_field, options_, true,
+ StrCat(key, ".data(), static_cast<int>(", key, ".length()),\n")
+ .data(),
+ format);
}
if (value_field->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- value_field, options_, true, variables_,
- StrCat(value, ".data(), static_cast<int>(", value, ".length()),\n")
+ value_field, options_, true,
+ StrCat(value, ".data(), static_cast<int>(", value,
+ ".length()),\n")
.data(),
- printer);
- }
-
- // If entry is allocated by arena, its desctructor should be avoided.
- if (using_entry && SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "if (entry->GetArena() != NULL) entry.release();\n");
+ format);
}
}
-static void GenerateSerializationLoop(io::Printer* printer,
- const std::map<string, string>& variables,
- bool supports_arenas,
- const string& utf8_check,
- const string& loop_header,
- const string& ptr,
- bool loop_via_iterators) {
- printer->Print(variables,
- StrCat("::std::unique_ptr<$map_classname$> entry;\n",
- loop_header, " {\n").c_str());
- printer->Indent();
-
- printer->Print(variables, StrCat(
- "entry.reset($name$_.New$wrapper$(\n"
- " ", ptr, "->first, ", ptr, "->second));\n"
- "$write_entry$;\n").c_str());
+static void GenerateSerializationLoop(const Formatter& format,
+ bool supports_arenas, bool string_key,
+ bool string_value, bool to_array,
+ bool is_deterministic) {
+ format("::std::unique_ptr<$map_classname$> entry;\n");
+ string ptr;
+ if (is_deterministic) {
+ format("for (size_type i = 0; i < n; i++) {\n");
+ ptr = string_key ? "items[static_cast<ptrdiff_t>(i)]"
+ : "items[static_cast<ptrdiff_t>(i)].second";
+ } else {
+ format(
+ "for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
+ " it = this->$name$().begin();\n"
+ " it != this->$name$().end(); ++it) {\n");
+ ptr = "it";
+ }
+ format.Indent();
+
+ format("entry.reset($name$_.New$wrapper$($1$->first, $1$->second));\n", ptr);
+ if (to_array) {
+ format(
+ "target = ::$proto_ns$::internal::WireFormatLite::InternalWrite"
+ "$declared_type$NoVirtualToArray($number$, *entry, deterministic, "
+ "target);\n");
+ } else {
+ format(
+ "::$proto_ns$::internal::WireFormatLite::Write$stream_writer$($number$,"
+ " "
+ "*entry, output);\n");
+ }
// If entry is allocated by arena, its desctructor should be avoided.
if (supports_arenas) {
- printer->Print(
+ format(
"if (entry->GetArena() != NULL) {\n"
" entry.release();\n"
"}\n");
}
- if (!utf8_check.empty()) {
- // If loop_via_iterators is true then ptr is actually an iterator, and we
- // create a pointer by prefixing it with "&*".
- printer->Print(
- StrCat(utf8_check, "(", (loop_via_iterators ? "&*" : ""), ptr, ");\n")
- .c_str());
+ if (string_key || string_value) {
+ // ptr is either an actual pointer or an iterator, either way we can
+ // create a pointer by taking the address after de-referencing it.
+ format("Utf8Check::Check(&(*$1$));\n", ptr);
}
- printer->Outdent();
- printer->Print(
- "}\n");
+ format.Outdent();
+ format("}\n");
}
void MapFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["write_entry"] = "::google::protobuf::internal::WireFormatLite::Write" +
- variables["stream_writer"] + "(\n " +
- variables["number"] + ", *entry, output)";
- variables["deterministic"] = "output->IsSerializationDeterministic()";
- GenerateSerializeWithCachedSizes(printer, variables);
+ GenerateSerializeWithCachedSizes(printer, false);
}
void MapFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- std::map<string, string> variables(variables_);
- variables["write_entry"] =
- "target = ::google::protobuf::internal::WireFormatLite::\n"
- " InternalWrite" + variables["declared_type"] +
- "NoVirtualToArray(\n " + variables["number"] +
- ", *entry, deterministic, target);\n";
- variables["deterministic"] = "deterministic";
- GenerateSerializeWithCachedSizes(printer, variables);
+ GenerateSerializeWithCachedSizes(printer, true);
}
-void MapFieldGenerator::GenerateSerializeWithCachedSizes(
- io::Printer* printer, const std::map<string, string>& variables) const {
- printer->Print(variables,
- "if (!this->$name$().empty()) {\n");
- printer->Indent();
+void MapFieldGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer,
+ bool to_array) const {
+ Formatter format(printer, variables_);
+ format("if (!this->$name$().empty()) {\n");
+ format.Indent();
const FieldDescriptor* key_field =
descriptor_->message_type()->FindFieldByName("key");
const FieldDescriptor* value_field =
@@ -320,114 +311,110 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
const bool string_key = key_field->type() == FieldDescriptor::TYPE_STRING;
const bool string_value = value_field->type() == FieldDescriptor::TYPE_STRING;
- printer->Print(variables,
- "typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_pointer\n"
+ format(
+ "typedef ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_pointer\n"
" ConstPtr;\n");
if (string_key) {
- printer->Print(variables,
+ format(
"typedef ConstPtr SortItem;\n"
- "typedef ::google::protobuf::internal::"
+ "typedef ::$proto_ns$::internal::"
"CompareByDerefFirst<SortItem> Less;\n");
} else {
- printer->Print(variables,
- "typedef ::google::protobuf::internal::SortItem< $key_cpp$, ConstPtr > "
+ format(
+ "typedef ::$proto_ns$::internal::SortItem< $key_cpp$, ConstPtr > "
"SortItem;\n"
- "typedef ::google::protobuf::internal::CompareByFirstField<SortItem> Less;\n");
+ "typedef ::$proto_ns$::internal::CompareByFirstField<SortItem> "
+ "Less;\n");
}
- string utf8_check;
- if (string_key || string_value) {
- printer->Print(
+ bool utf8_check = string_key || string_value;
+ if (utf8_check) {
+ format(
"struct Utf8Check {\n"
" static void Check(ConstPtr p) {\n");
- printer->Indent();
- printer->Indent();
+ format.Indent();
+ format.Indent();
if (string_key) {
GenerateUtf8CheckCodeForString(
- key_field, options_, false, variables,
- "p->first.data(), static_cast<int>(p->first.length()),\n", printer);
+ key_field, options_, false,
+ "p->first.data(), static_cast<int>(p->first.length()),\n", format);
}
if (string_value) {
GenerateUtf8CheckCodeForString(
- value_field, options_, false, variables,
- "p->second.data(), static_cast<int>(p->second.length()),\n", printer);
+ value_field, options_, false,
+ "p->second.data(), static_cast<int>(p->second.length()),\n", format);
}
- printer->Outdent();
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format.Outdent();
+ format(
" }\n"
"};\n");
- utf8_check = "Utf8Check::Check";
}
- printer->Print(variables,
+ format(
"\n"
- "if ($deterministic$ &&\n"
+ "if ($1$ &&\n"
" this->$name$().size() > 1) {\n"
" ::std::unique_ptr<SortItem[]> items(\n"
" new SortItem[this->$name$().size()]);\n"
- " typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::size_type size_type;\n"
+ " typedef ::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::size_type "
+ "size_type;\n"
" size_type n = 0;\n"
- " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
+ " for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
" it = this->$name$().begin();\n"
" it != this->$name$().end(); ++it, ++n) {\n"
" items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);\n"
" }\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[static_cast<ptrdiff_t>(i)]" :
- "items[static_cast<ptrdiff_t>(i)].second", false);
- printer->Outdent();
- printer->Print(
- "} else {\n");
- printer->Indent();
- GenerateSerializationLoop(
- printer, variables, SupportsArenas(descriptor_), utf8_check,
- "for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
- " it = this->$name$().begin();\n"
- " it != this->$name$().end(); ++it)",
- "it", true);
- printer->Outdent();
- printer->Print("}\n");
- printer->Outdent();
- printer->Print("}\n");
+ " ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());\n",
+ to_array ? "deterministic" : "output->IsSerializationDeterministic()");
+ format.Indent();
+ GenerateSerializationLoop(format, SupportsArenas(descriptor_), string_key,
+ string_value, to_array, true);
+ format.Outdent();
+ format("} else {\n");
+ format.Indent();
+ GenerateSerializationLoop(format, SupportsArenas(descriptor_), string_key,
+ string_value, to_array, false);
+ format.Outdent();
+ format("}\n");
+ format.Outdent();
+ format("}\n");
}
void MapFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
+ Formatter format(printer, variables_);
+ format(
"total_size += $tag_size$ *\n"
- " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
+ " ::$proto_ns$::internal::FromIntSize(this->$name$_size());\n"
"{\n"
" ::std::unique_ptr<$map_classname$> entry;\n"
- " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
+ " for (::$proto_ns$::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
" it = this->$name$().begin();\n"
" it != this->$name$().end(); ++it) {\n");
// If entry is allocated by arena, its desctructor should be avoided.
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
+ format(
" if (entry.get() != NULL && entry->GetArena() != NULL) {\n"
" entry.release();\n"
" }\n");
}
- printer->Print(variables_,
+ format(
" entry.reset($name$_.New$wrapper$(it->first, it->second));\n"
- " total_size += ::google::protobuf::internal::WireFormatLite::\n"
+ " total_size += ::$proto_ns$::internal::WireFormatLite::\n"
" $declared_type$SizeNoVirtual(*entry);\n"
" }\n");
// If entry is allocated by arena, its desctructor should be avoided.
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
+ format(
" if (entry.get() != NULL && entry->GetArena() != NULL) {\n"
" entry.release();\n"
" }\n");
}
- printer->Print("}\n");
+ format("}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/cpp_map_field.h
index 0d54f0ea..95eecc07 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.h
@@ -62,11 +62,8 @@ class MapFieldGenerator : public FieldGenerator {
private:
// A helper for GenerateSerializeWithCachedSizes{,ToArray}.
- void GenerateSerializeWithCachedSizes(
- io::Printer* printer, const std::map<string, string>& variables) const;
-
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ void GenerateSerializeWithCachedSizes(io::Printer* printer,
+ bool to_array) const;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
};
@@ -74,6 +71,6 @@ class MapFieldGenerator : public FieldGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MAP_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc
index 8c2336af..4af54032 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message.cc
@@ -35,9 +35,9 @@
#include <google/protobuf/compiler/cpp/cpp_message.h>
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
+#include <unordered_map>
#include <utility>
#include <vector>
@@ -57,6 +57,8 @@
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/hash.h>
+
namespace google {
namespace protobuf {
@@ -69,7 +71,7 @@ using internal::WireFormatLite;
namespace {
template <class T>
-void PrintFieldComment(io::Printer* printer, const T* field) {
+void PrintFieldComment(const Formatter& format, const T* field) {
// Print the field's (or oneof's) proto-syntax definition as a comment.
// We don't want to print group bodies so we cut off after the first
// line.
@@ -77,8 +79,25 @@ void PrintFieldComment(io::Printer* printer, const T* field) {
options.elide_group_body = true;
options.elide_oneof_body = true;
string def = field->DebugStringWithOptions(options);
- printer->Print("// $def$\n",
- "def", def.substr(0, def.find_first_of('\n')));
+ format("// $1$\n", def.substr(0, def.find_first_of('\n')));
+}
+
+void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
+ const std::vector<int>& has_bit_indices,
+ io::Printer* printer, int* cached_has_bit_index) {
+ if (!field->options().weak()) {
+ int has_bit_index = has_bit_indices[field->index()];
+ if (*cached_has_bit_index != (has_bit_index / 32)) {
+ *cached_has_bit_index = (has_bit_index / 32);
+ format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_bit_index);
+ }
+ const string mask =
+ StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format("if (cached_has_bits & 0x$1$u) {\n", mask);
+ } else {
+ format("if (has_$1$()) {\n", FieldName(field));
+ }
+ format.Indent();
}
struct FieldOrderingByNumber {
@@ -135,9 +154,9 @@ bool CanConstructByZeroing(const FieldDescriptor* field,
// Non-repeated, non-lazy message fields are simply raw pointers, so we can
// use memset to initialize these in SharedCtor. We cannot use this in
// Clear, as we need to potentially delete the existing value.
- ret = ret ||
- (!field->is_repeated() &&
- field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
+ ret = ret || (!field->is_repeated() &&
+ !IsLazy(field, options) &&
+ field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
return ret;
}
@@ -145,36 +164,27 @@ bool CanConstructByZeroing(const FieldDescriptor* field,
// considered non-default (will be sent over the wire), for message types
// without true field presence. Should only be called if
// !HasFieldPresence(message_descriptor).
-bool EmitFieldNonDefaultCondition(io::Printer* printer,
- const string& prefix,
+bool EmitFieldNonDefaultCondition(io::Printer* printer, const string& prefix,
const FieldDescriptor* field) {
+ Formatter format(printer);
+ format.Set("prefix", prefix);
+ format.Set("name", FieldName(field));
// Merge and serialize semantics: primitive fields are merged/serialized only
// if non-zero (numeric) or non-empty (string).
if (!field->is_repeated() && !field->containing_oneof()) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
- printer->Print(
- "if ($prefix$$name$().size() > 0) {\n",
- "prefix", prefix,
- "name", FieldName(field));
+ format("if ($prefix$$name$().size() > 0) {\n");
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Message fields still have has_$name$() methods.
- printer->Print(
- "if ($prefix$has_$name$()) {\n",
- "prefix", prefix,
- "name", FieldName(field));
+ format("if ($prefix$has_$name$()) {\n");
} else {
- printer->Print(
- "if ($prefix$$name$() != 0) {\n",
- "prefix", prefix,
- "name", FieldName(field));
+ format("if ($prefix$$name$() != 0) {\n");
}
- printer->Indent();
+ format.Indent();
return true;
} else if (field->containing_oneof()) {
- printer->Print(
- "if (has_$name$()) {\n",
- "name", FieldName(field));
- printer->Indent();
+ format("if (has_$name$()) {\n");
+ format.Indent();
return true;
}
return false;
@@ -192,13 +202,13 @@ bool HasHasMethod(const FieldDescriptor* field) {
}
// Collects map entry message type information.
-void CollectMapInfo(const Descriptor* descriptor,
+void CollectMapInfo(const Options& options, 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");
- vars["key_cpp"] = PrimitiveTypeName(key->cpp_type());
+ vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
switch (val->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
vars["val_cpp"] = FieldMessageTypeName(val);
@@ -207,12 +217,12 @@ void CollectMapInfo(const Descriptor* descriptor,
vars["val_cpp"] = ClassName(val->enum_type(), true);
break;
default:
- vars["val_cpp"] = PrimitiveTypeName(val->cpp_type());
+ vars["val_cpp"] = PrimitiveTypeName(options, 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()));
+ vars["key_wire_type"] =
+ "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type()));
+ vars["val_wire_type"] =
+ "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();
@@ -231,9 +241,51 @@ bool HasPrivateHasMethod(const FieldDescriptor* field) {
field->containing_oneof() != NULL);
}
+// TODO(ckennelly): Cull these exclusions if/when these protos do not have
+// their methods overriden by subclasses.
+
+bool ShouldMarkClearAsFinal(const Descriptor* descriptor,
+ const Options& options) {
+ static std::set<string> exclusions{
+ };
+
+ const string name = ClassName(descriptor, true);
+ return exclusions.find(name) == exclusions.end() ||
+ options.opensource_runtime;
+}
-bool TableDrivenParsingEnabled(
- const Descriptor* descriptor, const Options& options) {
+bool ShouldMarkIsInitializedAsFinal(const Descriptor* descriptor,
+ const Options& options) {
+ static std::set<string> exclusions{
+ };
+
+ const string name = ClassName(descriptor, true);
+ return exclusions.find(name) == exclusions.end() ||
+ options.opensource_runtime;
+}
+
+bool ShouldMarkMergePartialAsFinal(const Descriptor* descriptor,
+ const Options& options) {
+ static std::set<string> exclusions{
+ };
+
+ const string name = ClassName(descriptor, true);
+ return exclusions.find(name) == exclusions.end() ||
+ options.opensource_runtime;
+}
+
+bool ShouldMarkNewAsFinal(const Descriptor* descriptor,
+ const Options& options) {
+ static std::set<string> exclusions{
+ };
+
+ const string name = ClassName(descriptor, true);
+ return exclusions.find(name) == exclusions.end() ||
+ options.opensource_runtime;
+}
+
+bool TableDrivenParsingEnabled(const Descriptor* descriptor,
+ const Options& options) {
if (!options.table_driven_parsing) {
return false;
}
@@ -247,14 +299,18 @@ bool TableDrivenParsingEnabled(
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);
+ for (auto field : FieldRange(descriptor)) {
if (max_field_number < field->number()) {
max_field_number = field->number();
}
// - There are no weak fields.
- if (field->options().weak()) {
+ if (IsWeak(field, options)) {
+ return false;
+ }
+
+ // - There are no lazy fields (they require the non-lite library).
+ if (IsLazy(field, options)) {
return false;
}
}
@@ -282,24 +338,16 @@ bool TableDrivenParsingEnabled(
void SetUnknkownFieldsVariable(const Descriptor* descriptor,
const Options& options,
std::map<string, string>* variables) {
+ string proto_ns = ProtobufNamespace(options);
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()";
+ (*variables)["unknown_fields_type"] = "::" + proto_ns + "::UnknownFieldSet";
} 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)["unknown_fields_type"] =
+ PrimitiveTypeName(options, FieldDescriptor::CPPTYPE_STRING);
}
+ (*variables)["have_unknown_fields"] =
+ "_internal_metadata_.have_unknown_fields()";
+ (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()";
(*variables)["mutable_unknown_fields"] =
"_internal_metadata_.mutable_unknown_fields()";
}
@@ -393,13 +441,13 @@ std::vector<std::vector<const FieldDescriptor*> > CollectFields(
const FieldDescriptor* last_field = fields.front();
std::vector<const FieldDescriptor*> chunk;
- for (int i = 0; i < fields.size(); i++) {
- if (!equivalent(last_field, fields[i]) && !chunk.empty()) {
+ for (auto field : fields) {
+ if (!equivalent(last_field, field) && !chunk.empty()) {
chunks.push_back(chunk);
chunk.clear();
}
- chunk.push_back(fields[i]);
- last_field = fields[i];
+ chunk.push_back(field);
+ last_field = field;
}
if (!chunk.empty()) {
chunks.push_back(chunk);
@@ -415,8 +463,7 @@ uint32 GenChunkMask(const std::vector<const FieldDescriptor*>& fields,
GOOGLE_CHECK(!fields.empty());
int first_index_offset = has_bit_indices[fields.front()->index()] / 32;
uint32 chunk_mask = 0;
- for (int i = 0; i < fields.size(); i++) {
- const FieldDescriptor* field = fields[i];
+ for (auto field : fields) {
// "index" defines where in the _has_bits_ the field appears.
int index = has_bit_indices[field->index()];
GOOGLE_CHECK_EQ(first_index_offset, index / 32);
@@ -426,32 +473,161 @@ uint32 GenChunkMask(const std::vector<const FieldDescriptor*>& fields,
return chunk_mask;
}
+// Return the number of bits set in n, a non-negative integer.
+static int popcnt(uint32 n) {
+ int result = 0;
+ while (n != 0) {
+ result += (n & 1);
+ n = n / 2;
+ }
+ return result;
+}
+
+// For a run of cold chunks, opens and closes an external if statement that
+// checks multiple has_bits words to skip bulk of cold fields.
+class ColdChunkSkipper {
+ public:
+ ColdChunkSkipper(
+ const Options& options,
+ const std::vector<std::vector<const FieldDescriptor*>>& chunks,
+ const std::vector<int>& has_bit_indices, const double cold_threshold,
+ bool has_field_presence)
+ : chunks_(chunks),
+ has_bit_indices_(has_bit_indices),
+ access_info_map_(options.access_info_map),
+ cold_threshold_(cold_threshold),
+ has_field_presence_(has_field_presence) {
+ SetCommonVars(options, &variables_);
+ }
+
+ // May open an external if check for a batch of cold fields. "from" is the
+ // prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_".
+ // Otherwise, it should be "".
+ void OnStartChunk(int chunk, int cached_has_bit_index, const string& from,
+ io::Printer* printer);
+ bool OnEndChunk(int chunk, io::Printer* printer);
+
+ private:
+ bool IsColdChunk(int chunk);
+
+ int HasbitWord(int chunk, int offset) {
+ return has_bit_indices_[chunks_[chunk][offset]->index()] / 32;
+ }
+
+ const std::vector<std::vector<const FieldDescriptor*> >& chunks_;
+ const std::vector<int>& has_bit_indices_;
+ const AccessInfoMap* access_info_map_;
+ const double cold_threshold_;
+ std::map<string, string> variables_;
+ int limit_chunk_ = -1;
+ bool has_field_presence_;
+};
+
+// Tuning parameters for ColdChunkSkipper.
+const double kColdRatio = 0.005;
+
+bool ColdChunkSkipper::IsColdChunk(int chunk) { return false; }
+
+void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index,
+ const string& from, io::Printer* printer) {
+ Formatter format(printer, variables_);
+ if (!access_info_map_ || !has_field_presence_) {
+ return;
+ } else if (chunk < limit_chunk_) {
+ // We are already inside a run of cold chunks.
+ return;
+ } else if (!IsColdChunk(chunk)) {
+ // We can't start a run of cold chunks.
+ return;
+ }
+
+ // Find the end of consecutive cold chunks.
+ limit_chunk_ = chunk;
+ while (limit_chunk_ < chunks_.size() && IsColdChunk(limit_chunk_)) {
+ limit_chunk_++;
+ }
+
+ if (limit_chunk_ <= chunk + 1) {
+ // Require at least two chunks to emit external has_bit checks.
+ limit_chunk_ = -1;
+ return;
+ }
+
+ // Emit has_bit check for each has_bit_dword index.
+ format("if (PROTOBUF_PREDICT_FALSE(");
+ int first_word = HasbitWord(chunk, 0);
+ while (chunk < limit_chunk_) {
+ uint32 mask = 0;
+ int this_word = HasbitWord(chunk, 0);
+ // Generate mask for chunks on the same word.
+ for (; chunk < limit_chunk_ && HasbitWord(chunk, 0) == this_word; chunk++) {
+ for (auto field : chunks_[chunk]) {
+ int hasbit_index = has_bit_indices_[field->index()];
+ // Fields on a chunk must be in the same word.
+ GOOGLE_CHECK_EQ(this_word, hasbit_index / 32);
+ mask |= 1 << (hasbit_index % 32);
+ }
+ }
+
+ if (this_word != first_word) {
+ format(" ||\n ");
+ }
+ format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8));
+ if (this_word == cached_has_bit_index) {
+ format("(cached_has_bits & 0x$mask$u) != 0");
+ } else {
+ format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word);
+ }
+ }
+ format(")) {\n");
+ format.Indent();
+}
+
+bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) {
+ Formatter format(printer, variables_);
+ if (chunk != limit_chunk_ - 1) {
+ return false;
+ }
+ format.Outdent();
+ format("}\n");
+ return true;
+}
+
} // anonymous namespace
// ===================================================================
MessageGenerator::MessageGenerator(const Descriptor* descriptor,
+ const std::map<string, string>& vars,
int index_in_file_messages,
const Options& options,
- SCCAnalyzer* scc_analyzer)
+ MessageSCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
index_in_file_messages_(index_in_file_messages),
classname_(ClassName(descriptor, false)),
options_(options),
field_generators_(descriptor, options, scc_analyzer),
max_has_bit_index_(0),
- enum_generators_(
- new std::unique_ptr<EnumGenerator>[descriptor->enum_type_count()]),
- extension_generators_(new std::unique_ptr<
- ExtensionGenerator>[descriptor->extension_count()]),
num_weak_fields_(0),
- message_layout_helper_(new PaddingOptimizer()),
- scc_analyzer_(scc_analyzer) {
+ scc_analyzer_(scc_analyzer),
+ variables_(vars) {
+ if (!message_layout_helper_) {
+ message_layout_helper_.reset(new PaddingOptimizer());
+ }
+
+ // Variables that apply to this class
+ variables_["classname"] = classname_;
+ variables_["classtype"] = QualifiedClassName(descriptor_);
+ string scc_name =
+ ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative());
+ variables_["scc_name"] = UniqueName(scc_name, descriptor_, options_);
+ variables_["full_name"] = descriptor_->full_name();
+ variables_["superclass"] = SuperClassName(descriptor_, options_);
+
// Compute optimized field order to be used for layout and initialization
// purposes.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- if (field->options().weak()) {
+ for (auto field : FieldRange(descriptor_)) {
+ if (IsWeak(field, options_)) {
num_weak_fields_++;
} else if (!field->containing_oneof()) {
optimized_order_.push_back(field);
@@ -463,8 +639,7 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
if (HasFieldPresence(descriptor_->file())) {
// 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];
+ for (auto field : optimized_order_) {
// Skip fields that do not have has bits.
if (field->is_repeated()) {
continue;
@@ -472,16 +647,7 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
has_bit_indices_[field->index()] = max_has_bit_index_++;
}
- }
-
- for (int i = 0; i < descriptor->enum_type_count(); i++) {
- enum_generators_[i].reset(
- new EnumGenerator(descriptor->enum_type(i), options));
- }
-
- for (int i = 0; i < descriptor->extension_count(); i++) {
- extension_generators_[i].reset(
- new ExtensionGenerator(descriptor->extension(i), options));
+ field_generators_.SetHasBitIndices(has_bit_indices_);
}
num_required_fields_ = 0;
@@ -492,12 +658,9 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
}
table_driven_ = TableDrivenParsingEnabled(descriptor_, options_);
-
- scc_name_ =
- ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative(), false);
}
-MessageGenerator::~MessageGenerator() {}
+MessageGenerator::~MessageGenerator() = default;
size_t MessageGenerator::HasBitsSize() const {
size_t sizeof_has_bits = (max_has_bit_index_ + 31) / 32 * 4;
@@ -513,23 +676,22 @@ size_t MessageGenerator::HasBitsSize() const {
}
void MessageGenerator::AddGenerators(
- std::vector<EnumGenerator*>* enum_generators,
- std::vector<ExtensionGenerator*>* extension_generators) {
+ std::vector<std::unique_ptr<EnumGenerator>>* enum_generators,
+ std::vector<std::unique_ptr<ExtensionGenerator>>* extension_generators) {
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
- enum_generators->push_back(enum_generators_[i].get());
+ enum_generators->emplace_back(
+ new EnumGenerator(descriptor_->enum_type(i), variables_, options_));
+ enum_generators_.push_back(enum_generators->back().get());
}
for (int i = 0; i < descriptor_->extension_count(); i++) {
- extension_generators->push_back(extension_generators_[i].get());
+ extension_generators->emplace_back(
+ new ExtensionGenerator(descriptor_->extension(i), options_));
+ extension_generators_.push_back(extension_generators->back().get());
}
}
-void MessageGenerator::FillMessageForwardDeclarations(
- std::map<string, const Descriptor*>* class_names) {
- (*class_names)[classname_] = descriptor_;
-}
-
-void MessageGenerator::
-GenerateFieldAccessorDeclarations(io::Printer* printer) {
+void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) {
+ Formatter format(printer, variables_);
// optimized_fields_ does not contain fields where
// field->containing_oneof() != NULL
// so we need to iterate over those as well.
@@ -540,77 +702,75 @@ GenerateFieldAccessorDeclarations(io::Printer* printer) {
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);
+ ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(),
+ optimized_order_.end());
+ for (auto field : FieldRange(descriptor_)) {
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];
+ for (auto field : ordered_fields) {
+ PrintFieldComment(format, field);
- PrintFieldComment(printer, field);
+ Formatter::SaveState save(&format);
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
- vars["constant_name"] = FieldConstantName(field);
+ format.AddMap(vars);
if (field->is_repeated()) {
- printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n");
- printer->Annotate("{", "}", field);
+ format("$deprecated_attr$int ${1$$name$_size$}$() const;\n", field);
} else if (HasHasMethod(field)) {
- printer->Print(vars, "$deprecated_attr$bool ${$has_$name$$}$() const;\n");
- printer->Annotate("{", "}", field);
+ format("$deprecated_attr$bool ${1$has_$name$$}$() const;\n", field);
} else if (HasPrivateHasMethod(field)) {
- printer->Print(vars,
- "private:\n"
- "bool ${$has_$name$$}$() const;\n"
- "public:\n");
- printer->Annotate("{", "}", field);
+ format(
+ "private:\n"
+ "bool ${1$has_$name$$}$() const;\n"
+ "public:\n",
+ field);
}
- 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);
+ format(
+ "$deprecated_attr$void ${1$clear_$name$$}$();\n"
+ "$deprecated_attr$static const int ${1$$2$$}$ = $number$;\n",
+ field, FieldConstantName(field));
// Generate type-specific accessor declarations.
field_generators_.get(field).GenerateAccessorDeclarations(printer);
- printer->Print("\n");
+ format("\n");
}
if (descriptor_->extension_range_count() > 0) {
// Generate accessors for extensions. We just call a macro located in
// extension_set.h since the accessors about 80 lines of static code.
- printer->Print(
- "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
- "classname", classname_);
+ format("$GOOGLE_PROTOBUF$_EXTENSION_ACCESSORS($classname$)\n");
+ // Generate MessageSet specific APIs for proto2 MessageSet.
+ // For testing purposes we don't check for bridge.MessageSet, so
+ // we don't use IsProto2MessageSet
+ if (descriptor_->options().message_set_wire_format() &&
+ !options_.opensource_runtime && !options_.lite_implicit_weak_fields) {
+ // Special-case MessageSet
+ format("GOOGLE_PROTOBUF_EXTENSION_MESSAGE_SET_ACCESSORS($classname$)\n");
+ }
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
+ for (auto oneof : OneOfRange(descriptor_)) {
+ Formatter::SaveState saver(&format);
+ format.Set("oneof_name", oneof->name());
+ format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true));
+ format(
"void clear_$oneof_name$();\n"
- "$camel_oneof_name$Case $oneof_name$_case() const;\n",
- "camel_oneof_name",
- UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true),
- "oneof_name", descriptor_->oneof_decl(i)->name());
+ "$camel_oneof_name$Case $oneof_name$_case() const;\n");
}
}
-void MessageGenerator::
-GenerateSingularFieldHasBits(const FieldDescriptor* field,
- std::map<string, string> vars,
- io::Printer* printer) {
+void MessageGenerator::GenerateSingularFieldHasBits(
+ const FieldDescriptor* field, Formatter format) {
if (field->options().weak()) {
- printer->Print(
- vars,
+ format(
"inline bool $classname$::has_$name$() const {\n"
" return _weak_field_map_.Has($number$);\n"
"}\n");
@@ -622,31 +782,23 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
int has_bit_index = has_bit_indices_[field->index()];
GOOGLE_CHECK_GE(has_bit_index, 0);
- vars["has_array_index"] = SimpleItoa(has_bit_index / 32);
- 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"
- " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
- "}\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"
- " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
- "}\n");
+ format.Set("has_array_index", has_bit_index / 32);
+ format.Set("has_mask",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format(
+ "inline bool $classname$::has_$name$() const {\n"
+ " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
+ "}\n");
} else {
// Message fields have a has_$name$() method.
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- bool is_lazy = false;
- if (is_lazy) {
- printer->Print(vars,
- "inline bool $classname$::has_$name$() const {\n"
- " return !$name$_.IsCleared();\n"
- "}\n");
+ if (IsLazy(field, options_)) {
+ format(
+ "inline bool $classname$::has_$name$() const {\n"
+ " return !$name$_.IsCleared();\n"
+ "}\n");
} else {
- printer->Print(
- vars,
+ format(
"inline bool $classname$::has_$name$() const {\n"
" return this != internal_default_instance() && $name$_ != NULL;\n"
"}\n");
@@ -655,17 +807,13 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
}
}
-void MessageGenerator::
-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();
- vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
- vars["cap_oneof_name"] =
- ToUpper(descriptor_->oneof_decl(i)->name());
- vars["classname"] = classname_;
- printer->Print(
- vars,
+void MessageGenerator::GenerateOneofHasBits(io::Printer* printer) {
+ Formatter format(printer, variables_);
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format.Set("oneof_name", oneof->name());
+ format.Set("oneof_index", oneof->index());
+ format.Set("cap_oneof_name", ToUpper(oneof->name()));
+ format(
"inline bool $classname$::has_$oneof_name$() const {\n"
" return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n"
"}\n"
@@ -675,168 +823,157 @@ GenerateOneofHasBits(io::Printer* printer) {
}
}
-void MessageGenerator::
-GenerateOneofMemberHasBits(const FieldDescriptor* field,
- const std::map<string, string>& vars,
- io::Printer* printer) {
+void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field,
+ const Formatter& format) {
// Singular field in a oneof
// N.B.: Without field presence, we do not use has-bits or generate
// has_$name$() methods, but oneofs still have set_has_$name$().
// Oneofs also have has_$name$() but only as a private helper
// 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"
- " return $oneof_name$_case() == k$field_name$;\n"
- "}\n");
- printer->Print(vars,
- "inline void $classname$::set_has_$name$() {\n"
- " _oneof_case_[$oneof_index$] = k$field_name$;\n"
- "}\n");
+ format(
+ "inline bool $classname$::has_$name$() const {\n"
+ " return $oneof_name$_case() == k$field_name$;\n"
+ "}\n"
+ "inline void $classname$::set_has_$name$() {\n"
+ " _oneof_case_[$oneof_index$] = k$field_name$;\n"
+ "}\n");
}
-void MessageGenerator::
-GenerateFieldClear(const FieldDescriptor* field,
- const std::map<string, string>& vars,
- bool is_inline,
- io::Printer* printer) {
+void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field,
+ bool is_inline,
+ Formatter format) {
// Generate clear_$name$().
if (is_inline) {
- printer->Print("inline ");
+ format("inline ");
}
- printer->Print(vars,
- "void $classname$::clear_$name$() {\n");
+ format("void $classname$::clear_$name$() {\n");
- printer->Indent();
+ format.Indent();
if (field->containing_oneof()) {
// Clear this field only if it is the active field in this oneof,
// otherwise ignore
- printer->Print(vars,
- "if (has_$name$()) {\n");
- printer->Indent();
- field_generators_.get(field)
- .GenerateClearingCode(printer);
- printer->Print(vars,
- "clear_has_$oneof_name$();\n");
- printer->Outdent();
- printer->Print("}\n");
+ format("if (has_$name$()) {\n");
+ format.Indent();
+ field_generators_.get(field).GenerateClearingCode(format.printer());
+ format("clear_has_$oneof_name$();\n");
+ format.Outdent();
+ format("}\n");
} else {
- field_generators_.get(field)
- .GenerateClearingCode(printer);
+ field_generators_.get(field).GenerateClearingCode(format.printer());
if (HasFieldPresence(descriptor_->file())) {
if (!field->is_repeated() && !field->options().weak()) {
- printer->Print(vars, "clear_has_$name$();\n");
+ int has_bit_index = has_bit_indices_[field->index()];
+ GOOGLE_CHECK_GE(has_bit_index, 0);
+
+ format.Set("has_array_index", has_bit_index / 32);
+ format.Set("has_mask",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n");
}
}
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateFieldAccessorDefinitions(io::Printer* printer) {
- printer->Print("// $classname$\n\n", "classname", classname_);
+void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) {
+ Formatter format(printer, variables_);
+ format("// $classname$\n\n");
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
-
- PrintFieldComment(printer, field);
+ for (auto field : FieldRange(descriptor_)) {
+ PrintFieldComment(format, field);
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
+ Formatter::SaveState saver(&format);
+ format.AddMap(vars);
+
// Generate has_$name$() or $name$_size().
if (field->is_repeated()) {
- printer->Print(vars,
- "inline int $classname$::$name$_size() const {\n"
- " return $name$_.size();\n"
- "}\n");
+ format(
+ "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());
- GenerateOneofMemberHasBits(field, vars, printer);
+ format.Set("field_name", UnderscoresToCamelCase(field->name(), true));
+ format.Set("oneof_name", field->containing_oneof()->name());
+ format.Set("oneof_index",
+ SimpleItoa(field->containing_oneof()->index()));
+ GenerateOneofMemberHasBits(field, format);
} else {
// Singular field.
- GenerateSingularFieldHasBits(field, vars, printer);
+ GenerateSingularFieldHasBits(field, format);
}
if (!IsCrossFileMaybeMap(field)) {
- GenerateFieldClear(field, vars, true, printer);
+ GenerateFieldClear(field, true, format);
}
// Generate type-specific accessors.
field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
- printer->Print("\n");
+ format("\n");
}
// Generate has_$name$() and clear_has_$name$() functions for oneofs.
GenerateOneofHasBits(printer);
}
-void MessageGenerator::
-GenerateClassDefinition(io::Printer* printer) {
+void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (IsMapEntryMessage(descriptor_)) {
std::map<string, string> vars;
- vars["classname"] = classname_;
- CollectMapInfo(descriptor_, &vars);
+ CollectMapInfo(options_, descriptor_, &vars);
vars["lite"] =
HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite";
- printer->Print(
- vars,
+ format.AddMap(vars);
+ format(
"class $classname$ : public "
- "::google::protobuf::internal::MapEntry$lite$<$classname$, \n"
+ "::$proto_ns$::internal::MapEntry$lite$<$classname$, \n"
" $key_cpp$, $val_cpp$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
" $default_enum_value$ > {\n"
"public:\n"
- " typedef ::google::protobuf::internal::MapEntry$lite$<$classname$, \n"
+ "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ "static bool _ParseMap(const char* begin, const "
+ "char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);\n"
+ "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ " typedef ::$proto_ns$::internal::MapEntry$lite$<$classname$, \n"
" $key_cpp$, $val_cpp$,\n"
- " $key_wire_type$,\n"
- " $val_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
+ " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
" $default_enum_value$ > SuperType;\n"
" $classname$();\n"
- " $classname$(::google::protobuf::Arena* arena);\n"
+ " $classname$(::$proto_ns$::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) final;\n"
- " ::google::protobuf::Metadata GetMetadata() const;\n"
+ format(
+ " void MergeFrom(const ::$proto_ns$::Message& other) final;\n"
+ " ::$proto_ns$::Metadata GetMetadata() const;\n"
"};\n");
} else {
- printer->Print("};\n");
+ format("};\n");
}
return;
}
- std::map<string, string> vars;
- vars["classname"] = classname_;
- vars["full_name"] = descriptor_->full_name();
- vars["field_count"] = SimpleItoa(descriptor_->field_count());
- vars["oneof_decl_count"] = SimpleItoa(descriptor_->oneof_decl_count());
- if (options_.dllexport_decl.empty()) {
- vars["dllexport"] = "";
- } else {
- vars["dllexport"] = options_.dllexport_decl + " ";
- }
- vars["superclass"] = SuperClassName(descriptor_, options_);
- printer->Print(vars,
- "class $dllexport$$classname$ : public $superclass$ "
- "/* @@protoc_insertion_point(class_definition:$full_name$) */ "
- "{\n");
- printer->Annotate("classname", descriptor_);
- printer->Print(" public:\n");
- printer->Indent();
-
- printer->Print(
- vars,
+ format(
+ "class $dllexport_decl $${1$$classname$$}$ : public $superclass$ "
+ "/* @@protoc_insertion_point(class_definition:$full_name$) */ "
+ "{\n",
+ descriptor_);
+ format(" public:\n");
+ format.Indent();
+
+ format(
"$classname$();\n"
"virtual ~$classname$();\n"
"\n"
@@ -848,34 +985,36 @@ GenerateClassDefinition(io::Printer* printer) {
"}\n");
if (options_.table_driven_serialization) {
- printer->Print(
- "private:\n"
- "const void* InternalGetTable() const;\n"
- "public:\n"
- "\n");
+ format(
+ "private:\n"
+ "const void* InternalGetTable() const;\n"
+ "public:\n"
+ "\n");
}
// Generate move constructor and move assignment operator.
- printer->Print(vars,
- "#if LANG_CXX11\n"
- "$classname$($classname$&& from) noexcept\n"
- " : $classname$() {\n"
- " *this = ::std::move(from);\n"
- "}\n"
- "\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"
- "#endif\n");
+ format(
+ "#if LANG_CXX11\n"
+ "$classname$($classname$&& from) noexcept\n"
+ " : $classname$() {\n"
+ " *this = ::std::move(from);\n"
+ "}\n"
+ "\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"
+ "#endif\n");
+ std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
if (PublicUnknownFieldsAccessors(descriptor_)) {
- printer->Print(vars,
+ format(
"inline const $unknown_fields_type$& unknown_fields() const {\n"
" return $unknown_fields$;\n"
"}\n"
@@ -889,10 +1028,10 @@ GenerateClassDefinition(io::Printer* printer) {
// MessageLite's implementation which returns NULL rather than generating our
// own method which returns NULL, in order to reduce code size.
if (SupportsArenas(descriptor_)) {
- // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a
- // MessageLite* (e.g., in RepeatedField::AddAllocated()).
- printer->Print(
- "inline ::google::protobuf::Arena* GetArena() const final {\n"
+ // virtual method version of GetArenaNoVirtual(), required for generic
+ // dispatch given a MessageLite* (e.g., in RepeatedField::AddAllocated()).
+ format(
+ "inline ::$proto_ns$::Arena* GetArena() const final {\n"
" return GetArenaNoVirtual();\n"
"}\n"
"inline void* GetMaybeArenaPointer() const final {\n"
@@ -903,229 +1042,240 @@ GenerateClassDefinition(io::Printer* printer) {
// Only generate this member if it's not disabled.
if (HasDescriptorMethods(descriptor_->file(), options_) &&
!descriptor_->options().no_standard_descriptor_accessor()) {
- printer->Print(vars,
- "static const ::google::protobuf::Descriptor* descriptor();\n");
+ format(
+ "static const ::$proto_ns$::Descriptor* descriptor() {\n"
+ " return default_instance().GetDescriptor();\n"
+ "}\n");
}
- printer->Print(vars,
- "static const $classname$& default_instance();\n"
- "\n");
+ format(
+ "static const $classname$& default_instance();\n"
+ "\n");
// Generate enum values for every field in oneofs. One list is generated for
// each oneof with an additional *_NOT_SET value.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "enum $camel_oneof_name$Case {\n",
- "camel_oneof_name",
- UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- printer->Print(
- "k$field_name$ = $field_number$,\n",
- "field_name",
- UnderscoresToCamelCase(
- descriptor_->oneof_decl(i)->field(j)->name(), true),
- "field_number",
- SimpleItoa(descriptor_->oneof_decl(i)->field(j)->number()));
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("enum $1$Case {\n", UnderscoresToCamelCase(oneof->name(), true));
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ string oneof_enum_case_field_name =
+ UnderscoresToCamelCase(field->name(), true);
+ format("k$1$ = $2$,\n", oneof_enum_case_field_name, // 1
+ field->number()); // 2
}
- printer->Print(
- "$cap_oneof_name$_NOT_SET = 0,\n",
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
+ format("$1$_NOT_SET = 0,\n", ToUpper(oneof->name()));
+ format.Outdent();
+ format(
"};\n"
"\n");
}
// TODO(gerbens) make this private, while still granting other protos access.
- vars["message_index"] = SimpleItoa(index_in_file_messages_);
- printer->Print(
- vars,
+ format(
"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 constexpr int kIndexInFileMessages =\n"
- " $message_index$;\n"
- "\n");
+ " $1$;\n"
+ "\n", index_in_file_messages_);
if (SupportsArenas(descriptor_)) {
- printer->Print(vars,
- "void UnsafeArenaSwap($classname$* other);\n");
+ format("void UnsafeArenaSwap($classname$* other);\n");
}
if (IsAnyMessage(descriptor_)) {
- printer->Print(vars,
- "// implements Any -----------------------------------------------\n"
- "\n"
- "void PackFrom(const ::google::protobuf::Message& message);\n"
- "void PackFrom(const ::google::protobuf::Message& message,\n"
- " const ::std::string& type_url_prefix);\n"
- "bool UnpackTo(::google::protobuf::Message* message) const;\n"
- "template<typename T> bool Is() const {\n"
- " return _any_metadata_.Is<T>();\n"
- "}\n"
- "static bool ParseAnyTypeUrl(const string& type_url,\n"
- " string* full_type_name);\n"
- "\n");
+ format(
+ "// implements Any -----------------------------------------------\n"
+ "\n"
+ "void PackFrom(const ::$proto_ns$::Message& message);\n"
+ "void PackFrom(const ::$proto_ns$::Message& message,\n"
+ " const $string$& type_url_prefix);\n"
+ "bool UnpackTo(::$proto_ns$::Message* message) const;\n"
+ "template<typename T> bool Is() const {\n"
+ " return _any_metadata_.Is<T>();\n"
+ "}\n"
+ "static bool ParseAnyTypeUrl(const string& type_url,\n"
+ " string* full_type_name);\n"
+ "static bool GetAnyFieldDescriptors(\n"
+ " const ::$proto_ns$::Message& message,\n"
+ " const ::$proto_ns$::FieldDescriptor** type_url_field,\n"
+ " const ::$proto_ns$::FieldDescriptor** value_field);\n");
}
- vars["new_final"] = " final";
-
- 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"
- "inline $classname$* New() const$new_final$ {\n"
- " return CreateMaybeMessage<$classname$>(NULL);\n"
- "}\n"
- "\n"
- "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n"
- " return CreateMaybeMessage<$classname$>(arena);\n"
- "}\n");
+ format.Set("new_final",
+ ShouldMarkNewAsFinal(descriptor_, options_) ? "final" : "");
+
+ format(
+ "void Swap($classname$* other);\n"
+ "friend void swap($classname$& a, $classname$& b) {\n"
+ " a.Swap(&b);\n"
+ "}\n"
+ "\n"
+ "// implements Message ----------------------------------------------\n"
+ "\n"
+ "inline $classname$* New() const$ new_final$ {\n"
+ " return CreateMaybeMessage<$classname$>(NULL);\n"
+ "}\n"
+ "\n"
+ "$classname$* New(::$proto_ns$::Arena* arena) const$ new_final$ {\n"
+ " return CreateMaybeMessage<$classname$>(arena);\n"
+ "}\n");
// For instances that derive from Message (rather than MessageLite), some
// methods are virtual and should be marked as final.
- string use_final = HasDescriptorMethods(descriptor_->file(), options_) ?
- " final" : "";
+ format.Set("full_final", HasDescriptorMethods(descriptor_->file(), options_)
+ ? "final"
+ : "");
if (HasGeneratedMethods(descriptor_->file(), options_)) {
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(vars,
- "void CopyFrom(const ::google::protobuf::Message& from) final;\n"
- "void MergeFrom(const ::google::protobuf::Message& from) final;\n");
+ format(
+ "void CopyFrom(const ::$proto_ns$::Message& from) final;\n"
+ "void MergeFrom(const ::$proto_ns$::Message& from) final;\n");
} else {
- printer->Print(vars,
- "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n"
- " final;\n");
+ format(
+ "void CheckTypeAndMergeFrom(const ::$proto_ns$::MessageLite& from)\n"
+ " final;\n");
}
- vars["clear_final"] = " final";
- vars["is_initialized_final"] = " final";
- vars["merge_partial_final"] = " final";
+ format.Set("clear_final",
+ ShouldMarkClearAsFinal(descriptor_, options_) ? "final" : "");
+ format.Set(
+ "is_initialized_final",
+ ShouldMarkIsInitializedAsFinal(descriptor_, options_) ? "final" : "");
+ format.Set(
+ "merge_partial_final",
+ ShouldMarkMergePartialAsFinal(descriptor_, options_) ? "final" : "");
- printer->Print(
- vars,
+ format(
"void CopyFrom(const $classname$& from);\n"
"void MergeFrom(const $classname$& from);\n"
- "void Clear()$clear_final$;\n"
- "bool IsInitialized() const$is_initialized_final$;\n"
+ "void Clear()$ clear_final$;\n"
+ "bool IsInitialized() const$ is_initialized_final$;\n"
"\n"
"size_t ByteSizeLong() const final;\n"
+ "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ "static const char* _InternalParse(const char* begin, const char* end, "
+ "void* object, ::$proto_ns$::internal::ParseContext* ctx);\n"
+ "::$proto_ns$::internal::ParseFunc _ParseFunc() const final { return "
+ "_InternalParse; }\n"
+ "#else\n"
"bool MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n");
+ " ::$proto_ns$::io::CodedInputStream* input)$ "
+ "merge_partial_final$;\n"
+ "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
+ if (descriptor_->options().message_set_wire_format()) {
+ format(
+ "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ "static const char* InternalParseMessageSetItem(const char* begin, "
+ "const char* end, void* object, "
+ "::$proto_ns$::internal::ParseContext* "
+ "ctx);\n"
+ "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
+ }
+
if (!options_.table_driven_serialization ||
descriptor_->options().message_set_wire_format()) {
- printer->Print(
+ format(
"void SerializeWithCachedSizes(\n"
- " ::google::protobuf::io::CodedOutputStream* output) const "
- "final;\n");
+ " ::$proto_ns$::io::CodedOutputStream* output) const 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_)) {
- printer->Print(
- "void DiscardUnknownFields()$final$;\n",
- "final", use_final);
+ format("void DiscardUnknownFields()$ full_final$;\n");
}
if (HasFastArraySerialization(descriptor_->file(), options_)) {
- printer->Print(
- "::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n"
- " bool deterministic, ::google::protobuf::uint8* target) const final;\n");
+ format(
+ "$uint8$* InternalSerializeWithCachedSizesToArray(\n"
+ " bool deterministic, $uint8$* target) const final;\n");
}
}
- printer->Print(
+ format(
"int GetCachedSize() const final { return _cached_size_.Get(); }"
"\n\nprivate:\n"
"void SharedCtor();\n"
"void SharedDtor();\n"
- "void SetCachedSize(int size) const$final$;\n"
- "void InternalSwap($classname$* other);\n",
- "classname", classname_, "final", use_final);
+ "void SetCachedSize(int size) const$ full_final$;\n"
+ "void InternalSwap($classname$* other);\n");
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"
- "static void ArenaDtor(void* object);\n"
- "inline void RegisterArenaDtor(::google::protobuf::Arena* arena);\n",
- "classname", classname_);
+ format(
+ // 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$(::$proto_ns$::Arena* arena);\n"
+ "private:\n"
+ "static void ArenaDtor(void* object);\n"
+ "inline void RegisterArenaDtor(::$proto_ns$::Arena* arena);\n");
}
if (SupportsArenas(descriptor_)) {
- printer->Print(
- "private:\n"
- "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n"
- " return _internal_metadata_.arena();\n"
- "}\n"
- "inline void* MaybeArenaPtr() const {\n"
- " return _internal_metadata_.raw_arena_ptr();\n"
- "}\n");
+ format(
+ "private:\n"
+ "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
+ " return _internal_metadata_.arena();\n"
+ "}\n"
+ "inline void* MaybeArenaPtr() const {\n"
+ " return _internal_metadata_.raw_arena_ptr();\n"
+ "}\n");
} else {
- printer->Print(
- "private:\n"
- "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n"
- " return NULL;\n"
- "}\n"
- "inline void* MaybeArenaPtr() const {\n"
- " return NULL;\n"
- "}\n");
+ format(
+ "private:\n"
+ "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
+ " return NULL;\n"
+ "}\n"
+ "inline void* MaybeArenaPtr() const {\n"
+ " return NULL;\n"
+ "}\n");
}
- printer->Print(
+ format(
"public:\n"
"\n");
if (HasDescriptorMethods(descriptor_->file(), options_)) {
- printer->Print(
- "::google::protobuf::Metadata GetMetadata() const final;\n"
- "\n");
+ format(
+ "::$proto_ns$::Metadata GetMetadata() const final;\n"
+ "\n");
} else {
- printer->Print(
- "::std::string GetTypeName() const final;\n"
- "\n");
+ format(
+ "$string$ GetTypeName() const final;\n"
+ "\n");
}
- printer->Print(
- "// nested types ----------------------------------------------------\n"
- "\n");
+ format(
+ "// nested types ----------------------------------------------------\n"
+ "\n");
// Import all nested message classes into this class's scope with typedefs.
for (int i = 0; i < descriptor_->nested_type_count(); i++) {
const Descriptor* nested_type = descriptor_->nested_type(i);
if (!IsMapEntryMessage(nested_type)) {
- 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);
+ format.Set("nested_full_name", ClassName(nested_type, false));
+ format.Set("nested_name", nested_type->name());
+ format("typedef ${1$$nested_full_name$$}$ ${1$$nested_name$$}$;\n",
+ nested_type);
}
}
if (descriptor_->nested_type_count() > 0) {
- printer->Print("\n");
+ format("\n");
}
// Import all nested enums and their values into this class's scope with
// typedefs and constants.
for (int i = 0; i < descriptor_->enum_type_count(); i++) {
enum_generators_[i]->GenerateSymbolImports(printer);
- printer->Print("\n");
+ format("\n");
}
- printer->Print(
- "// accessors -------------------------------------------------------\n"
- "\n");
+ format(
+ "// accessors -------------------------------------------------------\n"
+ "\n");
// Generate accessor methods for all fields.
GenerateFieldAccessorDeclarations(printer);
@@ -1136,49 +1286,37 @@ GenerateClassDefinition(io::Printer* printer) {
}
- printer->Print(
- "// @@protoc_insertion_point(class_scope:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format("// @@protoc_insertion_point(class_scope:$full_name$)\n");
// Generate private members.
- printer->Outdent();
- printer->Print(" private:\n");
- printer->Indent();
-
-
- for (int i = 0; i < descriptor_->field_count(); i++) {
- 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()) ||
- descriptor_->field(i)->containing_oneof()) {
- printer->Print("void set_has_$name$();\n", "name",
- FieldName(descriptor_->field(i)));
- }
- // clear_has_***() generated only for non-oneof fields
- // in proto1/2.
- if (!descriptor_->field(i)->containing_oneof() &&
- HasFieldPresence(descriptor_->file())) {
- printer->Print("void clear_has_$name$();\n", "name",
- FieldName(descriptor_->field(i)));
- }
+ format.Outdent();
+ format(" private:\n");
+ format.Indent();
+ // TODO(seongkim): Remove hack to track field access and remove this class.
+ format("class HasBitSetters;\n");
+
+
+ for (auto field : FieldRange(descriptor_)) {
+ // set_has_***() generated in all oneofs.
+ if (!field->is_repeated() && !field->options().weak() &&
+ field->containing_oneof()) {
+ format("void set_has_$1$();\n", FieldName(field));
}
}
- printer->Print("\n");
+ format("\n");
// Generate oneof function declarations
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "inline bool has_$oneof_name$() const;\n"
- "inline void clear_has_$oneof_name$();\n\n",
- "oneof_name", descriptor_->oneof_decl(i)->name());
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format(
+ "inline bool has_$1$() const;\n"
+ "inline void clear_has_$1$();\n\n",
+ oneof->name());
}
if (HasGeneratedMethods(descriptor_->file(), options_) &&
!descriptor_->options().message_set_wire_format() &&
num_required_fields_ > 1) {
- printer->Print(
+ format(
"// helper for ByteSizeLong()\n"
"size_t RequiredFieldsByteSizeFallback() const;\n\n");
}
@@ -1187,14 +1325,15 @@ GenerateClassDefinition(io::Printer* printer) {
// output will be determined later.
bool need_to_emit_cached_size = true;
- // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
const string cached_size_decl =
- "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n";
+ "mutable ::$proto_ns$::internal::CachedSize _cached_size_;\n";
const size_t sizeof_has_bits = HasBitsSize();
- const string has_bits_decl = sizeof_has_bits == 0 ? "" :
- "::google::protobuf::internal::HasBits<" + SimpleItoa(sizeof_has_bits / 4) +
- "> _has_bits_;\n";
+ const string has_bits_decl =
+ sizeof_has_bits == 0
+ ? ""
+ : "::$proto_ns$::internal::HasBits<" +
+ SimpleItoa(sizeof_has_bits / 4) + "> _has_bits_;\n";
// To minimize padding, data members are divided into three sections:
// (1) members assumed to align to 8 bytes
@@ -1205,154 +1344,142 @@ GenerateClassDefinition(io::Printer* printer) {
// Members assumed to align to 8 bytes:
if (descriptor_->extension_range_count() > 0) {
- printer->Print(
- "::google::protobuf::internal::ExtensionSet _extensions_;\n"
- "\n");
+ format(
+ "::$proto_ns$::internal::ExtensionSet _extensions_;\n"
+ "\n");
}
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(
- "::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;\n");
+ format(
+ "::$proto_ns$::internal::InternalMetadataWithArena "
+ "_internal_metadata_;\n");
} else {
- printer->Print(
- "::google::protobuf::internal::InternalMetadataWithArenaLite "
+ format(
+ "::$proto_ns$::internal::InternalMetadataWithArenaLite "
"_internal_metadata_;\n");
}
if (SupportsArenas(descriptor_)) {
- printer->Print(
- "template <typename T> friend class ::google::protobuf::Arena::InternalHelper;\n"
- "typedef void InternalArenaConstructable_;\n"
- "typedef void DestructorSkippable_;\n");
+ if (!options_.opensource_runtime) {
+ format(
+ "template <typename T> friend struct "
+ "::proto::internal::EmbeddedMessageHolder;\n");
+ }
+ format(
+ "template <typename T> friend class "
+ "::$proto_ns$::Arena::InternalHelper;\n"
+ "typedef void InternalArenaConstructable_;\n"
+ "typedef void DestructorSkippable_;\n");
}
if (HasFieldPresence(descriptor_->file())) {
// _has_bits_ is frequently accessed, so to reduce code size and improve
- // speed, it should be close to the start of the object. But, try not to
- // waste space:_has_bits_ by itself always makes sense if its size is a
- // multiple of 8, but, otherwise, maybe _has_bits_ and cached_size_ together
- // will work well.
- printer->Print(has_bits_decl.c_str());
- if ((sizeof_has_bits % 8) != 0) {
- printer->Print(cached_size_decl.c_str());
- need_to_emit_cached_size = false;
- }
+ // speed, it should be close to the start of the object. Placing
+ // _cached_size_ together with _has_bits_ improves cache locality despite
+ // potential alignment padding.
+ format(has_bits_decl.c_str());
+ format(cached_size_decl.c_str());
+ need_to_emit_cached_size = false;
}
// Field members:
// Emit some private and static members
- for (int i = 0; i < optimized_order_.size(); ++i) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
const FieldGenerator& generator = field_generators_.get(field);
generator.GenerateStaticMembers(printer);
generator.GeneratePrivateMembers(printer);
}
// For each oneof generate a union
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "union $camel_oneof_name$Union {\n"
+ for (auto oneof : OneOfRange(descriptor_)) {
+ string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true);
+ format(
+ "union $1$Union {\n"
// explicit empty constructor is needed when union contains
// ArenaStringPtr members for string fields.
- " $camel_oneof_name$Union() {}\n",
- "camel_oneof_name",
- UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- field_generators_.get(descriptor_->oneof_decl(i)->
- field(j)).GeneratePrivateMembers(printer);
+ " $1$Union() {}\n",
+ camel_oneof_name);
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ field_generators_.get(field).GeneratePrivateMembers(printer);
}
- printer->Outdent();
- printer->Print(
- "} $oneof_name$_;\n",
- "oneof_name", descriptor_->oneof_decl(i)->name());
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- field_generators_.get(descriptor_->oneof_decl(i)->
- field(j)).GenerateStaticMembers(printer);
+ format.Outdent();
+ format("} $1$_;\n", oneof->name());
+ for (auto field : FieldRange(oneof)) {
+ field_generators_.get(field).GenerateStaticMembers(printer);
}
}
// Members assumed to align to 4 bytes:
if (need_to_emit_cached_size) {
- printer->Print(cached_size_decl.c_str());
+ format(cached_size_decl.c_str());
need_to_emit_cached_size = false;
}
// Generate _oneof_case_.
if (descriptor_->oneof_decl_count() > 0) {
- printer->Print(vars,
- "::google::protobuf::uint32 _oneof_case_[$oneof_decl_count$];\n"
- "\n");
+ format(
+ "$uint32$ _oneof_case_[$1$];\n"
+ "\n",
+ descriptor_->oneof_decl_count());
}
if (num_weak_fields_) {
- printer->Print(
- "::google::protobuf::internal::WeakFieldMap _weak_field_map_;\n");
+ format("::$proto_ns$::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");
+ format("::$proto_ns$::internal::AnyMetadata _any_metadata_;\n");
}
// The TableStruct struct needs access to the private parts, in order to
// construct the offsets of all members.
- printer->Print("friend struct ::$file_namespace$::TableStruct;\n",
- // Vars.
- "scc_name", scc_name_, "file_namespace",
- FileLevelNamespace(descriptor_));
+ format("friend struct ::$tablename$;\n");
- printer->Outdent();
- printer->Print("};");
+ format.Outdent();
+ format("};");
GOOGLE_DCHECK(!need_to_emit_cached_size);
}
-void MessageGenerator::
-GenerateInlineMethods(io::Printer* printer) {
+void MessageGenerator::GenerateInlineMethods(io::Printer* printer) {
if (IsMapEntryMessage(descriptor_)) return;
GenerateFieldAccessorDefinitions(printer);
// Generate oneof_case() functions.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- std::map<string, string> vars;
- vars["class_name"] = classname_;
- vars["camel_oneof_name"] = UnderscoresToCamelCase(
- descriptor_->oneof_decl(i)->name(), true);
- vars["oneof_name"] = descriptor_->oneof_decl(i)->name();
- vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
- printer->Print(
- vars,
- "inline $class_name$::$camel_oneof_name$Case $class_name$::"
+ for (auto oneof : OneOfRange(descriptor_)) {
+ Formatter format(printer, variables_);
+ format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true));
+ format.Set("oneof_name", oneof->name());
+ format.Set("oneof_index", oneof->index());
+ format(
+ "inline $classname$::$camel_oneof_name$Case $classname$::"
"$oneof_name$_case() const {\n"
- " return $class_name$::$camel_oneof_name$Case("
+ " return $classname$::$camel_oneof_name$Case("
"_oneof_case_[$oneof_index$]);\n"
"}\n");
}
}
-void MessageGenerator::
-GenerateExtraDefaultFields(io::Printer* printer) {
+void MessageGenerator::GenerateExtraDefaultFields(io::Printer* printer) {
// Generate oneof default instance and weak field instances for reflection
// usage.
+ Formatter format(printer, variables_);
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);
+ for (auto oneof : OneOfRange(descriptor_)) {
+ for (auto field : FieldRange(oneof)) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
(field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
- EffectiveStringCType(field) != FieldOptions::STRING)) {
- printer->Print("const ");
+ EffectiveStringCType(field, options_) != FieldOptions::STRING)) {
+ format("const ");
}
field_generators_.get(field).GeneratePrivateMembers(printer);
}
}
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
+ for (auto field : FieldRange(descriptor_)) {
if (field->options().weak()) {
- printer->Print(
- " const ::google::protobuf::Message* $name$_;\n", "name", FieldName(field));
+ format(" const ::$proto_ns$::Message* $1$_;\n", FieldName(field));
}
}
}
@@ -1360,130 +1487,78 @@ GenerateExtraDefaultFields(io::Printer* printer) {
bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset,
size_t aux_offset) {
+ Formatter format(printer, variables_);
+
if (!table_driven_) {
- printer->Print("{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },\n");
+ format("{ 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);
+ for (auto field : FieldRange(descriptor_)) {
if (max_field_number < field->number()) {
max_field_number = field->number();
}
}
- vars["max_field_number"] = SimpleItoa(max_field_number);
-
- printer->Print("{\n");
- printer->Indent();
+ format("{\n");
+ format.Indent();
- printer->Print(vars,
- "TableStruct::entries + $offset$,\n"
- "TableStruct::aux + $aux_offset$,\n"
- "$max_field_number$,\n");
+ format(
+ "$tablename$::entries + $1$,\n"
+ "$tablename$::aux + $2$,\n"
+ "$3$,\n",
+ offset, aux_offset, max_field_number);
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have field presence, then _has_bits_ does not exist.
- printer->Print(vars, "-1,\n");
+ format("-1,\n");
} else {
- printer->Print(vars,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
- " $classtype$, _has_bits_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
}
if (descriptor_->oneof_decl_count() > 0) {
- printer->Print(vars,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
- " $classtype$, _oneof_case_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n");
} else {
- printer->Print("-1, // no _oneof_case_\n");
+ format("-1, // no _oneof_case_\n");
}
if (descriptor_->extension_range_count() > 0) {
- printer->Print(vars,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, "
- "_extensions_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n");
} else {
- printer->Print("-1, // no _extensions_\n");
+ format("-1, // no _extensions_\n");
}
// TODO(ckennelly): Consolidate this with the calculation for
// AuxillaryParseTableField.
- vars["ns"] = Namespace(descriptor_);
-
- printer->Print(vars,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n"
- " $classtype$, _internal_metadata_),\n"
- "&$ns$::_$classname$_default_instance_,\n");
+ format(
+ "PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n"
+ "&$package_ns$::_$classname$_default_instance_,\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(vars, "true,\n");
+ format("true,\n");
} else {
- printer->Print(vars, "false,\n");
+ format("false,\n");
}
- printer->Outdent();
- printer->Print("},\n");
+ format.Outdent();
+ format("},\n");
return true;
}
void MessageGenerator::GenerateSchema(io::Printer* printer, int offset,
int has_offset) {
- std::map<string, string> vars;
-
- vars["classname"] = QualifiedClassName(descriptor_);
- vars["offset"] = SimpleItoa(offset);
- vars["has_bits_offsets"] =
+ Formatter format(printer, variables_);
+ has_offset =
HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)
- ? SimpleItoa(offset + has_offset)
- : "-1";
+ ? offset + has_offset
+ : -1;
- printer->Print(vars,
- "{ $offset$, $has_bits_offsets$, sizeof($classname$)},\n");
+ format("{ $1$, $2$, sizeof($classtype$)},\n", offset, has_offset);
}
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 FieldGenerator&, 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 FieldGenerator& generator,
@@ -1495,6 +1570,12 @@ uint32 CalcFieldNum(const FieldGenerator& generator,
if (generator.IsInlined()) {
type = internal::FieldMetadata::kInlinedType;
}
+ // string field
+ if (IsCord(field, options)) {
+ type = internal::FieldMetadata::kCordType;
+ } else if (IsStringPiece(field, options)) {
+ type = internal::FieldMetadata::kStringPieceType;
+ }
}
if (field->containing_oneof()) {
return internal::FieldMetadata::CalculateType(
@@ -1515,7 +1596,6 @@ uint32 CalcFieldNum(const FieldGenerator& generator,
type, internal::FieldMetadata::kPresence);
}
}
-#endif
int FindMessageIndexInFile(const Descriptor* descriptor) {
std::vector<const Descriptor*> flatten =
@@ -1527,12 +1607,11 @@ int FindMessageIndexInFile(const Descriptor* descriptor) {
} // namespace
int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (!options_.table_driven_serialization) {
return 0;
}
- string full_classname = QualifiedClassName(descriptor_);
-
std::vector<const FieldDescriptor*> sorted = SortFieldsByNumber(descriptor_);
if (IsMapEntryMessage(descriptor_)) {
for (int i = 0; i < 2; i++) {
@@ -1543,36 +1622,39 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
field->number(), WireFormat::WireTypeForFieldType(field->type()));
std::map<string, string> vars;
- vars["classname"] = QualifiedClassName(descriptor_);
+ vars["classtype"] = QualifiedClassName(descriptor_);
vars["field_name"] = FieldName(field);
vars["tag"] = SimpleItoa(tag);
vars["hasbit"] = SimpleItoa(i);
- vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_));
+ vars["type"] =
+ SimpleItoa(CalcFieldNum(generator, field, options_));
vars["ptr"] = "NULL";
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
GOOGLE_CHECK(!IsMapEntryMessage(field->message_type()));
- {
+ if (!IsProto1(field->message_type()->file(), options_)) {
vars["ptr"] =
- "::" + FileLevelNamespace(field->message_type()) +
- "::TableStruct::serialization_table + " +
- SimpleItoa(FindMessageIndexInFile(field->message_type()));
+ "::" +
+ UniqueName("TableStruct", field->message_type(), options_) +
+ "::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");
+ Formatter::SaveState saver(&format);
+ format.AddMap(vars);
+ format(
+ "{PROTOBUF_FIELD_OFFSET("
+ "::$proto_ns$::internal::MapEntryHelper<$classtype$::"
+ "SuperType>, $field_name$_), $tag$,"
+ "PROTOBUF_FIELD_OFFSET("
+ "::$proto_ns$::internal::MapEntryHelper<$classtype$::"
+ "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);
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, _cached_size_), 0, 0, 0, NULL},\n");
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));
@@ -1586,14 +1668,12 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
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, "
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, _extensions_), "
+ "$1$, $2$, ::$proto_ns$::internal::FieldMetadata::kSpecial, "
"reinterpret_cast<const "
- "void*>(::google::protobuf::internal::ExtensionSerializer)},\n",
- "classname", full_classname, "start", SimpleItoa(range->start), "end",
- SimpleItoa(range->end));
+ "void*>(::$proto_ns$::internal::ExtensionSerializer)},\n",
+ range->start, range->end);
}
if (i == sorted.size()) break;
const FieldDescriptor* field = sorted[i];
@@ -1609,105 +1689,116 @@ int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
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";
+ format.Set("field_name", classfieldname);
+ string 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");
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$, $2$, "
+ "::$proto_ns$::internal::FieldMetadata::kSpecial, "
+ "reinterpret_cast<const void*>(static_cast< "
+ "::$proto_ns$::internal::SpecialSerializer>("
+ "::$proto_ns$::internal::MapFieldSerializer< "
+ "::$proto_ns$::internal::MapEntryToMapField<"
+ "$3$>::MapFieldType, "
+ "$tablename$::serialization_table>))},\n",
+ tag, FindMessageIndexInFile(field->message_type()),
+ QualifiedClassName(field->message_type()));
continue;
- } else {
- vars["ptr"] =
- "::" + FileLevelNamespace(field->message_type()) +
- "::TableStruct::serialization_table + " +
+ } else if (!IsProto1(field->message_type()->file(), options_) &&
+ !field->message_type()->options().message_set_wire_format()) {
+ // Proto1 or message_set don't have the usual table and we need to
+ // dispatch to generated serializer, hence ptr stays zero.
+ ptr =
+ "::" + UniqueName("TableStruct", field->message_type(), options_) +
+ "::serialization_table + " +
SimpleItoa(FindMessageIndexInFile(field->message_type()));
}
}
const FieldGenerator& generator = field_generators_.get(field);
- vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_));
+ int type = CalcFieldNum(generator, field, options_);
+ if (IsLazy(field, options_)) {
+ type = internal::FieldMetadata::kSpecial;
+ ptr = "reinterpret_cast<const void*>(::" + variables_["proto_ns"] +
+ "::internal::LazyFieldSerializer";
+ if (field->containing_oneof()) {
+ ptr += "OneOf";
+ } else if (!HasFieldPresence(descriptor_->file()) ||
+ has_bit_indices_[field->index()] == -1) {
+ ptr += "NoPresence";
+ }
+ ptr += ")";
+ }
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");
+ format(
+ "{PROTOBUF_FIELD_OFFSET("
+ "$classtype$, _weak_field_map_), $1$, $1$, "
+ "::$proto_ns$::internal::FieldMetadata::kSpecial, "
+ "reinterpret_cast<const "
+ "void*>(::$proto_ns$::internal::WeakFieldSerializer)},\n",
+ tag);
} 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");
+ format.Set("oneofoffset",
+ sizeof(uint32) * field->containing_oneof()->index());
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$,"
+ " PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + "
+ "$oneofoffset$, $2$, $3$},\n",
+ tag, type, ptr);
} 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");
+ format.Set("hasbitsoffset", has_bit_indices_[field->index()]);
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), "
+ "$1$, PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_) * 8 + "
+ "$hasbitsoffset$, $2$, $3$},\n",
+ tag, type, ptr);
} else {
- printer->Print(vars,
- "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($"
- "classname$, $field_name$_), $tag$, ~0u, $type$, "
- "$ptr$},\n");
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), "
+ "$1$, ~0u, $2$, $3$},\n",
+ tag, type, ptr);
}
}
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);
+ ? "UnknownFieldSetSerializer"
+ : "UnknownFieldSerializerLite";
+ format(
+ "{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, "
+ "::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast<const "
+ "void*>(::$proto_ns$::internal::$1$)},\n",
+ serializer);
return num_field_metadata;
}
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);
+ for (auto field : FieldRange(descriptor_)) {
+ field_generators_.get(field).GenerateDefaultInstanceAllocator(printer);
}
}
-void MessageGenerator::
-GenerateDefaultInstanceInitializer(io::Printer* printer) {
+void MessageGenerator::GenerateDefaultInstanceInitializer(
+ io::Printer* printer) {
+ Formatter format(printer, variables_);
+
// 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
// constructed yet at that time.
// TODO(kenton): Maybe all message fields (even for non-default messages)
// should be initialized to point at default instances rather than NULL?
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
+ for (auto field : FieldRange(descriptor_)) {
+ Formatter::SaveState saver(&format);
if (!field->is_repeated() &&
+ !IsLazy(field, options_) &&
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
(field->containing_oneof() == NULL ||
HasDescriptorMethods(descriptor_->file(), options_))) {
@@ -1719,201 +1810,294 @@ GenerateDefaultInstanceInitializer(io::Printer* printer) {
"_" + classname_ + "_default_instance_._instance.get_mutable()->";
}
name += FieldName(field);
- printer->Print(
- "$ns$::$name$_ = const_cast< $type$*>(\n"
- " $type$::internal_default_instance());\n",
- // Vars.
- "name", name, "type", FieldMessageTypeName(field), "ns",
- Namespace(descriptor_));
+ format.Set("name", name);
+ if (IsWeak(field, options_)) {
+ const FileDescriptor* dependency = field->message_type()->file();
+ string default_instance = QualifiedFileLevelSymbol(
+ dependency->package(),
+ "_" + ClassName(field->message_type()) + "_default_instance_");
+ format(
+ "$package_ns$::$name$_ = reinterpret_cast<const "
+ "::$proto_ns$::Message*>(&$1$);\n"
+ "if ($package_ns$::$name$_ == NULL) {\n"
+ " $package_ns$::$name$_ = "
+ "::$proto_ns$::Empty::internal_default_instance();\n"
+ "}\n",
+ default_instance); // 1
+ continue;
+ }
+ format(
+ "$package_ns$::$name$_ = const_cast< $1$*>(\n"
+ " $1$::internal_default_instance());\n",
+ FieldMessageTypeName(field));
} else if (field->containing_oneof() &&
HasDescriptorMethods(descriptor_->file(), options_)) {
- field_generators_.get(descriptor_->field(i))
- .GenerateConstructorCode(printer);
+ field_generators_.get(field).GenerateConstructorCode(printer);
}
}
}
-void MessageGenerator::
-GenerateClassMethods(io::Printer* printer) {
+void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (IsMapEntryMessage(descriptor_)) {
- printer->Print(
+ format(
"$classname$::$classname$() {}\n"
- "$classname$::$classname$(::google::protobuf::Arena* arena) : "
- "SuperType(arena) {}\n"
+ "$classname$::$classname$(::$proto_ns$::Arena* arena)\n"
+ " : SuperType(arena) {}\n"
"void $classname$::MergeFrom(const $classname$& other) {\n"
" MergeFromInternal(other);\n"
- "}\n",
- "classname", classname_);
+ "}\n");
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"
+ format(
+ "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n"
+ " "
+ "::$proto_ns$::internal::AssignDescriptors(&::$assign_desc_table$);\n"
+ " return ::$file_level_metadata$[$1$];\n"
+ "}\n",
+ index_in_file_messages_);
+ format(
"void $classname$::MergeFrom(\n"
- " const ::google::protobuf::Message& other) {\n"
- " ::google::protobuf::Message::MergeFrom(other);\n"
+ " const ::$proto_ns$::Message& other) {\n"
+ " ::$proto_ns$::Message::MergeFrom(other);\n"
"}\n"
- "\n",
- "file_namespace", FileLevelNamespace(descriptor_),
- "classname", classname_, "index",
- SimpleItoa(index_in_file_messages_));
+ "\n");
+ }
+ format(
+ "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ "bool $classname$::_ParseMap(const char* begin, const "
+ "char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) {\n"
+ " using MF = ::$proto_ns$::internal::MapField$1$<\n"
+ " $classname$, EntryKeyType, EntryValueType,\n"
+ " kEntryKeyFieldType, kEntryValueFieldType,\n"
+ " kEntryDefaultEnumValue>;\n"
+ " auto mf = static_cast<MF*>(object);\n"
+ " Parser<MF, ::$proto_ns$::Map<EntryKeyType, EntryValueType>> "
+ "parser(mf);\n"
+ "#define DO_(x) if (!(x)) return false\n",
+ HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite");
+ const FieldDescriptor* key = descriptor_->FindFieldByName("key");
+ const FieldDescriptor* val = descriptor_->FindFieldByName("value");
+ GOOGLE_CHECK(val);
+ string key_string;
+ string value_string;
+ if (HasFieldPresence(descriptor_->file()) &&
+ val->type() == FieldDescriptor::TYPE_ENUM) {
+ format(
+ " DO_(parser.ParseMapEnumValidation(\n"
+ " begin, end, ctx->extra_parse_data().field_number,\n"
+ " static_cast<::google::protobuf::internal::InternalMetadataWithArena$1$*>("
+ "ctx->extra_parse_data().unknown_fields), $2$_IsValid));\n",
+ HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite",
+ QualifiedClassName(val->enum_type()));
+ key_string = "parser.entry_key()";
+ value_string = "parser.entry_value()";
+ } else {
+ format(" DO_(parser.ParseMap(begin, end));\n");
+ key_string = "parser.key()";
+ value_string = "parser.value()";
+ }
+ format.Indent();
+ if (key->type() == FieldDescriptor::TYPE_STRING) {
+ GenerateUtf8CheckCodeForString(
+ key, options_, true,
+ StrCat(key_string, ".data(), static_cast<int>(", key_string,
+ ".length()),\n")
+ .data(),
+ format);
}
+ if (val->type() == FieldDescriptor::TYPE_STRING) {
+ GenerateUtf8CheckCodeForString(
+ val, options_, true,
+ StrCat(value_string, ".data(), static_cast<int>(", value_string,
+ ".length()),\n")
+ .data(),
+ format);
+ }
+ format.Outdent();
+ format(
+ "#undef DO_\n"
+ " return true;\n"
+ "}\n"
+ "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
+ format("\n");
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();
+ format("void $classname$::InitAsDefaultInstance() {\n");
+ format.Indent();
GenerateDefaultInstanceInitializer(printer);
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
if (IsAnyMessage(descriptor_)) {
- printer->Print(
- "void $classname$::PackFrom(const ::google::protobuf::Message& message) {\n"
- " _any_metadata_.PackFrom(message);\n"
- "}\n"
- "\n"
- "void $classname$::PackFrom(const ::google::protobuf::Message& message,\n"
- " const ::std::string& type_url_prefix) {\n"
- " _any_metadata_.PackFrom(message, type_url_prefix);\n"
- "}\n"
- "\n"
- "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n"
- " return _any_metadata_.UnpackTo(message);\n"
- "}\n"
- "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n"
- " string* full_type_name) {\n"
- " return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,\n"
- " full_type_name);\n"
- "}\n"
- "\n",
- "classname", classname_);
+ format(
+ "void $classname$::PackFrom(const ::$proto_ns$::Message& message) {\n"
+ " _any_metadata_.PackFrom(message);\n"
+ "}\n"
+ "\n"
+ "void $classname$::PackFrom(const ::$proto_ns$::Message& message,\n"
+ " const $string$& type_url_prefix) {\n"
+ " _any_metadata_.PackFrom(message, type_url_prefix);\n"
+ "}\n"
+ "\n"
+ "bool $classname$::UnpackTo(::$proto_ns$::Message* message) const {\n"
+ " return _any_metadata_.UnpackTo(message);\n"
+ "}\n"
+ "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n"
+ " string* full_type_name) {\n"
+ " return ::$proto_ns$::internal::ParseAnyTypeUrl(type_url,\n"
+ " full_type_name);\n"
+ "}\n"
+ "bool $classname$::GetAnyFieldDescriptors(\n"
+ " const ::$proto_ns$::Message& message,\n"
+ " const ::$proto_ns$::FieldDescriptor** type_url_field,\n"
+ " const ::$proto_ns$::FieldDescriptor** value_field) {\n"
+ " return ::$proto_ns$::internal::GetAnyFieldDescriptors(\n"
+ " message, type_url_field, value_field);\n"
+ "}\n"
+ "\n");
+ }
+
+ format(
+ "class $classname$::HasBitSetters {\n"
+ " public:\n");
+ format.Indent();
+ for (auto field : FieldRange(descriptor_)) {
+ field_generators_.get(field).GenerateInternalAccessorDeclarations(printer);
+ if (HasFieldPresence(descriptor_->file()) && !field->is_repeated() &&
+ !field->options().weak() && !field->containing_oneof()) {
+ int has_bit_index = has_bit_indices_[field->index()];
+ GOOGLE_CHECK_GE(has_bit_index, 0);
+
+ format.Set("has_array_index", has_bit_index / 32);
+ format.Set("has_mask",
+ strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
+ format(
+ "static void set_has_$1$($classname$* msg) {\n"
+ " msg->_has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
+ "}\n",
+ FieldName(field));
+ }
+ }
+ format.Outdent();
+ format("};\n\n");
+ for (auto field : FieldRange(descriptor_)) {
+ field_generators_.get(field).GenerateInternalAccessorDefinitions(printer);
}
// Generate non-inline field definitions.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
- field_generators_.get(field)
- .GenerateNonInlineAccessorDefinitions(printer);
+ for (auto field : FieldRange(descriptor_)) {
+ field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer);
if (IsCrossFileMaybeMap(field)) {
+ Formatter::SaveState saver(&format);
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
if (field->containing_oneof()) {
SetCommonOneofFieldVariables(field, &vars);
}
- GenerateFieldClear(field, vars, false, printer);
+ format.AddMap(vars);
+ GenerateFieldClear(field, false, format);
}
}
// Generate field number constants.
- printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor *field = descriptor_->field(i);
- printer->Print(
- "const int $classname$::$constant_name$;\n",
- "classname", ClassName(FieldScope(field), false),
- "constant_name", FieldConstantName(field));
- }
- printer->Print(
- "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"
- "\n");
+ format("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
+ for (auto field : FieldRange(descriptor_)) {
+ format("const int $classname$::$1$;\n", FieldConstantName(field));
+ }
+ format(
+ "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"
+ "\n");
GenerateStructors(printer);
- printer->Print("\n");
+ format("\n");
if (descriptor_->oneof_decl_count() > 0) {
GenerateOneofClear(printer);
- printer->Print("\n");
+ format("\n");
}
if (HasGeneratedMethods(descriptor_->file(), options_)) {
GenerateClear(printer);
- printer->Print("\n");
+ format("\n");
GenerateMergeFromCodedStream(printer);
- printer->Print("\n");
+ format("\n");
GenerateSerializeWithCachedSizes(printer);
- printer->Print("\n");
+ format("\n");
if (HasFastArraySerialization(descriptor_->file(), options_)) {
GenerateSerializeWithCachedSizesToArray(printer);
- printer->Print("\n");
+ format("\n");
}
GenerateByteSize(printer);
- printer->Print("\n");
+ format("\n");
GenerateMergeFrom(printer);
- printer->Print("\n");
+ format("\n");
GenerateCopyFrom(printer);
- printer->Print("\n");
+ format("\n");
GenerateIsInitialized(printer);
- printer->Print("\n");
+ format("\n");
}
GenerateSwap(printer);
- printer->Print("\n");
+ format("\n");
if (options_.table_driven_serialization) {
- printer->Print(
+ format(
"const void* $classname$::InternalGetTable() const {\n"
- " return ::$file_namespace$::TableStruct::serialization_table + "
- "$index$;\n"
+ " return ::$tablename$::serialization_table + $1$;\n"
"}\n"
"\n",
- "classname", classname_, "index", SimpleItoa(index_in_file_messages_),
- "file_namespace", FileLevelNamespace(descriptor_));
+ index_in_file_messages_);
}
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[kIndexInFileMessages];\n"
+ format(
+ "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n"
+ " ::$proto_ns$::internal::AssignDescriptors(&::$assign_desc_table$);\n"
+ " return ::$file_level_metadata$[kIndexInFileMessages];\n"
"}\n"
- "\n",
- "classname", classname_, "file_namespace",
- FileLevelNamespace(descriptor_));
+ "\n");
} else {
- printer->Print(
- "::std::string $classname$::GetTypeName() const {\n"
- " return \"$type_name$\";\n"
- "}\n"
- "\n",
- "classname", classname_,
- "type_name", descriptor_->full_name());
+ format(
+ "$string$ $classname$::GetTypeName() const {\n"
+ " return \"$full_name$\";\n"
+ "}\n"
+ "\n");
}
}
size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
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");
+ format("{0, 0, 0, ::$proto_ns$::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];
+ for (auto field : ordered_fields) {
+ Formatter::SaveState saver(&format);
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");
+ format(
+ "{ 0, 0, ::$proto_ns$::internal::kInvalidMask,\n"
+ " ::$proto_ns$::internal::kInvalidMask, 0, 0 },\n");
}
last_field_number++;
@@ -1929,30 +2113,39 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
processing_type = static_cast<unsigned>(field->type());
const FieldGenerator& generator = field_generators_.get(field);
if (field->type() == FieldDescriptor::TYPE_STRING) {
- switch (EffectiveStringCType(field)) {
+ switch (EffectiveStringCType(field, options_)) {
case FieldOptions::STRING:
- default: {
if (generator.IsInlined()) {
processing_type = internal::TYPE_STRING_INLINED;
break;
}
break;
- }
+ case FieldOptions::CORD:
+ processing_type = internal::TYPE_STRING_CORD;
+ break;
+ case FieldOptions::STRING_PIECE:
+ processing_type = internal::TYPE_STRING_STRING_PIECE;
+ break;
}
} else if (field->type() == FieldDescriptor::TYPE_BYTES) {
- switch (EffectiveStringCType(field)) {
+ switch (EffectiveStringCType(field, options_)) {
case FieldOptions::STRING:
- default:
if (generator.IsInlined()) {
processing_type = internal::TYPE_BYTES_INLINED;
break;
}
break;
+ case FieldOptions::CORD:
+ processing_type = internal::TYPE_BYTES_CORD;
+ break;
+ case FieldOptions::STRING_PIECE:
+ processing_type = internal::TYPE_BYTES_STRING_PIECE;
+ break;
}
}
processing_type |= static_cast<unsigned>(
- field->is_repeated() ? internal::kRepeatedMask : 0);
+ field->is_repeated() ? internal::kRepeatedMask : 0);
processing_type |= static_cast<unsigned>(
field->containing_oneof() ? internal::kOneofMask : 0);
@@ -1961,13 +2154,13 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
}
const unsigned char tag_size =
- WireFormat::TagSize(field->number(), field->type());
+ 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());
+ vars["presence"] =
+ SimpleItoa(field->containing_oneof()->index());
} else {
vars["name"] = FieldName(field);
vars["presence"] = SimpleItoa(has_bit_indices_[field->index()]);
@@ -1977,19 +2170,22 @@ size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
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");
+ format.AddMap(vars);
+
+ format(
+ "{\n"
+ " PROTOBUF_FIELD_OFFSET($classtype$, $name$_),\n"
+ " static_cast<$uint32$>($presence$),\n"
+ " $nwtype$, $pwtype$, $ptype$, $tag_size$\n"
+ "},\n");
}
return last_field_number;
}
size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
if (!table_driven_) {
return 0;
}
@@ -1997,74 +2193,71 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
std::vector<const FieldDescriptor*> ordered_fields =
SortFieldsByNumber(descriptor_);
- printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
int last_field_number = 1;
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = ordered_fields[i];
+ for (auto field : ordered_fields) {
+ Formatter::SaveState saver(&format);
GOOGLE_CHECK_GE(field->number(), last_field_number);
for (; last_field_number < field->number(); last_field_number++) {
- printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n");
+ format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
}
std::map<string, string> vars;
SetCommonFieldVariables(field, &vars, options_);
+ format.AddMap(vars);
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");
+ format(
+ "{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
+ "$1$_IsValid}},\n",
+ ClassName(field->enum_type(), true));
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");
+ format(
+ "{::$proto_ns$::internal::AuxillaryParseTableField::map_"
+ "aux{&::$proto_ns$::internal::ParseMap<$1$>}},\n",
+ QualifiedClassName(field->message_type()));
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");
+ format.Set("field_classname", ClassName(field->message_type(), false));
+ format.Set("ns", Namespace(field->message_type()));
+
+ format(
+ "{::$proto_ns$::internal::AuxillaryParseTableField::message_aux{\n"
+ " &$ns$::_$field_classname$_default_instance_}},\n");
last_field_number++;
break;
}
- case FieldDescriptor::CPPTYPE_STRING:
- switch (EffectiveStringCType(field)) {
+ case FieldDescriptor::CPPTYPE_STRING: {
+ string default_val;
+ switch (EffectiveStringCType(field, options_)) {
case FieldOptions::STRING:
- vars["default"] =
- field->default_value_string().empty()
- ? "&::google::protobuf::internal::fixed_address_empty_string"
- : "&" + Namespace(field) + " ::" + classname_ +
- "::" + MakeDefaultName(field);
+ default_val = field->default_value_string().empty()
+ ? "&::" + variables_["proto_ns"] +
+ "::internal::fixed_address_empty_string"
+ : "&" + Namespace(field) + " ::" + classname_ +
+ "::" + MakeDefaultName(field);
break;
case FieldOptions::CORD:
case FieldOptions::STRING_PIECE:
- vars["default"] =
+ default_val =
"\"" + 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");
+ format(
+ "{::$proto_ns$::internal::AuxillaryParseTableField::string_aux{\n"
+ " $1$,\n"
+ " \"$2$\"\n"
+ "}},\n",
+ default_val, field->full_name());
last_field_number++;
break;
+ }
default:
break;
}
@@ -2075,171 +2268,149 @@ size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
io::Printer* printer) {
- std::map<string, string> variables;
- string full_classname = QualifiedClassName(descriptor_);
- variables["classname"] = full_classname;
+ Formatter format(printer, variables_);
if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) {
- printer->Print(
- variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "_has_bits_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
} else {
- printer->Print("~0u, // no _has_bits_\n");
+ format("~0u, // no _has_bits_\n");
}
- printer->Print(variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "_internal_metadata_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n");
if (descriptor_->extension_range_count() > 0) {
- printer->Print(
- variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
- "_extensions_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n");
} else {
- printer->Print("~0u, // no _extensions_\n");
+ format("~0u, // no _extensions_\n");
}
if (descriptor_->oneof_decl_count() > 0) {
- printer->Print(variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
- "$classname$, _oneof_case_[0]),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n");
} else {
- printer->Print("~0u, // no _oneof_case_\n");
+ format("~0u, // no _oneof_case_\n");
}
if (num_weak_fields_ > 0) {
- printer->Print(variables,
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$,"
- " _weak_field_map_),\n");
+ format("PROTOBUF_FIELD_OFFSET($classtype$, _weak_field_map_),\n");
} else {
- printer->Print("~0u, // no _weak_field_map_\n");
+ format("~0u, // no _weak_field_map_\n");
}
const int kNumGenericOffsets = 5; // the number of fixed offsets above
- const size_t offsets = kNumGenericOffsets +
- descriptor_->field_count() +
+ 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);
+ for (auto field : FieldRange(descriptor_)) {
if (field->containing_oneof() || field->options().weak()) {
- printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)",
- "classname", full_classname, "name", FieldName(field));
+ format("offsetof($classtype$DefaultTypeInternal, $1$_)",
+ FieldName(field));
} else {
- printer->Print(
- "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)",
- "classname", full_classname, "name", FieldName(field));
+ format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_)", FieldName(field));
}
uint32 tag = field_generators_.get(field).CalculateFieldTag();
if (tag != 0) {
- printer->Print(" | $tag$", "tag", SimpleItoa(tag));
+ format(" | $1$", tag);
}
- printer->Print(",\n");
+ format(",\n");
}
- 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", full_classname, "name", oneof->name());
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name());
}
if (IsMapEntryMessage(descriptor_)) {
entries += 2;
- printer->Print(
+ format(
"0,\n"
"1,\n");
} else if (HasFieldPresence(descriptor_->file())) {
entries += has_bit_indices_.size();
for (int i = 0; i < has_bit_indices_.size(); i++) {
- const string index = has_bit_indices_[i] >= 0 ?
- SimpleItoa(has_bit_indices_[i]) : "~0u";
- printer->Print("$index$,\n", "index", index);
+ const string index = has_bit_indices_[i] >= 0
+ ? SimpleItoa(has_bit_indices_[i])
+ : "~0u";
+ format("$1$,\n", index);
}
}
return std::make_pair(entries, offsets);
}
-void MessageGenerator::
-GenerateSharedConstructorCode(io::Printer* printer) {
- printer->Print(
- "void $classname$::SharedCtor() {\n",
- "classname", classname_);
- printer->Indent();
+void MessageGenerator::GenerateSharedConstructorCode(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
+ format("void $classname$::SharedCtor() {\n");
+ if (scc_analyzer_
+ ->GetSCCAnalysis(scc_analyzer_->GetSCC(descriptor_))
+ .constructor_requires_initialization) {
+ format(
+ " ::$proto_ns$::internal::InitSCC(\n"
+ " &scc_info_$scc_name$.base);\n");
+ }
+
+ format.Indent();
std::vector<bool> processed(optimized_order_.size(), false);
GenerateConstructorBody(printer, processed, false);
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "clear_has_$oneof_name$();\n",
- "oneof_name", descriptor_->oneof_decl(i)->name());
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("clear_has_$1$();\n", oneof->name());
}
- printer->Outdent();
- printer->Print("}\n\n");
+ format.Outdent();
+ format("}\n\n");
}
-void MessageGenerator::
-GenerateSharedDestructorCode(io::Printer* printer) {
- printer->Print(
- "void $classname$::SharedDtor() {\n",
- "classname", classname_);
- printer->Indent();
+void MessageGenerator::GenerateSharedDestructorCode(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
+ format("void $classname$::SharedDtor() {\n");
+ format.Indent();
if (SupportsArenas(descriptor_)) {
- printer->Print(
- "GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);\n");
+ format("$DCHK$(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++) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
field_generators_.get(field).GenerateDestructorCode(printer);
}
// Generate code to destruct oneofs. Clearing should do the work.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "if (has_$oneof_name$()) {\n"
- " clear_$oneof_name$();\n"
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format(
+ "if (has_$1$()) {\n"
+ " clear_$1$();\n"
"}\n",
- "oneof_name", descriptor_->oneof_decl(i)->name());
+ oneof->name());
}
if (num_weak_fields_) {
- printer->Print("_weak_field_map_.ClearAll();\n");
+ format("_weak_field_map_.ClearAll();\n");
}
- printer->Outdent();
- printer->Print(
- "}\n"
- "\n");
+ format.Outdent();
+ format(
+ "}\n"
+ "\n");
}
-void MessageGenerator::
-GenerateArenaDestructorCode(io::Printer* printer) {
+void MessageGenerator::GenerateArenaDestructorCode(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
// Generate the ArenaDtor() method. Track whether any fields actually produced
// code that needs to be called.
- printer->Print(
- "void $classname$::ArenaDtor(void* object) {\n",
- "classname", classname_);
- printer->Indent();
+ format("void $classname$::ArenaDtor(void* object) {\n");
+ format.Indent();
// This code is placed inside a static method, rather than an ordinary one,
// since that simplifies Arena's destructor list (ordinary function pointers
// rather than member function pointers). _this is the object being
// destructed.
- printer->Print(
+ format(
"$classname$* _this = reinterpret_cast< $classname$* >(object);\n"
// avoid an "unused variable" warning in case no fields have dtor code.
- "(void)_this;\n",
- "classname", classname_);
+ "(void)_this;\n");
bool need_registration = false;
// Process non-oneof fields first.
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (field_generators_.get(field)
- .GenerateArenaDestructorCode(printer)) {
+ for (auto field : optimized_order_) {
+ if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
need_registration = true;
}
}
@@ -2248,13 +2419,9 @@ GenerateArenaDestructorCode(io::Printer* printer) {
//
// Note: As of 10/5/2016, GenerateArenaDestructorCode does not emit anything
// and returns false for oneof fields.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
-
- for (int j = 0; j < oneof->field_count(); j++) {
- const FieldDescriptor* field = oneof->field(j);
- if (field_generators_.get(field)
- .GenerateArenaDestructorCode(printer)) {
+ for (auto oneof : OneOfRange(descriptor_)) {
+ for (auto field : FieldRange(oneof)) {
+ if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
need_registration = true;
}
}
@@ -2262,42 +2429,40 @@ 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");
+ format("_this->_weak_field_map_.ClearAll();\n");
need_registration = true;
}
- printer->Outdent();
- printer->Print(
- "}\n");
+ format.Outdent();
+ format("}\n");
if (need_registration) {
- printer->Print(
- "inline void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n"
+ format(
+ "inline void $classname$::RegisterArenaDtor(::$proto_ns$::Arena* "
+ "arena) {\n"
" if (arena != NULL) {\n"
" arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n"
" }\n"
- "}\n",
- "classname", classname_);
+ "}\n");
} else {
- printer->Print(
- "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n"
- "}\n",
- "classname", classname_);
+ format(
+ "void $classname$::RegisterArenaDtor(::$proto_ns$::Arena*) {\n"
+ "}\n");
}
}
void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
std::vector<bool> processed,
bool copy_constructor) const {
+ Formatter format(printer, variables_);
const FieldDescriptor* last_start = NULL;
// RunMap maps from fields that start each run to the number of fields in that
// run. This is optimized for the common case that there are very few runs in
// a message and that most of the eligible fields appear together.
- typedef hash_map<const FieldDescriptor*, size_t> RunMap;
+ typedef std::unordered_map<const FieldDescriptor*, size_t> RunMap;
RunMap runs;
- for (int i = 0; i < optimized_order_.size(); ++i) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
if ((copy_constructor && IsPOD(field)) ||
(!copy_constructor && CanConstructByZeroing(field, options_))) {
if (last_start == NULL) {
@@ -2340,9 +2505,10 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
const string last_field_name =
FieldName(optimized_order_[i + run_length - 1]);
- printer->Print(pod_template.c_str(),
- "first", first_field_name,
- "last", last_field_name);
+ format.Set("first", first_field_name);
+ format.Set("last", last_field_name);
+
+ format(pod_template.c_str());
i += run_length - 1;
// ++i at the top of the loop.
@@ -2356,8 +2522,9 @@ void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
}
}
-void MessageGenerator::
-GenerateStructors(io::Printer* printer) {
+void MessageGenerator::GenerateStructors(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
string superclass;
superclass = SuperClassName(descriptor_, options_);
string initializer_with_arena = superclass + "()";
@@ -2369,13 +2536,15 @@ GenerateStructors(io::Printer* printer) {
initializer_with_arena += ",\n _internal_metadata_(arena)";
// Initialize member variables with arena constructor.
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
-
+ for (auto field : optimized_order_) {
bool has_arena_constructor = field->is_repeated();
+ if (field->containing_oneof() == NULL &&
+ (IsLazy(field, options_) || IsStringPiece(field, options_))) {
+ has_arena_constructor = true;
+ }
if (has_arena_constructor) {
- initializer_with_arena += string(",\n ") +
- FieldName(field) + string("_(arena)");
+ initializer_with_arena +=
+ string(",\n ") + FieldName(field) + string("_(arena)");
}
}
@@ -2394,33 +2563,23 @@ GenerateStructors(io::Printer* printer) {
initializer_null += ", _weak_field_map_(nullptr)";
}
- printer->Print(
+ format(
"$classname$::$classname$()\n"
- " : $initializer$ {\n"
- " ::google::protobuf::internal::InitSCC(\n"
- " &$file_namespace$::scc_info_$scc_name$.base);\n"
+ " : $1$ {\n"
" SharedCtor();\n"
" // @@protoc_insertion_point(constructor:$full_name$)\n"
"}\n",
- "classname", classname_, "full_name", descriptor_->full_name(),
- "scc_name", scc_name_, "initializer", initializer_null, "file_namespace",
- FileLevelNamespace(descriptor_));
+ initializer_null);
if (SupportsArenas(descriptor_)) {
- printer->Print(
- "$classname$::$classname$(::google::protobuf::Arena* arena)\n"
- " : $initializer$ {\n"
- " "
- "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$."
- "base);\n"
+ format(
+ "$classname$::$classname$(::$proto_ns$::Arena* arena)\n"
+ " : $1$ {\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(),
- "scc_name", scc_name_, "file_namespace",
- FileLevelNamespace(descriptor_));
+ initializer_with_arena);
}
// Generate the copy constructor.
@@ -2429,117 +2588,98 @@ GenerateStructors(io::Printer* printer) {
// one-liner copy constructor that delegates to MergeFrom. This saves some
// code size and also cuts down on the complexity of implicit weak fields.
// We might eventually want to do this for all lite protos.
- printer->Print(
- "$classname$::$classname$(const $classname$& from)\n"
- " : $classname$() {\n"
- " MergeFrom(from);\n"
- "}\n",
- "classname", classname_);
+ format(
+ "$classname$::$classname$(const $classname$& from)\n"
+ " : $classname$() {\n"
+ " MergeFrom(from);\n"
+ "}\n");
} else {
- printer->Print(
- "$classname$::$classname$(const $classname$& from)\n"
- " : $superclass$()",
- "classname", classname_,
- "superclass", superclass,
- "full_name", descriptor_->full_name());
- printer->Indent();
- printer->Indent();
- printer->Indent();
-
- printer->Print(
- ",\n_internal_metadata_(NULL)");
+ format(
+ "$classname$::$classname$(const $classname$& from)\n"
+ " : $superclass$()");
+ format.Indent();
+ format.Indent();
+ format.Indent();
+ format(",\n_internal_metadata_(NULL)");
if (HasFieldPresence(descriptor_->file())) {
- printer->Print(",\n_has_bits_(from._has_bits_)");
+ if (!IsProto2MessageSet(descriptor_, options_)) {
+ format(",\n_has_bits_(from._has_bits_)");
+ }
}
std::vector<bool> processed(optimized_order_.size(), false);
- for (int i = 0; i < optimized_order_.size(); ++i) {
- const FieldDescriptor* field = optimized_order_[i];
-
- if (!(field->is_repeated() && !(field->is_map()))
- ) {
+ for (int i = 0; i < optimized_order_.size(); i++) {
+ auto field = optimized_order_[i];
+ if (!(field->is_repeated() && !(field->is_map())) &&
+ !IsCord(field, options_)) {
continue;
}
processed[i] = true;
- printer->Print(",\n$name$_(from.$name$_)",
- "name", FieldName(field));
+ format(",\n$1$_(from.$1$_)", FieldName(field));
}
if (IsAnyMessage(descriptor_)) {
- printer->Print(",\n_any_metadata_(&type_url_, &value_)");
+ format(",\n_any_metadata_(&type_url_, &value_)");
}
if (num_weak_fields_ > 0) {
- printer->Print(",\n_weak_field_map_(from._weak_field_map_)");
+ format(",\n_weak_field_map_(from._weak_field_map_)");
}
- printer->Outdent();
- printer->Outdent();
- printer->Print(" {\n");
+ format.Outdent();
+ format.Outdent();
+ format(" {\n");
- printer->Print(
- "_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
+ format("_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
if (descriptor_->extension_range_count() > 0) {
- printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
+ format("_extensions_.MergeFrom(from._extensions_);\n");
}
GenerateConstructorBody(printer, processed, true);
// Copy oneof fields. Oneof field requires oneof case check.
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
- printer->Print(
- "clear_has_$oneofname$();\n"
- "switch (from.$oneofname$_case()) {\n",
- "oneofname", descriptor_->oneof_decl(i)->name());
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format(
+ "clear_has_$1$();\n"
+ "switch (from.$1$_case()) {\n",
+ oneof->name());
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
field_generators_.get(field).GenerateMergingCode(printer);
- printer->Print(
- "break;\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
+ format(
+ "case $1$_NOT_SET: {\n"
" break;\n"
"}\n",
- "oneof_index",
- SimpleItoa(descriptor_->oneof_decl(i)->index()),
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
- "}\n");
+ ToUpper(oneof->name()));
+ format.Outdent();
+ format("}\n");
}
- printer->Outdent();
- printer->Print(
- " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
- "}\n"
- "\n",
- "full_name", descriptor_->full_name());
+ format.Outdent();
+ format(
+ " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
+ "}\n"
+ "\n");
}
// Generate the shared constructor code.
GenerateSharedConstructorCode(printer);
// Generate the destructor.
- printer->Print(
- "$classname$::~$classname$() {\n"
- " // @@protoc_insertion_point(destructor:$full_name$)\n"
- " SharedDtor();\n"
- "}\n"
- "\n",
- "classname", classname_,
- "full_name", descriptor_->full_name());
+ format(
+ "$classname$::~$classname$() {\n"
+ " // @@protoc_insertion_point(destructor:$full_name$)\n"
+ " SharedDtor();\n"
+ "}\n"
+ "\n");
// Generate the shared destructor code.
GenerateSharedDestructorCode(printer);
@@ -2550,90 +2690,60 @@ GenerateStructors(io::Printer* printer) {
}
// Generate SetCachedSize.
- printer->Print(
+ format(
"void $classname$::SetCachedSize(int size) const {\n"
" _cached_size_.Set(size);\n"
- "}\n",
- "classname", classname_);
-
- // Only generate this member if it's not disabled.
- if (HasDescriptorMethods(descriptor_->file(), options_) &&
- !descriptor_->options().no_standard_descriptor_accessor()) {
- printer->Print(
- "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
- " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n"
- " return ::"
- "$file_namespace$::file_level_metadata[kIndexInFileMessages]."
- "descriptor;\n"
- "}\n"
- "\n",
- "classname", classname_, "file_namespace",
- FileLevelNamespace(descriptor_));
- }
+ "}\n");
- printer->Print(
+ format(
"const $classname$& $classname$::default_instance() {\n"
" "
- "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)"
+ "::$proto_ns$::internal::InitSCC(&::scc_info_$scc_name$.base)"
";\n"
" return *internal_default_instance();\n"
- "}\n\n",
- "classname", classname_, "scc_name", scc_name_, "file_namespace",
- FileLevelNamespace(descriptor_));
+ "}\n\n");
}
void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) {
- printer->Print(
+ Formatter format(printer, variables_);
+ format(
"template<> "
- "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE "
- "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n"
- " return Arena::$create_func$Internal< $classname$ >(arena);\n"
+ "PROTOBUF_NOINLINE "
+ "$classtype$* Arena::CreateMaybeMessage< $classtype$ >(Arena* arena) {\n"
+ " return Arena::$1$Internal< $classtype$ >(arena);\n"
"}\n",
- "classname", QualifiedClassName(descriptor_),
- "create_func", MessageCreateFunction(descriptor_));
-}
-
-// Return the number of bits set in n, a non-negative integer.
-static int popcnt(uint32 n) {
- int result = 0;
- while (n != 0) {
- result += (n & 1);
- n = n / 2;
- }
- return result;
+ MessageCreateFunction(descriptor_));
}
bool MessageGenerator::MaybeGenerateOptionalFieldCondition(
io::Printer* printer, const FieldDescriptor* field,
int expected_has_bits_index) {
+ Formatter format(printer, variables_);
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);
+ format("if (cached_has_bits & 0x$1$u) {\n", mask);
return true;
}
return false;
}
-void MessageGenerator::
-GenerateClear(io::Printer* printer) {
+void MessageGenerator::GenerateClear(io::Printer* printer) {
+ Formatter format(printer, variables_);
// Performance tuning parameters
const int kMaxUnconditionalPrimitiveBytesClear = 4;
- printer->Print(
+ format(
"void $classname$::Clear() {\n"
- "// @@protoc_insertion_point(message_clear_start:$full_name$)\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
+ "// @@protoc_insertion_point(message_clear_start:$full_name$)\n");
+ format.Indent();
- printer->Print(
+ format(
// 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"
+ "$uint32$ cached_has_bits = 0;\n"
"// Prevent compiler warnings about cached_has_bits being unused\n"
"(void) cached_has_bits;\n\n");
@@ -2641,7 +2751,7 @@ GenerateClear(io::Printer* printer) {
// Step 1: Extensions
if (descriptor_->extension_range_count() > 0) {
- printer->Print("_extensions_.Clear();\n");
+ format("_extensions_.Clear();\n");
}
int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear;
@@ -2687,6 +2797,8 @@ GenerateClear(io::Printer* printer) {
}
}
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
+ HasFieldPresence(descriptor_->file()));
for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
GOOGLE_CHECK(!chunk.empty());
@@ -2703,6 +2815,8 @@ GenerateClear(io::Printer* printer) {
continue;
}
+ cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
+
// Step 3: Non-repeated fields that can be cleared by memset-to-0, then
// non-repeated, non-zero initializable fields.
int last_chunk = HasFieldPresence(descriptor_->file())
@@ -2738,12 +2852,11 @@ GenerateClear(io::Printer* printer) {
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));
+ format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
}
- printer->Print("if (cached_has_bits & $mask$u) {\n", "mask",
- SimpleItoa(last_chunk_mask));
- printer->Indent();
+ format("if (cached_has_bits & 0x$1$u) {\n",
+ StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ format.Indent();
}
if (memset_run_start != -1) {
@@ -2756,11 +2869,11 @@ GenerateClear(io::Printer* printer) {
const string first_field_name = FieldName(chunk[memset_run_start]);
const string last_field_name = FieldName(chunk[memset_run_end]);
- printer->Print(
- "::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);
+ format(
+ "::memset(&$1$_, 0, static_cast<size_t>(\n"
+ " reinterpret_cast<char*>(&$2$_) -\n"
+ " reinterpret_cast<char*>(&$1$_)) + sizeof($2$_));\n",
+ first_field_name, last_field_name);
}
// Advance last_chunk_start to skip over the fields we zeroed/memset.
@@ -2770,7 +2883,6 @@ GenerateClear(io::Printer* printer) {
// Go back and emit clears for each of the fields we processed.
for (int j = last_chunk_start; j < chunk.size(); j++) {
const FieldDescriptor* field = chunk[j];
- const string fieldname = FieldName(field);
const FieldGenerator& generator = field_generators_.get(field);
// It's faster to just overwrite primitive types, but we should only
@@ -2785,121 +2897,101 @@ GenerateClear(io::Printer* printer) {
if (should_check_bit &&
// If no field presence, then always clear strings/messages as well.
HasFieldPresence(descriptor_->file())) {
- 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();
+ PrintPresenceCheck(format, field, has_bit_indices_, printer,
+ &cached_has_bit_index);
have_enclosing_if = true;
}
generator.GenerateMessageClearingCode(printer);
if (have_enclosing_if) {
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
}
if (have_outer_if) {
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
+ }
+
+ if (cold_skipper.OnEndChunk(chunk_index, printer)) {
+ // Reset here as it may have been updated in just closed if statement.
+ cached_has_bit_index = -1;
}
}
// Step 4: Unions.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "clear_$oneof_name$();\n",
- "oneof_name", descriptor_->oneof_decl(i)->name());
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("clear_$1$();\n", oneof->name());
}
if (num_weak_fields_) {
- printer->Print("_weak_field_map_.ClearAll();\n");
+ format("_weak_field_map_.ClearAll();\n");
}
if (HasFieldPresence(descriptor_->file())) {
// Step 5: Everything else.
- printer->Print("_has_bits_.Clear();\n");
+ format("_has_bits_.Clear();\n");
}
- printer->Print("_internal_metadata_.Clear();\n");
+ format("_internal_metadata_.Clear();\n");
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateOneofClear(io::Printer* printer) {
+void MessageGenerator::GenerateOneofClear(io::Printer* printer) {
// Generated function clears the active field and union case (e.g. foo_case_).
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- std::map<string, string> oneof_vars;
- oneof_vars["classname"] = classname_;
- oneof_vars["oneofname"] = descriptor_->oneof_decl(i)->name();
- oneof_vars["full_name"] = descriptor_->full_name();
- string message_class;
-
- printer->Print(oneof_vars,
- "void $classname$::clear_$oneofname$() {\n"
- "// @@protoc_insertion_point(one_of_clear_start:"
- "$full_name$)\n");
- printer->Indent();
- printer->Print(oneof_vars,
- "switch ($oneofname$_case()) {\n");
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ auto oneof = descriptor_->oneof_decl(i);
+ Formatter format(printer, variables_);
+ format.Set("oneofname", oneof->name());
+
+ format(
+ "void $classname$::clear_$oneofname$() {\n"
+ "// @@protoc_insertion_point(one_of_clear_start:$full_name$)\n");
+ format.Indent();
+ format("switch ($oneofname$_case()) {\n");
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
// We clear only allocated objects in oneofs
if (!IsStringOrMessage(field)) {
- printer->Print(
- "// No need to clear\n");
+ format("// No need to clear\n");
} else {
field_generators_.get(field).GenerateClearingCode(printer);
}
- printer->Print(
- "break;\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
+ format(
+ "case $1$_NOT_SET: {\n"
" break;\n"
"}\n",
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
+ ToUpper(oneof->name()));
+ format.Outdent();
+ format(
"}\n"
- "_oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n",
- "oneof_index", SimpleItoa(i),
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
+ "_oneof_case_[$1$] = $2$_NOT_SET;\n",
+ i, ToUpper(oneof->name()));
+ format.Outdent();
+ format(
"}\n"
"\n");
}
}
-void MessageGenerator::
-GenerateSwap(io::Printer* printer) {
+void MessageGenerator::GenerateSwap(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
// Generate the Swap member function. This is a lightweight wrapper around
// UnsafeArenaSwap() / MergeFrom() with temporaries, depending on the memory
// ownership situation: swapping across arenas or between an arena and a
// heap requires copying.
- printer->Print(
+ format(
"void $classname$::Swap($classname$* other) {\n"
" if (other == this) return;\n"
" if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n"
@@ -2916,26 +3008,35 @@ GenerateSwap(io::Printer* printer) {
"}\n"
"void $classname$::UnsafeArenaSwap($classname$* other) {\n"
" if (other == this) return;\n"
- " GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n"
+ " $DCHK$(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n"
" InternalSwap(other);\n"
- "}\n",
- "classname", classname_);
+ "}\n");
} else {
- printer->Print(
+ format(
"void $classname$::Swap($classname$* other) {\n"
" if (other == this) return;\n"
" InternalSwap(other);\n"
- "}\n",
- "classname", classname_);
+ "}\n");
}
// Generate the UnsafeArenaSwap member function.
- printer->Print("void $classname$::InternalSwap($classname$* other) {\n",
- "classname", classname_);
- printer->Indent();
- printer->Print("using std::swap;\n");
+ format("void $classname$::InternalSwap($classname$* other) {\n");
+ format.Indent();
+ format("using std::swap;\n");
if (HasGeneratedMethods(descriptor_->file(), options_)) {
+ if (descriptor_->extension_range_count() > 0) {
+ format("_extensions_.Swap(&other->_extensions_);\n");
+ }
+
+ format("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
+
+ if (HasFieldPresence(descriptor_->file())) {
+ for (int i = 0; i < HasBitsSize() / 4; ++i) {
+ format("swap(_has_bits_[$1$], other->_has_bits_[$1$]);\n", i);
+ }
+ }
+
for (int i = 0; i < optimized_order_.size(); i++) {
// optimized_order_ does not contain oneof fields, but the field
// generators for these fields do not emit swapping code on their own.
@@ -2943,163 +3044,125 @@ GenerateSwap(io::Printer* printer) {
field_generators_.get(field).GenerateSwappingCode(printer);
}
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "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));
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("swap($1$_, other->$1$_);\n", oneof->name());
}
- if (HasFieldPresence(descriptor_->file())) {
- for (int i = 0; i < HasBitsSize() / 4; ++i) {
- printer->Print("swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
- "i", SimpleItoa(i));
- }
+ for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
+ format(
+ "swap(_oneof_case_[$1$], other->_oneof_case_[$1$]);\n", i);
}
- printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\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");
+ format("_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n");
}
} else {
- printer->Print("GetReflection()->Swap(this, other);");
+ format("GetReflection()->Swap(this, other);");
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateMergeFrom(io::Printer* printer) {
+void MessageGenerator::GenerateMergeFrom(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (HasDescriptorMethods(descriptor_->file(), options_)) {
// Generate the generalized MergeFrom (aka that which takes in the Message
// base class as a parameter).
- printer->Print(
- "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
+ format(
+ "void $classname$::MergeFrom(const ::$proto_ns$::Message& from) {\n"
"// @@protoc_insertion_point(generalized_merge_from_start:"
"$full_name$)\n"
- " GOOGLE_DCHECK_NE(&from, this);\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
+ " $DCHK$_NE(&from, this);\n");
+ format.Indent();
// Cast the message to the proper type. If we find that the message is
// *not* of the proper type, we can still call Merge via the reflection
// system, as the GOOGLE_CHECK above ensured that we have the same descriptor
// for each message.
- printer->Print(
- "const $classname$* source =\n"
- " ::google::protobuf::internal::DynamicCastToGenerated<const $classname$>(\n"
- " &from);\n"
- "if (source == NULL) {\n"
- "// @@protoc_insertion_point(generalized_merge_from_cast_fail:"
- "$full_name$)\n"
- " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
- "} else {\n"
- "// @@protoc_insertion_point(generalized_merge_from_cast_success:"
- "$full_name$)\n"
- " MergeFrom(*source);\n"
- "}\n",
- "classname", classname_, "full_name", descriptor_->full_name());
+ format(
+ "const $classname$* source =\n"
+ " ::$proto_ns$::DynamicCastToGenerated<$classname$>(\n"
+ " &from);\n"
+ "if (source == NULL) {\n"
+ "// @@protoc_insertion_point(generalized_merge_from_cast_fail:"
+ "$full_name$)\n"
+ " ::$proto_ns$::internal::ReflectionOps::Merge(from, this);\n"
+ "} else {\n"
+ "// @@protoc_insertion_point(generalized_merge_from_cast_success:"
+ "$full_name$)\n"
+ " MergeFrom(*source);\n"
+ "}\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ format.Outdent();
+ format("}\n\n");
} else {
// Generate CheckTypeAndMergeFrom().
- printer->Print(
- "void $classname$::CheckTypeAndMergeFrom(\n"
- " const ::google::protobuf::MessageLite& from) {\n"
- " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
- "}\n"
- "\n",
- "classname", classname_);
+ format(
+ "void $classname$::CheckTypeAndMergeFrom(\n"
+ " const ::$proto_ns$::MessageLite& from) {\n"
+ " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
+ "}\n"
+ "\n");
}
// Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
- printer->Print(
+ format(
"void $classname$::MergeFrom(const $classname$& from) {\n"
"// @@protoc_insertion_point(class_specific_merge_from_start:"
"$full_name$)\n"
- " GOOGLE_DCHECK_NE(&from, this);\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
+ " $DCHK$_NE(&from, this);\n");
+ format.Indent();
if (descriptor_->extension_range_count() > 0) {
- printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
+ format("_extensions_.MergeFrom(from._extensions_);\n");
}
- printer->Print(
- "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"
- "::google::protobuf::uint32 cached_has_bits = 0;\n"
- "(void) cached_has_bits;\n\n");
+ format(
+ "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"
+ "$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;
+ if (HasFieldPresence(descriptor_->file())) {
+ std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
+ optimized_order_, MatchRepeatedAndHasByte(&has_bit_indices_, true));
- int last_i = -1;
- for (int i = 0; i < optimized_order_.size(); ) {
- // Detect infinite loops.
- GOOGLE_CHECK_NE(i, last_i);
- last_i = i;
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_,
+ kColdRatio, true);
- // Merge Repeated fields. These fields do not require a
- // check as we can simply iterate over them.
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (!field->is_repeated()) {
- break;
- }
+ // 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;
- const FieldGenerator& generator = field_generators_.get(field);
- generator.GenerateMergingCode(printer);
- }
+ for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
+ const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
+ GOOGLE_CHECK(!chunk.empty());
- // Merge Optional and Required fields (after a _has_bit_ check).
- int last_chunk = -1;
- int last_chunk_start = -1;
- int last_chunk_end = -1;
- uint32 last_chunk_mask = 0;
- for (; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
- if (field->is_repeated()) {
- break;
- }
+ // Merge Repeated fields. These fields do not require a
+ // check as we can simply iterate over them.
+ if (chunk.front()->is_repeated()) {
+ for (int i = 0; i < chunk.size(); i++) {
+ const FieldDescriptor* field = chunk[i];
- // "index" defines where in the _has_bits_ the field appears.
- // "i" is our loop counter within optimized_order_.
- int index = HasFieldPresence(descriptor_->file()) ?
- has_bit_indices_[field->index()] : 0;
- int chunk = index / 8;
-
- if (last_chunk == -1) {
- last_chunk = chunk;
- last_chunk_start = i;
- } else if (chunk != last_chunk) {
- // Emit the fields for this chunk so far.
- break;
+ const FieldGenerator& generator = field_generators_.get(field);
+ generator.GenerateMergingCode(printer);
+ }
+ continue;
}
- last_chunk_end = i;
- last_chunk_mask |= static_cast<uint32>(1) << (index % 32);
- }
-
- if (last_chunk != -1) {
- GOOGLE_DCHECK_NE(-1, last_chunk_start);
- GOOGLE_DCHECK_NE(-1, last_chunk_end);
- GOOGLE_DCHECK_NE(0, last_chunk_mask);
+ // Merge Optional and Required fields (after a _has_bit_ check).
+ cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "from.",
+ printer);
- const int count = popcnt(last_chunk_mask);
- const bool have_outer_if = HasFieldPresence(descriptor_->file()) &&
- (last_chunk_start != last_chunk_end);
+ int last_chunk = has_bit_indices_[chunk.front()->index()] / 8;
+ GOOGLE_DCHECK_NE(-1, last_chunk);
+ const bool have_outer_if = chunk.size() > 1;
if (have_outer_if) {
+ uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
+ const int count = popcnt(last_chunk_mask);
+
// Check (up to) 8 has_bits at a time if we have more than one field in
// this chunk. Due to field layout ordering, we may check
// _has_bits_[last_chunk * 8 / 32] multiple times.
@@ -3107,50 +3170,32 @@ GenerateMergeFrom(io::Printer* printer) {
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;
+ cached_has_bit_index = last_chunk / 4;
+ format("cached_has_bits = from._has_bits_[$1$];\n",
+ cached_has_bit_index);
}
-
- printer->Print(
- "if (cached_has_bits & $mask$u) {\n",
- "mask", SimpleItoa(last_chunk_mask));
- printer->Indent();
+ format("if (cached_has_bits & 0x$1$u) {\n",
+ StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ format.Indent();
}
- // Go back and emit clears for each of the fields we processed.
+ // Go back and emit merging code 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];
+ for (const auto field : chunk) {
const FieldGenerator& generator = field_generators_.get(field);
- bool have_enclosing_if = false;
- if (HasFieldPresence(descriptor_->file())) {
- // 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));
- }
+ // 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->Indent();
- have_enclosing_if = true;
+ format("if (cached_has_bits & 0x$1$u) {\n", mask);
} else {
- // Merge semantics without true field presence: primitive fields are
- // merged only if non-zero (numeric) or non-empty (string).
- have_enclosing_if = EmitFieldNonDefaultCondition(
- printer, "from.", field);
+ format("if (from.has_$1$()) {\n", FieldName(field));
}
+ format.Indent();
if (have_outer_if && IsPOD(field)) {
// GenerateCopyConstructorCode for enum and primitive scalar fields
@@ -3164,181 +3209,234 @@ GenerateMergeFrom(io::Printer* printer) {
generator.GenerateMergingCode(printer);
}
- if (have_enclosing_if) {
- printer->Outdent();
- printer->Print("}\n");
- }
+ format.Outdent();
+ format("}\n");
}
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));
+ format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_bit_index);
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
+ }
+
+ if (cold_skipper.OnEndChunk(chunk_index, printer)) {
+ // Reset here as it may have been updated in just closed if statement.
+ cached_has_bit_index = -1;
+ }
+ }
+ } else {
+ // proto3
+ for (const auto field : optimized_order_) {
+ const FieldGenerator& generator = field_generators_.get(field);
+ // Merge semantics without true field presence: primitive fields are
+ // merged only if non-zero (numeric) or non-empty (string).
+ bool have_enclosing_if =
+ EmitFieldNonDefaultCondition(printer, "from.", field);
+
+ generator.GenerateMergingCode(printer);
+
+ if (have_enclosing_if) {
+ format.Outdent();
+ format("}\n");
}
}
}
// Merge oneof fields. Oneof field requires oneof case check.
- for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
- printer->Print(
- "switch (from.$oneofname$_case()) {\n",
- "oneofname", descriptor_->oneof_decl(i)->name());
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("switch (from.$1$_case()) {\n", oneof->name());
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
field_generators_.get(field).GenerateMergingCode(printer);
- printer->Print(
- "break;\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
+ format(
+ "case $1$_NOT_SET: {\n"
" break;\n"
"}\n",
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
- "}\n");
+ ToUpper(oneof->name()));
+ format.Outdent();
+ format("}\n");
}
if (num_weak_fields_) {
- printer->Print("_weak_field_map_.MergeFrom(from._weak_field_map_);\n");
+ format("_weak_field_map_.MergeFrom(from._weak_field_map_);\n");
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateCopyFrom(io::Printer* printer) {
+void MessageGenerator::GenerateCopyFrom(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (HasDescriptorMethods(descriptor_->file(), options_)) {
// Generate the generalized CopyFrom (aka that which takes in the Message
// base class as a parameter).
- printer->Print(
- "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n"
+ format(
+ "void $classname$::CopyFrom(const ::$proto_ns$::Message& from) {\n"
"// @@protoc_insertion_point(generalized_copy_from_start:"
- "$full_name$)\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
-
- printer->Print(
- "if (&from == this) return;\n"
- "Clear();\n"
- "MergeFrom(from);\n");
+ "$full_name$)\n");
+ format.Indent();
+
+ format("if (&from == this) return;\n");
+
+ if (!options_.opensource_runtime) {
+ // This check is disabled in the opensource release because we're
+ // concerned that many users do not define NDEBUG in their release
+ // builds.
+ format(
+ "#ifndef NDEBUG\n"
+ "size_t from_size = from.ByteSizeLong();\n"
+ "#endif\n"
+ "Clear();\n"
+ "#ifndef NDEBUG\n"
+ "$CHK$_EQ(from_size, from.ByteSizeLong())\n"
+ " << \"Source of CopyFrom changed when clearing target. Either \"\n"
+ " << \"source is a nested message in target (not allowed), or \"\n"
+ " << \"another thread is modifying the source.\";\n"
+ "#endif\n");
+ } else {
+ format("Clear();\n");
+ }
+ format("MergeFrom(from);\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ format.Outdent();
+ format("}\n\n");
}
// Generate the class-specific CopyFrom.
- printer->Print(
+ format(
"void $classname$::CopyFrom(const $classname$& from) {\n"
"// @@protoc_insertion_point(class_specific_copy_from_start:"
- "$full_name$)\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
-
- printer->Print(
- "if (&from == this) return;\n"
- "Clear();\n"
- "MergeFrom(from);\n");
+ "$full_name$)\n");
+ format.Indent();
+
+ format("if (&from == this) return;\n");
+
+ if (!options_.opensource_runtime) {
+ // This check is disabled in the opensource release because we're
+ // concerned that many users do not define NDEBUG in their release builds.
+ format(
+ "#ifndef NDEBUG\n"
+ "size_t from_size = from.ByteSizeLong();\n"
+ "#endif\n"
+ "Clear();\n"
+ "#ifndef NDEBUG\n"
+ "$CHK$_EQ(from_size, from.ByteSizeLong())\n"
+ " << \"Source of CopyFrom changed when clearing target. Either \"\n"
+ " << \"source is a nested message in target (not allowed), or \"\n"
+ " << \"another thread is modifying the source.\";\n"
+ "#endif\n");
+ } else {
+ format("Clear();\n");
+ }
+ format("MergeFrom(from);\n");
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateMergeFromCodedStream(io::Printer* printer) {
- std::map<string, string> vars;
+void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) {
+ std::map<string, string> vars = variables_;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ Formatter format(printer, vars);
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- vars["classname"] = classname_;
- printer->Print(vars,
- "bool $classname$::MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input) {\n"
- " return _extensions_.ParseMessageSet(input,\n"
- " internal_default_instance(), $mutable_unknown_fields$);\n"
- "}\n");
+ format(
+ "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
+ "const char* $classname$::_InternalParse(const char* begin, const "
+ "char* end, void* object,\n"
+ " ::$proto_ns$::internal::ParseContext* ctx) {\n"
+ " auto msg = static_cast<$classname$*>(object);\n"
+ " return ::$proto_ns$::internal::ParseMessageSet(begin, end, "
+ "msg, &msg->_extensions_, &msg->_internal_metadata_, ctx);\n"
+ "}\n"
+ "const char* $classname$::InternalParseMessageSetItem(const char* "
+ "begin, const char* end, void* object,\n"
+ " ::$proto_ns$::internal::ParseContext* ctx) {\n"
+ " auto msg = static_cast<$classname$*>(object);\n"
+ " return "
+ "msg->_extensions_.ParseMessageSetItem({InternalParseMessageSetItem, "
+ "msg}, begin, end, internal_default_instance(), "
+ "&msg->_internal_metadata_, ctx);\n"
+ "}\n"
+ "#else\n"
+ "bool $classname$::MergePartialFromCodedStream(\n"
+ " ::$proto_ns$::io::CodedInputStream* input) {\n"
+ " return _extensions_.ParseMessageSet(input,\n"
+ " internal_default_instance(), $mutable_unknown_fields$);\n"
+ "}\n"
+ "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
return;
}
+ format("#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
+ GenerateParserLoop(descriptor_, options_, scc_analyzer_, printer);
+ format("#else // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
std::vector<const FieldDescriptor*> ordered_fields =
SortFieldsByNumber(descriptor_);
- printer->Print(
- "bool $classname$::MergePartialFromCodedStream(\n"
- " ::google::protobuf::io::CodedInputStream* input) {\n",
- "classname", classname_);
+ format(
+ "bool $classname$::MergePartialFromCodedStream(\n"
+ " ::$proto_ns$::io::CodedInputStream* input) {\n");
if (table_driven_) {
- printer->Indent();
+ format.Indent();
- const string lite = UseUnknownFieldSet(descriptor_->file(), options_) ?
- "" : "Lite";
+ const string lite =
+ UseUnknownFieldSet(descriptor_->file(), options_) ? "" : "Lite";
- printer->Print(
- "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);
+ format(
+ "return ::$proto_ns$::internal::MergePartialFromCodedStream$1$(\n"
+ " this, ::$tablename$::schema[\n"
+ " $classname$::kIndexInFileMessages], input);\n",
+ lite);
- printer->Outdent();
+ format.Outdent();
- printer->Print("}\n");
+ format("}\n");
+ format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
return;
}
if (SupportsArenas(descriptor_)) {
- for (int i = 0; i < ordered_fields.size(); i++) {
- const FieldDescriptor* field = ordered_fields[i];
+ for (auto field : ordered_fields) {
const FieldGenerator& field_generator = field_generators_.get(field);
if (field_generator.MergeFromCodedStreamNeedsArena()) {
- printer->Print(
- " ::google::protobuf::Arena* arena = GetArenaNoVirtual();\n");
+ format(" ::$proto_ns$::Arena* arena = GetArenaNoVirtual();\n");
break;
}
}
}
- printer->Print(
- "#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto "
- "failure\n"
- " ::google::protobuf::uint32 tag;\n");
+ format(
+ "#define DO_(EXPRESSION) if "
+ "(!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure\n"
+ " $uint32$ tag;\n");
if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(
- " ::google::protobuf::internal::LiteUnknownFieldSetter unknown_fields_setter(\n"
+ format(
+ " ::$proto_ns$::internal::LiteUnknownFieldSetter "
+ "unknown_fields_setter(\n"
" &_internal_metadata_);\n"
- " ::google::protobuf::io::StringOutputStream unknown_fields_output(\n"
+ " ::$proto_ns$::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_);
+ " ::$proto_ns$::io::CodedOutputStream unknown_fields_stream(\n"
+ " &unknown_fields_output, false);\n");
}
- printer->Print(
- " // @@protoc_insertion_point(parse_start:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format(" // @@protoc_insertion_point(parse_start:$full_name$)\n");
- printer->Indent();
- printer->Print("for (;;) {\n");
- printer->Indent();
+ format.Indent();
+ format("for (;;) {\n");
+ format.Indent();
// To calculate the maximum tag to expect, we look at the highest-numbered
// field. We need to be prepared to handle more than one wire type if that
@@ -3355,8 +3453,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
bool capture_last_tag = false;
const Descriptor* parent = descriptor_->containing_type();
if (parent) {
- for (int i = 0; i < parent->field_count(); i++) {
- const FieldDescriptor* field = parent->field(i);
+ for (auto field : FieldRange(parent)) {
if (field->type() == FieldDescriptor::TYPE_GROUP &&
field->message_type() == descriptor_) {
capture_last_tag = true;
@@ -3383,13 +3480,12 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
}
}
- printer->Print("::std::pair<::google::protobuf::uint32, bool> p = "
- "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)));
+ format(
+ "::std::pair<$uint32$, bool> p = "
+ "input->ReadTagWithCutoffNoLastTag($1$u);\n"
+ "tag = p.first;\n"
+ "if (!p.second) goto handle_unusual;\n",
+ maxtag <= kCutoff0 ? kCutoff0 : (maxtag <= kCutoff1 ? kCutoff1 : maxtag));
if (descriptor_->field_count() > 0) {
// We don't even want to print the switch() if we have no fields because
@@ -3407,182 +3503,189 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
// inserts branches that may fail (especially for real world protos that
// interleave--in field number order--hot and cold fields). Loadtests
// confirmed that removing this optimization is performance neutral.
- printer->Print("switch (::google::protobuf::internal::WireFormatLite::"
- "GetTagFieldNumber(tag)) {\n");
-
- printer->Indent();
-
- for (int i = 0; i < ordered_fields.size(); i++) {
- const FieldDescriptor* field = ordered_fields[i];
-
- PrintFieldComment(printer, field);
+ if (num_weak_fields_ > 0) {
+ format("uint32 weak_offset;\n");
+ }
+ format(
+ "switch (::$proto_ns$::internal::WireFormatLite::"
+ "GetTagFieldNumber(tag)) {\n");
+
+ format.Indent();
+
+ for (auto field : ordered_fields) {
+ PrintFieldComment(format, field);
+ if (IsWeak(field, options_)) {
+ format(
+ "case $1$:\n"
+ " weak_offset = offsetof($classname$DefaultTypeInternal, $2$_);\n"
+ " goto handle_weak_field_map;\n",
+ field->number(), FieldName(field));
+ continue;
+ }
- printer->Print(
- "case $number$: {\n",
- "number", SimpleItoa(field->number()));
- printer->Indent();
+ format("case $1$: {\n", field->number());
+ format.Indent();
const FieldGenerator& field_generator = field_generators_.get(field);
// Emit code to parse the common, expected case.
- 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)));
+ // MSVC is warning about truncating constant in the static_cast so
+ // we truncate the tag explicitly.
+ format(
+ "if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
+ WireFormat::MakeTag(field));
- printer->Indent();
+ format.Indent();
if (field->is_packed()) {
field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
} else {
field_generator.GenerateMergeFromCodedStream(printer);
}
- printer->Outdent();
+ format.Outdent();
// Emit code to parse unexpectedly packed or unpacked values.
if (field->is_packed()) {
internal::WireFormatLite::WireType wiretype =
WireFormat::WireTypeForFieldType(field->type());
- 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();
+ const uint32 tag =
+ internal::WireFormatLite::MakeTag(field->number(), wiretype);
+ format(
+ "} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
+ tag);
+
+ format.Indent();
field_generator.GenerateMergeFromCodedStream(printer);
- printer->Outdent();
+ format.Outdent();
} else if (field->is_packable() && !field->is_packed()) {
internal::WireFormatLite::WireType wiretype =
internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
- 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();
+ const uint32 tag =
+ internal::WireFormatLite::MakeTag(field->number(), wiretype);
+ format(
+ "} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
+ tag);
+ format.Indent();
field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
- printer->Outdent();
+ format.Outdent();
}
- printer->Print(
- "} else {\n"
- " goto handle_unusual;\n"
- "}\n");
+ format(
+ "} else {\n"
+ " goto handle_unusual;\n"
+ "}\n");
- printer->Print(
- "break;\n");
+ format("break;\n");
- printer->Outdent();
- printer->Print("}\n\n");
+ format.Outdent();
+ format("}\n\n");
}
- printer->Print("default: {\n");
- printer->Indent();
+ if (num_weak_fields_ > 0) {
+ format("handle_weak_field_map: {\n");
+ format.Indent();
+
+ format(
+ "if ((tag & 0x7) != 2) goto handle_unusual;\n"
+ "DO_(_weak_field_map_.ReadMessage(input, tag >> 3,\n"
+ " &_$classname$_default_instance_, weak_offset));\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n\n");
+ }
+ format("default: {\n");
+ format.Indent();
}
- printer->Outdent();
- printer->Print("handle_unusual:\n");
- printer->Indent();
+ format.Outdent();
+ format("handle_unusual:\n");
+ format.Indent();
// If tag is 0 or an end-group tag then this must be the end of the message.
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");
+ format(
+ "if (tag == 0 ||\n"
+ " ::$proto_ns$::internal::WireFormatLite::GetTagWireType(tag) ==\n"
+ " ::$proto_ns$::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");
+ format(
+ "if (tag == 0) {\n"
+ " goto success;\n"
+ "}\n");
}
// Handle extension ranges.
if (descriptor_->extension_range_count() > 0) {
- printer->Print(
- "if (");
+ format("if (");
for (int i = 0; i < descriptor_->extension_range_count(); i++) {
- const Descriptor::ExtensionRange* range =
- descriptor_->extension_range(i);
- if (i > 0) printer->Print(" ||\n ");
+ const Descriptor::ExtensionRange* range = descriptor_->extension_range(i);
+ if (i > 0) format(" ||\n ");
uint32 start_tag = WireFormatLite::MakeTag(
- range->start, static_cast<WireFormatLite::WireType>(0));
+ range->start, static_cast<WireFormatLite::WireType>(0));
uint32 end_tag = WireFormatLite::MakeTag(
- range->end, static_cast<WireFormatLite::WireType>(0));
+ range->end, static_cast<WireFormatLite::WireType>(0));
if (range->end > FieldDescriptor::kMaxNumber) {
- printer->Print(
- "($start$u <= tag)",
- "start", SimpleItoa(start_tag));
+ format("($1$u <= tag)", start_tag);
} else {
- printer->Print(
- "($start$u <= tag && tag < $end$u)",
- "start", SimpleItoa(start_tag),
- "end", SimpleItoa(end_tag));
+ format("($1$u <= tag && tag < $2$u)", start_tag, end_tag);
}
}
- printer->Print(") {\n");
+ format(") {\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(vars,
- " DO_(_extensions_.ParseField(tag, input,\n"
- " internal_default_instance(),\n"
- " $mutable_unknown_fields$));\n");
+ format(
+ " DO_(_extensions_.ParseField(tag, input,\n"
+ " internal_default_instance(),\n"
+ " $mutable_unknown_fields$));\n");
} else {
- printer->Print(
- " DO_(_extensions_.ParseField(tag, input,\n"
- " internal_default_instance(),\n"
- " &unknown_fields_stream));\n");
+ format(
+ " DO_(_extensions_.ParseField(tag, input,\n"
+ " internal_default_instance(),\n"
+ " &unknown_fields_stream));\n");
}
- printer->Print(
- " continue;\n"
- "}\n");
+ format(
+ " continue;\n"
+ "}\n");
}
// We really don't recognize this tag. Skip it.
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(vars,
- "DO_(::google::protobuf::internal::WireFormat::SkipField(\n"
+ format(
+ "DO_(::$proto_ns$::internal::WireFormat::SkipField(\n"
" input, tag, $mutable_unknown_fields$));\n");
} else {
- printer->Print(
- "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n"
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::SkipField(\n"
" input, tag, &unknown_fields_stream));\n");
}
if (descriptor_->field_count() > 0) {
- printer->Print("break;\n");
- printer->Outdent();
- printer->Print("}\n"); // default:
- printer->Outdent();
- printer->Print("}\n"); // switch
- }
-
- printer->Outdent();
- printer->Outdent();
- printer->Print(
- " }\n" // for (;;)
- "success:\n"
- " // @@protoc_insertion_point(parse_success:$full_name$)\n"
- " return true;\n"
- "failure:\n"
- " // @@protoc_insertion_point(parse_failure:$full_name$)\n"
- " return false;\n"
- "#undef DO_\n"
- "}\n", "full_name", descriptor_->full_name());
+ format("break;\n");
+ format.Outdent();
+ format("}\n"); // default:
+ format.Outdent();
+ format("}\n"); // switch
+ }
+
+ format.Outdent();
+ format.Outdent();
+ format(
+ " }\n" // for (;;)
+ "success:\n"
+ " // @@protoc_insertion_point(parse_success:$full_name$)\n"
+ " return true;\n"
+ "failure:\n"
+ " // @@protoc_insertion_point(parse_failure:$full_name$)\n"
+ " return false;\n"
+ "#undef DO_\n"
+ "}\n");
+ format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
}
void MessageGenerator::GenerateSerializeOneofFields(
io::Printer* printer, const std::vector<const FieldDescriptor*>& fields,
bool to_array) {
+ Formatter format(printer, variables_);
GOOGLE_CHECK(!fields.empty());
if (fields.size() == 1) {
GenerateSerializeOneField(printer, fields[0], to_array, -1);
@@ -3590,39 +3693,35 @@ void MessageGenerator::GenerateSerializeOneofFields(
}
// We have multiple mutually exclusive choices. Emit a switch statement.
const OneofDescriptor* oneof = fields[0]->containing_oneof();
- printer->Print(
- "switch ($oneofname$_case()) {\n",
- "oneofname", oneof->name());
- printer->Indent();
- for (int i = 0; i < fields.size(); i++) {
- const FieldDescriptor* field = fields[i];
- printer->Print(
- "case k$field_name$:\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ format("switch ($1$_case()) {\n", oneof->name());
+ format.Indent();
+ for (auto field : fields) {
+ format("case k$1$:\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
if (to_array) {
field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
printer);
} else {
field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
}
- printer->Print(
- "break;\n");
- printer->Outdent();
+ format("break;\n");
+ format.Outdent();
}
- printer->Outdent();
+ format.Outdent();
// Doing nothing is an option.
- printer->Print(
- " default: ;\n"
- "}\n");
+ format(
+ " default: ;\n"
+ "}\n");
}
-void MessageGenerator::GenerateSerializeOneField(
- io::Printer* printer, const FieldDescriptor* field, bool to_array,
- int cached_has_bits_index) {
+void MessageGenerator::GenerateSerializeOneField(io::Printer* printer,
+ const FieldDescriptor* field,
+ bool to_array,
+ int cached_has_bits_index) {
+ Formatter format(printer, variables_);
if (!field->options().weak()) {
// For weakfields, PrintFieldComment is called during iteration.
- PrintFieldComment(printer, field);
+ PrintFieldComment(format, field);
}
bool have_enclosing_if = false;
@@ -3631,19 +3730,15 @@ void MessageGenerator::GenerateSerializeOneField(
// 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));
+ 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);
+ format("if (cached_has_bits & 0x$1$u) {\n", mask);
} else {
- printer->Print(
- "if (has_$name$()) {\n",
- "name", FieldName(field));
+ format("if (has_$1$()) {\n", FieldName(field));
}
- printer->Indent();
+ format.Indent();
have_enclosing_if = true;
} else if (!HasFieldPresence(descriptor_->file())) {
have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field);
@@ -3657,10 +3752,10 @@ void MessageGenerator::GenerateSerializeOneField(
}
if (have_enclosing_if) {
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print("\n");
+ format("\n");
}
void MessageGenerator::GenerateSerializeOneExtensionRange(
@@ -3669,110 +3764,100 @@ void MessageGenerator::GenerateSerializeOneExtensionRange(
std::map<string, string> vars;
vars["start"] = SimpleItoa(range->start);
vars["end"] = SimpleItoa(range->end);
- printer->Print(vars,
- "// Extension range [$start$, $end$)\n");
+ Formatter format(printer, vars);
+ format("// Extension range [$start$, $end$)\n");
if (to_array) {
- printer->Print(vars,
- "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n"
- " $start$, $end$, deterministic, target);\n\n");
+ format(
+ "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n"
+ " $start$, $end$, deterministic, target);\n\n");
} else {
- printer->Print(vars,
- "_extensions_.SerializeWithCachedSizes(\n"
- " $start$, $end$, output);\n\n");
+ format(
+ "_extensions_.SerializeWithCachedSizes($start$, $end$, output);\n"
+ "\n");
}
}
-void MessageGenerator::
-GenerateSerializeWithCachedSizes(io::Printer* printer) {
+void MessageGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer) {
+ Formatter format(printer, variables_);
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- printer->Print(
- "void $classname$::SerializeWithCachedSizes(\n"
- " ::google::protobuf::io::CodedOutputStream* output) const {\n"
- " _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
- "classname", classname_);
- GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
+ format(
+ "void $classname$::SerializeWithCachedSizes(\n"
+ " ::$proto_ns$::io::CodedOutputStream* output) const {\n"
+ " _extensions_.SerializeMessageSetWithCachedSizes(output);\n");
std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
- printer->Print(vars,
- " ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n"
- " $unknown_fields$, output);\n");
- printer->Print(
- "}\n");
+ format.AddMap(vars);
+ format(
+ " "
+ "::$proto_ns$::internal::SerializeUnknownMessageSetItems(\n"
+ " $unknown_fields$, output);\n");
+ format("}\n");
return;
}
if (options_.table_driven_serialization) return;
- printer->Print(
- "void $classname$::SerializeWithCachedSizes(\n"
- " ::google::protobuf::io::CodedOutputStream* output) const {\n",
- "classname", classname_);
- printer->Indent();
+ format(
+ "void $classname$::SerializeWithCachedSizes(\n"
+ " ::$proto_ns$::io::CodedOutputStream* output) const {\n");
+ format.Indent();
- printer->Print(
- "// @@protoc_insertion_point(serialize_start:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format("// @@protoc_insertion_point(serialize_start:$full_name$)\n");
GenerateSerializeWithCachedSizesBody(printer, false);
- printer->Print(
- "// @@protoc_insertion_point(serialize_end:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format("// @@protoc_insertion_point(serialize_end:$full_name$)\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
+void MessageGenerator::GenerateSerializeWithCachedSizesToArray(
+ io::Printer* printer) {
+ Formatter format(printer, variables_);
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- printer->Print(
- "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n"
- " bool deterministic, ::google::protobuf::uint8* target) const {\n"
- " target = _extensions_."
- "InternalSerializeMessageSetWithCachedSizesToArray(\n"
- " deterministic, target);\n",
- "classname", classname_);
+ format(
+ "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n"
+ " bool deterministic, $uint8$* target) const {\n"
+ " target = _extensions_."
+ "InternalSerializeMessageSetWithCachedSizesToArray(\n"
+ " deterministic, target);\n");
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
- printer->Print(vars,
- " target = ::google::protobuf::internal::WireFormat::\n"
- " SerializeUnknownMessageSetItemsToArray(\n"
- " $unknown_fields$, target);\n");
- printer->Print(
- " return target;\n"
- "}\n");
+ format.AddMap(vars);
+ format(
+ " target = ::$proto_ns$::internal::WireFormat::\n"
+ " SerializeUnknownMessageSetItemsToArray(\n"
+ " $unknown_fields$, target);\n");
+ format(
+ " return target;\n"
+ "}\n");
return;
}
- printer->Print(
- "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n"
- " bool deterministic, ::google::protobuf::uint8* target) const {\n",
- "classname", classname_);
- printer->Indent();
+ format(
+ "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n"
+ " bool deterministic, $uint8$* target) const {\n");
+ format.Indent();
- printer->Print("(void)deterministic; // Unused\n");
- printer->Print(
- "// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format("(void)deterministic; // Unused\n");
+ format("// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n");
GenerateSerializeWithCachedSizesBody(printer, true);
- printer->Print(
- "// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n",
- "full_name", descriptor_->full_name());
+ format("// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n");
- printer->Outdent();
- printer->Print(
- " return target;\n"
- "}\n");
+ format.Outdent();
+ format(
+ " return target;\n"
+ "}\n");
}
-void MessageGenerator::
-GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
+void MessageGenerator::GenerateSerializeWithCachedSizesBody(
+ io::Printer* printer, bool to_array) {
+ Formatter format(printer, variables_);
// If there are multiple fields in a row from the same oneof then we
// coalesce them and emit a switch statement. This is more efficient
// because it lets the C++ compiler know this is a "at most one can happen"
@@ -3783,7 +3868,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer,
bool to_array)
: mg_(mg),
- printer_(printer),
+ format_(printer),
to_array_(to_array),
eager_(!HasFieldPresence(mg->descriptor_->file())),
cached_has_bit_index_(-1) {}
@@ -3808,16 +3893,14 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
// Reload.
int new_index = has_bit_index / 32;
- printer_->Print(
- "cached_has_bits = _has_bits_[$new_index$];\n",
- "new_index", SimpleItoa(new_index));
+ format_("cached_has_bits = _has_bits_[$1$];\n", new_index);
cached_has_bit_index_ = new_index;
}
}
- mg_->GenerateSerializeOneField(
- printer_, field, to_array_, cached_has_bit_index_);
+ mg_->GenerateSerializeOneField(format_.printer(), field, to_array_,
+ cached_has_bit_index_);
} else {
v_.push_back(field);
}
@@ -3825,7 +3908,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
void Flush() {
if (!v_.empty()) {
- mg_->GenerateSerializeOneofFields(printer_, v_, to_array_);
+ mg_->GenerateSerializeOneofFields(format_.printer(), v_, to_array_);
v_.clear();
}
}
@@ -3839,7 +3922,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
}
MessageGenerator* mg_;
- io::Printer* printer_;
+ Formatter format_;
const bool to_array_;
const bool eager_;
std::vector<const FieldDescriptor*> v_;
@@ -3860,13 +3943,13 @@ 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("
+ format(
+ "::$proto_ns$::internal::WeakFieldMap::FieldWriter field_writer("
"_weak_field_map_);\n");
}
- printer->Print(
- "::google::protobuf::uint32 cached_has_bits = 0;\n"
+ format(
+ "$uint32$ cached_has_bits = 0;\n"
"(void) cached_has_bits;\n\n");
// Merge the fields and the extension ranges, both sorted by field number.
@@ -3882,7 +3965,7 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
const FieldDescriptor* field = ordered_fields[i++];
if (field->options().weak()) {
last_weak_field = field;
- PrintFieldComment(printer, field);
+ PrintFieldComment(format, field);
} else {
if (last_weak_field != nullptr) {
e.Emit(last_weak_field);
@@ -3890,14 +3973,13 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
}
e.Emit(field);
}
- } else {
+ } else {
if (last_weak_field != nullptr) {
e.Emit(last_weak_field);
last_weak_field = nullptr;
}
e.Flush();
- GenerateSerializeOneExtensionRange(printer,
- sorted_extensions[j++],
+ GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++],
to_array);
}
}
@@ -3908,27 +3990,27 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(vars);
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- printer->Print(vars,
- "if ($have_unknown_fields$) {\n");
- printer->Indent();
+ format("if ($have_unknown_fields$) {\n");
+ format.Indent();
if (to_array) {
- printer->Print(vars,
- "target = "
- "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
- " $unknown_fields$, target);\n");
+ format(
+ "target = "
+ "::$proto_ns$::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
+ " $unknown_fields$, target);\n");
} else {
- printer->Print(vars,
- "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
- " $unknown_fields$, output);\n");
+ format(
+ "::$proto_ns$::internal::WireFormat::SerializeUnknownFields(\n"
+ " $unknown_fields$, output);\n");
}
- printer->Outdent();
+ format.Outdent();
- printer->Print("}\n");
+ format("}\n");
} else {
- printer->Print(vars,
- "output->WriteRaw($unknown_fields$.data(),\n"
- " static_cast<int>($unknown_fields$.size()));\n");
+ format(
+ "output->WriteRaw($unknown_fields$.data(),\n"
+ " static_cast<int>($unknown_fields$.size()));\n");
}
}
@@ -3936,15 +4018,13 @@ std::vector<uint32> MessageGenerator::RequiredFieldsBitMask() const {
const int array_size = HasBitsSize();
std::vector<uint32> masks(array_size, 0);
- for (int i = 0; i < descriptor_->field_count(); i++) {
- const FieldDescriptor* field = descriptor_->field(i);
+ for (auto field : FieldRange(descriptor_)) {
if (!field->is_required()) {
continue;
}
const int has_bit_index = has_bit_indices_[field->index()];
- masks[has_bit_index / 32] |=
- static_cast<uint32>(1) << (has_bit_index % 32);
+ masks[has_bit_index / 32] |= static_cast<uint32>(1) << (has_bit_index % 32);
}
return masks;
}
@@ -3959,35 +4039,36 @@ static string ConditionalToCheckBitmasks(const std::vector<uint32>& masks) {
if (masks[i] == 0) continue;
string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
// Each xor evaluates to 0 if the expected bits are present.
- parts.push_back(StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
+ parts.push_back(
+ StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
}
GOOGLE_CHECK(!parts.empty());
// If we have multiple parts, each expected to be 0, then bitwise-or them.
- string result = parts.size() == 1
- ? parts[0]
- : StrCat("(", Join(parts, "\n | "), ")");
+ string result =
+ parts.size() == 1
+ ? parts[0]
+ : StrCat("(", Join(parts, "\n | "), ")");
return result + " == 0";
}
-void MessageGenerator::
-GenerateByteSize(io::Printer* printer) {
+void MessageGenerator::GenerateByteSize(io::Printer* printer) {
+ Formatter format(printer, variables_);
+
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
- GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
- vars["classname"] = classname_;
- vars["full_name"] = descriptor_->full_name();
- printer->Print(
- vars,
+ format.AddMap(vars);
+ format(
"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"
+ " total_size += ::$proto_ns$::internal::\n"
" ComputeUnknownMessageSetItemsSize($unknown_fields$);\n"
" }\n"
- " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
+ " int cached_size = "
+ "::$proto_ns$::internal::ToCachedSize(total_size);\n"
" SetCachedSize(cached_size);\n"
" return total_size;\n"
"}\n");
@@ -3997,60 +4078,60 @@ GenerateByteSize(io::Printer* printer) {
if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
// Emit a function (rarely used, we hope) that handles the required fields
// by checking for each one individually.
- printer->Print(
+ format(
"size_t $classname$::RequiredFieldsByteSizeFallback() const {\n"
"// @@protoc_insertion_point(required_fields_byte_size_fallback_start:"
- "$full_name$)\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
- printer->Print("size_t total_size = 0;\n");
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
+ "$full_name$)\n");
+ format.Indent();
+ format("size_t total_size = 0;\n");
+ for (auto field : optimized_order_) {
if (field->is_required()) {
- printer->Print("\n"
- "if (has_$name$()) {\n",
- "name", FieldName(field));
- printer->Indent();
- PrintFieldComment(printer, field);
+ format(
+ "\n"
+ "if (has_$1$()) {\n",
+ FieldName(field));
+ format.Indent();
+ PrintFieldComment(format, field);
field_generators_.get(field).GenerateByteSize(printer);
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
}
- printer->Print("\n"
- "return total_size;\n");
- printer->Outdent();
- printer->Print("}\n");
+ format(
+ "\n"
+ "return total_size;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
+ format(
"size_t $classname$::ByteSizeLong() const {\n"
- "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n",
- "classname", classname_, "full_name", descriptor_->full_name());
- printer->Indent();
- printer->Print(
- "size_t total_size = 0;\n"
- "\n");
+ "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n");
+ format.Indent();
+ format(
+ "size_t total_size = 0;\n"
+ "\n");
if (descriptor_->extension_range_count() > 0) {
- printer->Print(
- "total_size += _extensions_.ByteSize();\n"
- "\n");
+ format(
+ "total_size += _extensions_.ByteSize();\n"
+ "\n");
}
std::map<string, string> vars;
SetUnknkownFieldsVariable(descriptor_, options_, &vars);
+ format.AddMap(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");
+ format(
+ "if ($have_unknown_fields$) {\n"
+ " total_size +=\n"
+ " ::$proto_ns$::internal::WireFormat::ComputeUnknownFieldsSize(\n"
+ " $unknown_fields$);\n"
+ "}\n");
} else {
- printer->Print(vars,
- "total_size += $unknown_fields$.size();\n"
- "\n");
+ format(
+ "total_size += $unknown_fields$.size();\n"
+ "\n");
}
// Handle required fields (if any). We expect all of them to be
@@ -4059,35 +4140,32 @@ GenerateByteSize(io::Printer* printer) {
if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
// The fast path works if all required fields are present.
const std::vector<uint32> masks_for_has_bits = RequiredFieldsBitMask();
- printer->Print((string("if (") +
- ConditionalToCheckBitmasks(masks_for_has_bits) +
- ") { // All required fields are present.\n").c_str());
- printer->Indent();
+ format("if ($1$) { // All required fields are present.\n",
+ ConditionalToCheckBitmasks(masks_for_has_bits));
+ format.Indent();
// Oneof fields cannot be required, so optimized_order_ contains all of the
// fields that we need to potentially emit.
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
if (!field->is_required()) continue;
- PrintFieldComment(printer, field);
+ PrintFieldComment(format, field);
field_generators_.get(field).GenerateByteSize(printer);
- printer->Print("\n");
+ format("\n");
}
- printer->Outdent();
- printer->Print("} else {\n" // the slow path
- " total_size += RequiredFieldsByteSizeFallback();\n"
- "}\n");
+ format.Outdent();
+ format(
+ "} else {\n" // the slow path
+ " total_size += RequiredFieldsByteSizeFallback();\n"
+ "}\n");
} else {
// num_required_fields_ <= 1: no need to be tricky
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
if (!field->is_required()) continue;
- PrintFieldComment(printer, field);
- printer->Print("if (has_$name$()) {\n",
- "name", FieldName(field));
- printer->Indent();
+ PrintFieldComment(format, field);
+ format("if (has_$1$()) {\n", FieldName(field));
+ format.Indent();
field_generators_.get(field).GenerateByteSize(printer);
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
}
@@ -4100,6 +4178,16 @@ GenerateByteSize(io::Printer* printer) {
chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired),
chunks.end());
+ ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
+ HasFieldPresence(descriptor_->file()));
+
+ format(
+ "$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;
+
for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
GOOGLE_CHECK(!chunk.empty());
@@ -4109,14 +4197,16 @@ GenerateByteSize(io::Printer* printer) {
for (int i = 0; i < chunk.size(); i++) {
const FieldDescriptor* field = chunk[i];
- PrintFieldComment(printer, field);
+ PrintFieldComment(format, field);
const FieldGenerator& generator = field_generators_.get(field);
generator.GenerateByteSize(printer);
- printer->Print("\n");
+ format("\n");
}
continue;
}
+ cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
+
// Handle optional (non-repeated/oneof) fields.
//
// These are handled in chunks of 8. The first chunk is
@@ -4144,10 +4234,13 @@ GenerateByteSize(io::Printer* printer) {
GOOGLE_DCHECK_LE(2, count);
GOOGLE_DCHECK_GE(8, count);
- printer->Print("if (_has_bits_[$index$ / 32] & $mask$u) {\n", "index",
- SimpleItoa(last_chunk * 8), "mask",
- SimpleItoa(last_chunk_mask));
- printer->Indent();
+ if (cached_has_bit_index != last_chunk / 4) {
+ cached_has_bit_index = last_chunk / 4;
+ format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
+ }
+ format("if (cached_has_bits & 0x$1$u) {\n",
+ StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
+ format.Indent();
}
// Go back and emit checks for each of the fields we processed.
@@ -4155,12 +4248,12 @@ GenerateByteSize(io::Printer* printer) {
const FieldDescriptor* field = chunk[j];
const FieldGenerator& generator = field_generators_.get(field);
- PrintFieldComment(printer, field);
+ PrintFieldComment(format, field);
bool have_enclosing_if = false;
if (HasFieldPresence(descriptor_->file())) {
- printer->Print("if (has_$name$()) {\n", "name", FieldName(field));
- printer->Indent();
+ PrintPresenceCheck(format, field, has_bit_indices_, printer,
+ &cached_has_bit_index);
have_enclosing_if = true;
} else {
// Without field presence: field is serialized only if it has a
@@ -4172,54 +4265,50 @@ GenerateByteSize(io::Printer* printer) {
generator.GenerateByteSize(printer);
if (have_enclosing_if) {
- printer->Outdent();
- printer->Print(
+ format.Outdent();
+ format(
"}\n"
"\n");
}
}
if (have_outer_if) {
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
+ }
+
+ if (cold_skipper.OnEndChunk(chunk_index, printer)) {
+ // Reset here as it may have been updated in just closed if statement.
+ cached_has_bit_index = -1;
}
}
// Fields inside a oneof don't use _has_bits_ so we count them in a separate
// pass.
- for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
- printer->Print(
- "switch ($oneofname$_case()) {\n",
- "oneofname", descriptor_->oneof_decl(i)->name());
- printer->Indent();
- for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
- const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- PrintFieldComment(printer, field);
- printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ for (auto oneof : OneOfRange(descriptor_)) {
+ format("switch ($1$_case()) {\n", oneof->name());
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ PrintFieldComment(format, field);
+ format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
field_generators_.get(field).GenerateByteSize(printer);
- printer->Print(
- "break;\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
+ format(
+ "case $1$_NOT_SET: {\n"
" break;\n"
"}\n",
- "cap_oneof_name",
- ToUpper(descriptor_->oneof_decl(i)->name()));
- printer->Outdent();
- printer->Print(
- "}\n");
+ ToUpper(oneof->name()));
+ format.Outdent();
+ format("}\n");
}
if (num_weak_fields_) {
// TagSize + MessageSize
- printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n");
+ format("total_size += _weak_field_map_.ByteSizeLong();\n");
}
// We update _cached_size_ even though this is a const method. Because
@@ -4230,27 +4319,25 @@ GenerateByteSize(io::Printer* printer) {
// the underlying atomic. This makes it easier on platforms where even relaxed
// memory order might have perf impact to replace it with ordinary loads and
// stores.
- printer->Print(
- "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
+ format(
+ "int cached_size = ::$proto_ns$::internal::ToCachedSize(total_size);\n"
"SetCachedSize(cached_size);\n"
"return total_size;\n");
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
-void MessageGenerator::
-GenerateIsInitialized(io::Printer* printer) {
- printer->Print(
- "bool $classname$::IsInitialized() const {\n",
- "classname", classname_);
- printer->Indent();
+void MessageGenerator::GenerateIsInitialized(io::Printer* printer) {
+ Formatter format(printer, variables_);
+ format("bool $classname$::IsInitialized() const {\n");
+ format.Indent();
if (descriptor_->extension_range_count() > 0) {
- printer->Print(
- "if (!_extensions_.IsInitialized()) {\n"
- " return false;\n"
- "}\n\n");
+ format(
+ "if (!_extensions_.IsInitialized()) {\n"
+ " return false;\n"
+ "}\n\n");
}
if (HasFieldPresence(descriptor_->file())) {
@@ -4267,57 +4354,51 @@ GenerateIsInitialized(io::Printer* printer) {
// TODO(ckennelly): Consider doing something similar to ByteSizeLong(),
// where we check all of the required fields in a single branch (assuming
// that we aren't going to benefit from early termination).
- printer->Print(
- "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n",
- "i", SimpleItoa(i),
- "mask", StrCat(strings::Hex(mask, strings::ZERO_PAD_8)));
+ format("if ((_has_bits_[$1$] & 0x$2$) != 0x$2$) return false;\n",
+ i, // 1
+ StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); // 2
}
}
// Now check that all non-oneof embedded messages are initialized.
- for (int i = 0; i < optimized_order_.size(); i++) {
- const FieldDescriptor* field = optimized_order_[i];
+ for (auto field : optimized_order_) {
// TODO(ckennelly): Push this down into a generator?
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
scc_analyzer_->HasRequiredFields(field->message_type())) {
if (field->is_repeated()) {
if (IsImplicitWeakField(field, options_, scc_analyzer_)) {
- printer->Print(
- "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))"
- " return false;\n",
- "name", FieldName(field));
+ format(
+ "if (!::$proto_ns$::internal::AllAreInitializedWeak(this->$1$_))"
+ " return false;\n",
+ FieldName(field));
} else {
- printer->Print(
- "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))"
- " return false;\n",
- "name", FieldName(field));
+ format(
+ "if (!::$proto_ns$::internal::AllAreInitialized(this->$1$()))"
+ " return false;\n",
+ FieldName(field));
}
} else if (field->options().weak()) {
continue;
} else {
GOOGLE_CHECK(!field->containing_oneof());
- printer->Print(
- "if (has_$name$()) {\n"
- " if (!this->$name$_->IsInitialized()) return false;\n"
+ format(
+ "if (has_$1$()) {\n"
+ " if (!this->$1$_->IsInitialized()) return false;\n"
"}\n",
- "name", FieldName(field));
+ FieldName(field));
}
}
}
if (num_weak_fields_) {
// For Weak fields.
- printer->Print("if (!_weak_field_map_.IsInitialized()) return false;\n");
+ format("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++) {
- const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
-
+ for (auto oneof : OneOfRange(descriptor_)) {
bool has_required_fields = false;
- for (int j = 0; j < oneof->field_count(); j++) {
- const FieldDescriptor* field = oneof->field(j);
-
+ for (auto field : FieldRange(oneof)) {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
scc_analyzer_->HasRequiredFields(field->message_type())) {
@@ -4330,16 +4411,11 @@ GenerateIsInitialized(io::Printer* printer) {
continue;
}
- printer->Print(
- "switch ($oneofname$_case()) {\n",
- "oneofname", oneof->name());
- printer->Indent();
- for (int j = 0; j < oneof->field_count(); j++) {
- const FieldDescriptor* field = oneof->field(j);
- printer->Print(
- "case k$field_name$: {\n",
- "field_name", UnderscoresToCamelCase(field->name(), true));
- printer->Indent();
+ format("switch ($1$_case()) {\n", oneof->name());
+ format.Indent();
+ for (auto field : FieldRange(oneof)) {
+ format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
+ format.Indent();
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!ShouldIgnoreRequiredFieldCheck(field, options_) &&
@@ -4348,35 +4424,31 @@ GenerateIsInitialized(io::Printer* printer) {
if (field->options().weak()) {
// Just skip.
} else {
- printer->Print(
- "if (has_$name$()) {\n"
- " if (!this->$name$().IsInitialized()) return false;\n"
- "}\n",
- "name", FieldName(field));
+ format(
+ "if (has_$1$()) {\n"
+ " if (!this->$1$().IsInitialized()) return false;\n"
+ "}\n",
+ FieldName(field));
}
}
- printer->Print(
- "break;\n");
- printer->Outdent();
- printer->Print(
- "}\n");
+ format("break;\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Print(
- "case $cap_oneof_name$_NOT_SET: {\n"
+ format(
+ "case $1$_NOT_SET: {\n"
" break;\n"
"}\n",
- "cap_oneof_name",
ToUpper(oneof->name()));
- printer->Outdent();
- printer->Print(
- "}\n");
+ format.Outdent();
+ format("}\n");
}
- printer->Outdent();
- printer->Print(
- " return true;\n"
- "}\n");
+ format.Outdent();
+ format(
+ " return true;\n"
+ "}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index ca2ca2c9..6bef8d56 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message.h
@@ -45,37 +45,33 @@
namespace google {
namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
-class EnumGenerator; // enum.h
-class ExtensionGenerator; // extension.h
+class EnumGenerator; // enum.h
+class ExtensionGenerator; // extension.h
class MessageGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
- MessageGenerator(const Descriptor* descriptor, int index_in_file_messages,
- const Options& options, SCCAnalyzer* scc_analyzer);
+ MessageGenerator(const Descriptor* descriptor,
+ const std::map<std::string, std::string>& vars,
+ int index_in_file_messages, const Options& options,
+ MessageSCCAnalyzer* scc_analyzer);
~MessageGenerator();
// Append the two types of nested generators to the corresponding vector.
- void AddGenerators(std::vector<EnumGenerator*>* enum_generators,
- std::vector<ExtensionGenerator*>* extension_generators);
-
- // Header stuff.
-
- // Return names for forward declarations of this class and all its nested
- // types. A given key in {class,enum}_names will map from a class name to the
- // descriptor that was responsible for its inclusion in the map. This can be
- // used to associate the descriptor with the code generated for it.
- void FillMessageForwardDeclarations(
- std::map<string, const Descriptor*>* class_names);
+ void AddGenerators(
+ std::vector<std::unique_ptr<EnumGenerator>>* enum_generators,
+ std::vector<std::unique_ptr<ExtensionGenerator>>* extension_generators);
// Generate definitions for this class and all its nested types.
void GenerateClassDefinition(io::Printer* printer);
@@ -112,8 +108,8 @@ class MessageGenerator {
// 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.
+ // Generates a ParseTable entry. Returns whether the proto uses
+ // table-driven parsing.
bool GenerateParseTable(io::Printer* printer, size_t offset,
size_t aux_offset);
@@ -140,8 +136,8 @@ class MessageGenerator {
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.
+ // 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);
@@ -166,8 +162,7 @@ class MessageGenerator {
// 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,
+ const FieldDescriptor* field, 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().
@@ -180,19 +175,15 @@ class MessageGenerator {
// Generates has_foo() functions and variables for singular field has-bits.
void GenerateSingularFieldHasBits(const FieldDescriptor* field,
- std::map<string, string> vars,
- io::Printer* printer);
+ Formatter format);
// Generates has_foo() functions and variables for oneof field has-bits.
void GenerateOneofHasBits(io::Printer* printer);
// Generates has_foo_bar() functions for oneof members.
void GenerateOneofMemberHasBits(const FieldDescriptor* field,
- const std::map<string, string>& vars,
- io::Printer* printer);
+ const Formatter& format);
// 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 GenerateFieldClear(const FieldDescriptor* field, bool is_inline,
+ Formatter format);
void GenerateConstructorBody(io::Printer* printer,
std::vector<bool> already_processed,
@@ -203,18 +194,19 @@ class MessageGenerator {
const Descriptor* descriptor_;
int index_in_file_messages_;
- string classname_;
+ std::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_ 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 and weak fields.
- std::vector<const FieldDescriptor *> optimized_order_;
+ std::vector<const FieldDescriptor*> optimized_order_;
std::vector<int> has_bit_indices_;
int max_has_bit_index_;
- std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_;
- std::unique_ptr<std::unique_ptr<ExtensionGenerator> []> extension_generators_;
+ std::vector<const EnumGenerator*> enum_generators_;
+ std::vector<const ExtensionGenerator*> extension_generators_;
int num_required_fields_;
int num_weak_fields_;
// table_driven_ indicates the generated message uses table-driven parsing.
@@ -222,8 +214,9 @@ class MessageGenerator {
std::unique_ptr<MessageLayoutHelper> message_layout_helper_;
- SCCAnalyzer* scc_analyzer_;
- string scc_name_;
+ MessageSCCAnalyzer* scc_analyzer_;
+
+ std::map<std::string, std::string> variables_;
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
@@ -232,6 +225,6 @@ class MessageGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
index c1e15c52..afb27273 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -101,9 +101,8 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options,
- SCCAnalyzer* scc_analyzer)
- : FieldGenerator(options),
- descriptor_(descriptor),
+ MessageSCCAnalyzer* scc_analyzer)
+ : FieldGenerator(descriptor, options),
implicit_weak_field_(
IsImplicitWeakField(descriptor, options, scc_analyzer)) {
SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_);
@@ -113,364 +112,388 @@ MessageFieldGenerator::~MessageFieldGenerator() {}
void MessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (implicit_weak_field_) {
- printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n");
+ format("::$proto_ns$::MessageLite* $name$_;\n");
} else {
- printer->Print(variables_, "$type$* $name$_;\n");
+ format("$type$* $name$_;\n");
}
}
void MessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- 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_,
- "private:\n"
- "const ::google::protobuf::MessageLite& _internal_$name$() const;\n"
- "::google::protobuf::MessageLite* _internal_mutable_$name$();\n"
- "public:\n");
- } else {
- // This inline accessor directly returns member field and is used in
- // Serialize such that AFDO profile correctly captures access information to
- // message fields under serialize.
- printer->Print(variables_,
- "private:\n"
- "const $type$& _internal_$name$() const;\n"
- "public:\n");
- }
- 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_);
- printer->Print(variables_,
- "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
- printer->Print(variables_,
- "$deprecated_attr$void ${$set_allocated_$name$$}$"
- "($type$* $name$);\n");
- printer->Annotate("{", "}", descriptor_);
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$const $type$& ${1$$name$$}$() const;\n"
+ "$deprecated_attr$$type$* ${1$$release_name$$}$();\n"
+ "$deprecated_attr$$type$* ${1$mutable_$name$$}$();\n"
+ "$deprecated_attr$void ${1$set_allocated_$name$$}$"
+ "($type$* $name$);\n",
+ descriptor_);
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "$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_);
+ format(
+ "$deprecated_attr$void "
+ "${1$unsafe_arena_set_allocated_$name$$}$(\n"
+ " $type$* $name$);\n"
+ "$deprecated_attr$$type$* ${1$unsafe_arena_release_$name$$}$();\n",
+ descriptor_);
}
}
void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {
- if (implicit_weak_field_) {
- printer->Print(variables_,
- "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 "
- "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n"
- " }\n"
- "}\n");
- }
+ Formatter format(printer, variables_);
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"
+ format(
+ "void $classname$::unsafe_arena_set_allocated_$name$(\n"
+ " $type$* $name$) {\n"
+ // If we're not on an arena, free whatever we were holding before.
+ // (If we are on arena, we can just forget the earlier pointer.)
+ " if (GetArenaNoVirtual() == NULL) {\n"
+ " delete $name$_;\n"
" }\n"
- " return $name$_;\n"
- "}\n");
- }
-
- printer->Print(variables_,
- "void $classname$::unsafe_arena_set_allocated_$name$(\n"
- " $type$* $name$) {\n"
- // If we're not on an arena, free whatever we were holding before.
- // (If we are on arena, we can just forget the earlier pointer.)
- " if (GetArenaNoVirtual() == NULL) {\n"
- " delete $name$_;\n"
- " }\n"
- " $name$_ = $name$;\n"
- " if ($name$) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " // @@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"
+ " $name$_ = $name$;\n"
+ " if ($name$) {\n"
+ " $set_hasbit$\n"
+ " } else {\n"
+ " $clear_hasbit$\n"
" }\n"
- " return $name$_;\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated"
+ ":$full_name$)\n"
"}\n");
}
}
void MessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- if (!implicit_weak_field_) {
- printer->Print(variables_,
- "inline const $type$& $classname$::_internal_$name$() const {\n"
- " return *$field_member$;\n"
+ Formatter format(printer, variables_);
+ format(
+ "inline const $type$& $classname$::$name$() const {\n"
+ " const $type$* p = $casted_member$;\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return p != NULL ? *p : *reinterpret_cast<const $type$*>(\n"
+ " &$type_default_instance$);\n"
"}\n");
- }
- printer->Print(variables_,
- "inline const $type$& $classname$::$name$() const {\n"
- " const $type$* p = $casted_member$;\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\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"
- "$type_reference_function$"
- " $clear_hasbit$\n"
- " $type$* temp = $casted_member$;\n");
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- " if (GetArenaNoVirtual() != NULL) {\n"
- " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n"
- " }\n");
- }
- printer->Print(variables_,
- " $name$_ = NULL;\n"
- " return temp;\n"
- "}\n");
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
- " // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ format(
+ "inline $type$* $classname$::$release_name$() {\n"
+ " // @@protoc_insertion_point(field_release:$full_name$)\n"
"$type_reference_function$"
" $clear_hasbit$\n"
- " $type$* temp = $casted_member$;\n"
+ " $type$* temp = $casted_member$;\n");
+ if (SupportsArenas(descriptor_)) {
+ format(
+ " if (GetArenaNoVirtual() != NULL) {\n"
+ " temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n"
+ " }\n");
+ }
+ format(
" $name$_ = NULL;\n"
" return temp;\n"
"}\n");
+
+ if (SupportsArenas(descriptor_)) {
+ format(
+ "inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
+ " // "
+ "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ "$type_reference_function$"
+ " $clear_hasbit$\n"
+ " $type$* temp = $casted_member$;\n"
+ " $name$_ = NULL;\n"
+ " return temp;\n"
+ "}\n");
}
- printer->Print(variables_,
- "inline $type$* $classname$::mutable_$name$() {\n"
- " $set_hasbit$\n"
- " if ($name$_ == NULL) {\n"
- " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n");
+ format(
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " $set_hasbit$\n"
+ " if ($name$_ == NULL) {\n"
+ " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n");
if (implicit_weak_field_) {
- printer->Print(variables_,
- " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n");
+ format(" $name$_ = reinterpret_cast<::$proto_ns$::MessageLite*>(p);\n");
} else {
- printer->Print(variables_,
- " $name$_ = p;\n");
+ format(" $name$_ = p;\n");
}
- printer->Print(variables_,
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $casted_member$;\n"
- "}\n");
+ format(
+ " }\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");
+ format(
+ "inline void $classname$::set_allocated_$name$($type$* $name$) {\n"
+ " ::$proto_ns$::Arena* message_arena = GetArenaNoVirtual();\n");
+ format(" if (message_arena == NULL) {\n");
if (IsCrossFileMessage(descriptor_)) {
- printer->Print(variables_,
- " delete reinterpret_cast< ::google::protobuf::MessageLite*>($name$_);\n");
+ format(
+ " delete reinterpret_cast< ::$proto_ns$::MessageLite*>($name$_);\n");
} else {
- printer->Print(variables_,
- " delete $name$_;\n");
+ format(" delete $name$_;\n");
}
- printer->Print(variables_,
- " }\n"
- " if ($name$) {\n");
+ format(
+ " }\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");
+ format(
+ " ::$proto_ns$::Arena* submessage_arena =\n"
+ " "
+ "reinterpret_cast<::$proto_ns$::MessageLite*>($name$)->GetArena();\n");
} else if (!SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables_,
- " ::google::protobuf::Arena* submessage_arena = NULL;\n");
+ format(" ::$proto_ns$::Arena* submessage_arena = NULL;\n");
} else {
- printer->Print(variables_,
- " ::google::protobuf::Arena* submessage_arena =\n"
- " ::google::protobuf::Arena::GetArena($name$);\n");
+ format(
+ " ::$proto_ns$::Arena* submessage_arena =\n"
+ " ::$proto_ns$::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");
+ format(
+ " if (message_arena != submessage_arena) {\n"
+ " $name$ = ::$proto_ns$::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");
+ format(" $name$_ = reinterpret_cast<MessageLite*>($name$);\n");
+ } else {
+ format(" $name$_ = $name$;\n");
+ }
+ format(
+ " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
+ "}\n");
+}
+
+void MessageFieldGenerator::
+GenerateInternalAccessorDeclarations(io::Printer* printer) const {
+ Formatter format(printer, variables_);
+ if (implicit_weak_field_) {
+ format(
+ "static const ::$proto_ns$::MessageLite& $name$("
+ "const $classname$* msg);\n"
+ "static ::$proto_ns$::MessageLite* mutable_$name$("
+ "$classname$* msg);\n");
+ } else {
+ format("static const $type$& $name$(const $classname$* msg);\n");
+ }
+}
+
+void MessageFieldGenerator::
+GenerateInternalAccessorDefinitions(io::Printer* printer) const {
+ // In theory, these accessors could be inline in HasBitSetters. However, in
+ // practice, the linker is then not able to throw them out making implicit
+ // weak dependencies not work at all.
+ Formatter format(printer, variables_);
+ 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.
+ format(
+ "const ::$proto_ns$::MessageLite& $classname$::HasBitSetters::$name$(\n"
+ " const $classname$* msg) {\n"
+ " if (msg->$name$_ != NULL) {\n"
+ " return *msg->$name$_;\n"
+ " } else if (&$type_default_instance$ != NULL) {\n"
+ " return *reinterpret_cast<const ::$proto_ns$::MessageLite*>(\n"
+ " &$type_default_instance$);\n"
+ " } else {\n"
+ " return "
+ "*::$proto_ns$::internal::ImplicitWeakMessage::default_instance();\n"
+ " }\n"
+ "}\n");
+ if (SupportsArenas(descriptor_)) {
+ format(
+ "::$proto_ns$::MessageLite*\n"
+ "$classname$::HasBitSetters::mutable_$name$($classname$* msg) {\n");
+ if (HasFieldPresence(descriptor_->file())) {
+ format(" msg->$set_hasbit$\n");
+ }
+ format(
+ " if (msg->$name$_ == NULL) {\n"
+ " if (&$type_default_instance$ == NULL) {\n"
+ " msg->$name$_ = ::$proto_ns$::Arena::CreateMessage<\n"
+ " ::$proto_ns$::internal::ImplicitWeakMessage>(\n"
+ " msg->GetArenaNoVirtual());\n"
+ " } else {\n"
+ " msg->$name$_ = reinterpret_cast<const "
+ "::$proto_ns$::MessageLite*>(\n"
+ " &$type_default_instance$)->New("
+ "msg->GetArenaNoVirtual());\n"
+ " }\n"
+ " }\n"
+ " return msg->$name$_;\n"
+ "}\n");
+ } else {
+ format(
+ "::$proto_ns$::MessageLite*\n"
+ "$classname$::HasBitSetters::mutable_$name$($classname$* msg) {\n");
+ if (HasFieldPresence(descriptor_->file())) {
+ format(" msg->$set_hasbit$\n");
+ }
+ format(
+ " if (msg->$name$_ == NULL) {\n"
+ " if (&$type_default_instance$ == NULL) {\n"
+ " msg->$name$_ = "
+ "new ::$proto_ns$::internal::ImplicitWeakMessage;\n"
+ " } else {\n"
+ " msg->$name$_ = "
+ "reinterpret_cast<const ::$proto_ns$::MessageLite*>(\n"
+ " &$type_default_instance$)->New();\n"
+ " }\n"
+ " }\n"
+ " return msg->$name$_;\n"
+ "}\n");
+ }
} else {
- printer->Print(variables_,
- " $name$_ = $name$;\n");
+ // This inline accessor directly returns member field and is used in
+ // Serialize such that AFDO profile correctly captures access information to
+ // message fields under serialize.
+ format(
+ "const $type$&\n"
+ "$classname$::HasBitSetters::$name$(const $classname$* msg) {\n"
+ " return *msg->$field_member$;\n"
+ "}\n");
}
- printer->Print(variables_,
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
- "}\n");
}
void MessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
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 (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n"
- " delete $name$_;\n"
- "}\n"
- "$name$_ = NULL;\n");
+ format(
+ "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n"
+ " delete $name$_;\n"
+ "}\n"
+ "$name$_ = NULL;\n");
} else {
- printer->Print(variables_,
- "if ($name$_ != NULL) $name$_->Clear();\n");
+ format("if ($name$_ != NULL) $name$_->Clear();\n");
}
}
void MessageFieldGenerator::
GenerateMessageClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
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 (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n"
- " delete $name$_;\n"
- "}\n"
- "$name$_ = NULL;\n");
+ format(
+ "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n"
+ " delete $name$_;\n"
+ "}\n"
+ "$name$_ = NULL;\n");
} else {
- printer->Print(variables_,
- "GOOGLE_DCHECK($name$_ != NULL);\n"
- "$name$_->Clear();\n");
+ format(
+ "$DCHK$($name$_ != NULL);\n"
+ "$name$_->Clear();\n");
}
}
void MessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (implicit_weak_field_) {
- printer->Print(variables_,
- "_internal_mutable_$name$()->CheckTypeAndMergeFrom(\n"
- " from._internal_$name$());\n");
+ format(
+ "HasBitSetters::mutable_$name$(this)->CheckTypeAndMergeFrom(\n"
+ " HasBitSetters::$name$(&from));\n");
} else {
- printer->Print(variables_,
- "mutable_$name$()->$type$::MergeFrom(from.$name$());\n");
+ format("mutable_$name$()->$type$::MergeFrom(from.$name$());\n");
}
}
void MessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "swap($name$_, other->$name$_);\n");
+ Formatter format(printer, variables_);
+ format("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()) ");
- printer->Print(variables_, "delete $name$_;\n");
+ Formatter format(printer, variables_);
+ if (options_.opensource_runtime) {
+ // 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.
+ format("if (this != internal_default_instance()) ");
+ }
+ format("delete $name$_;\n");
}
void MessageFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = NULL;\n");
+ Formatter format(printer, variables_);
+ format("$name$_ = NULL;\n");
}
void MessageFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (from.has_$name$()) {\n"
- " $name$_ = new $type$(*from.$name$_);\n"
- "} else {\n"
- " $name$_ = NULL;\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "if (from.has_$name$()) {\n"
+ " $name$_ = new $type$(*from.$name$_);\n"
+ "} else {\n"
+ " $name$_ = NULL;\n"
+ "}\n");
}
void MessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (implicit_weak_field_) {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n"
- " input, _internal_mutable_$name$()));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessage(\n"
+ " input, HasBitSetters::mutable_$name$(this)));\n");
} else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n"
- " input, mutable_$name$()));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::ReadMessage(\n"
+ " input, mutable_$name$()));\n");
} else {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::ReadGroup(\n"
- " $number$, input, mutable_$name$()));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::ReadGroup(\n"
+ " $number$, input, mutable_$name$()));\n");
}
}
void MessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n"
- " $number$, this->_internal_$name$(), output);\n");
+ Formatter format(printer, variables_);
+ format(
+ "::$proto_ns$::internal::WireFormatLite::Write$stream_writer$(\n"
+ " $number$, HasBitSetters::$name$(this), output);\n");
}
void MessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- printer->Print(variables_,
- "target = ::google::protobuf::internal::WireFormatLite::\n"
- " InternalWrite$declared_type$ToArray(\n"
- " $number$, this->_internal_$name$(), deterministic, target);\n");
+ Formatter format(printer, variables_);
+ format(
+ "target = ::$proto_ns$::internal::WireFormatLite::\n"
+ " InternalWrite$declared_type$ToArray(\n"
+ " $number$, HasBitSetters::$name$(this), deterministic, target);\n");
}
void MessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " *$field_member$);\n");
+ Formatter format(printer, variables_);
+ format(
+ "total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n"
+ " *$field_member$);\n");
}
// ===================================================================
MessageOneofFieldGenerator::MessageOneofFieldGenerator(
const FieldDescriptor* descriptor, const Options& options,
- SCCAnalyzer* scc_analyzer)
+ MessageSCCAnalyzer* scc_analyzer)
: MessageFieldGenerator(descriptor, options, scc_analyzer) {
SetCommonOneofFieldVariables(descriptor, &variables_);
}
@@ -479,126 +502,122 @@ MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {}
void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions(
io::Printer* printer) const {
- printer->Print(variables_,
- "void $classname$::set_allocated_$name$($type$* $name$) {\n"
- " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n"
- " clear_$oneof_name$();\n"
- " if ($name$) {\n");
+ Formatter format(printer, variables_);
+ format(
+ "void $classname$::set_allocated_$name$($type$* $name$) {\n"
+ " ::$proto_ns$::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");
+ format(
+ " ::$proto_ns$::Arena* submessage_arena =\n"
+ " "
+ "reinterpret_cast<::$proto_ns$::MessageLite*>($name$)->GetArena();\n");
} else if (!SupportsArenas(descriptor_->message_type())) {
- printer->Print(variables_,
- " ::google::protobuf::Arena* submessage_arena = NULL;\n");
+ format(" ::$proto_ns$::Arena* submessage_arena = NULL;\n");
} else {
- printer->Print(variables_,
- " ::google::protobuf::Arena* submessage_arena =\n"
- " ::google::protobuf::Arena::GetArena($name$);\n");
+ format(
+ " ::$proto_ns$::Arena* submessage_arena =\n"
+ " ::$proto_ns$::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_has_$name$();\n"
- " $field_member$ = $name$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
- "}\n");
+ format(
+ " if (message_arena != submessage_arena) {\n"
+ " $name$ = ::$proto_ns$::internal::GetOwnedMessage(\n"
+ " message_arena, $name$, submessage_arena);\n"
+ " }\n"
+ " set_has_$name$();\n"
+ " $field_member$ = $name$;\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
+ "}\n");
}
void MessageOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- if (!implicit_weak_field_) {
- printer->Print(variables_,
- "inline const $type$& $classname$::_internal_$name$() const {\n"
- " return *$field_member$;\n"
- "}\n");
- }
- printer->Print(variables_,
- "inline $type$* $classname$::$release_name$() {\n"
- " // @@protoc_insertion_point(field_release:$full_name$)\n"
- " if (has_$name$()) {\n"
- " clear_has_$oneof_name$();\n"
- " $type$* temp = $field_member$;\n");
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- " if (GetArenaNoVirtual() != NULL) {\n"
- " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n"
- " }\n");
- }
- printer->Print(variables_,
- " $field_member$ = NULL;\n"
- " return temp;\n"
- " } else {\n"
- " return NULL;\n"
- " }\n"
- "}\n");
-
- printer->Print(variables_,
- "inline const $type$& $classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return has_$name$()\n"
- " ? *$field_member$\n"
- " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n"
- "}\n");
-
- if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "inline $type$* $classname$::unsafe_arena_release_$name$() {\n"
- " // @@protoc_insertion_point(field_unsafe_arena_release"
- ":$full_name$)\n"
+ Formatter format(printer, variables_);
+ format(
+ "inline $type$* $classname$::$release_name$() {\n"
+ " // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
- " $type$* temp = $field_member$;\n"
+ " $type$* temp = $field_member$;\n");
+ if (SupportsArenas(descriptor_)) {
+ format(
+ " if (GetArenaNoVirtual() != NULL) {\n"
+ " temp = ::$proto_ns$::internal::DuplicateIfNonNull(temp);\n"
+ " }\n");
+ }
+ format(
" $field_member$ = 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"
- " $field_member$ = $name$;\n"
- " }\n"
- " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
- "$full_name$)\n"
"}\n");
+
+ format(
+ "inline const $type$& $classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return has_$name$()\n"
+ " ? *$field_member$\n"
+ " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n"
+ "}\n");
+
+ if (SupportsArenas(descriptor_)) {
+ format(
+ "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 = $field_member$;\n"
+ " $field_member$ = 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"
+ " $field_member$ = $name$;\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
+ "$full_name$)\n"
+ "}\n");
}
- printer->Print(variables_,
- "inline $type$* $classname$::mutable_$name$() {\n"
- " if (!has_$name$()) {\n"
- " clear_$oneof_name$();\n"
- " set_has_$name$();\n"
- " $field_member$ = CreateMaybeMessage< $type$ >(\n"
- " GetArenaNoVirtual());\n"
- " }\n"
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- " return $field_member$;\n"
- "}\n");
+ format(
+ "inline $type$* $classname$::mutable_$name$() {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$ = CreateMaybeMessage< $type$ >(\n"
+ " GetArenaNoVirtual());\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ " return $field_member$;\n"
+ "}\n");
}
void MessageOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "if (GetArenaNoVirtual() == NULL) {\n"
- " delete $field_member$;\n"
- "}\n");
+ format(
+ "if (GetArenaNoVirtual() == NULL) {\n"
+ " delete $field_member$;\n"
+ "}\n");
} else {
- printer->Print(variables_,
- "delete $field_member$;\n");
+ format("delete $field_member$;\n");
}
}
@@ -628,9 +647,8 @@ GenerateConstructorCode(io::Printer* printer) const {
RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(
const FieldDescriptor* descriptor, const Options& options,
- SCCAnalyzer* scc_analyzer)
- : FieldGenerator(options),
- descriptor_(descriptor),
+ MessageSCCAnalyzer* scc_analyzer)
+ : FieldGenerator(descriptor, options),
implicit_weak_field_(
IsImplicitWeakField(descriptor, options, scc_analyzer)) {
SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_);
@@ -640,108 +658,101 @@ RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {}
void RepeatedMessageFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::RepeatedPtrField< $type$ > $name$_;\n");
+ Formatter format(printer, variables_);
+ format("::$proto_ns$::RepeatedPtrField< $type$ > $name$_;\n");
}
void RepeatedMessageFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- printer->Print(variables_,
- "$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n");
- printer->Annotate("{", "}", descriptor_);
- printer->Print(variables_,
- "$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n"
- " ${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
-
- printer->Print(variables_,
- "$deprecated_attr$const $type$& $name$(int index) const;\n");
- printer->Annotate("name", descriptor_);
- printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
- printer->Print(variables_,
- "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- " $name$() const;\n");
- printer->Annotate("name", descriptor_);
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$$type$* ${1$mutable_$name$$}$(int index);\n"
+ "$deprecated_attr$::$proto_ns$::RepeatedPtrField< $type$ >*\n"
+ " ${1$mutable_$name$$}$();\n"
+ "$deprecated_attr$const $type$& ${1$$name$$}$(int index) const;\n"
+ "$deprecated_attr$$type$* ${1$add_$name$$}$();\n"
+ "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField< $type$ >&\n"
+ " ${1$$name$$}$() const;\n",
+ descriptor_);
}
void RepeatedMessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
- printer->Print(variables_,
- "inline $type$* $classname$::mutable_$name$(int index) {\n"
- // TODO(dlj): move insertion points
- " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
- "$type_reference_function$"
- " return $name$_.Mutable(index);\n"
- "}\n"
- "inline ::google::protobuf::RepeatedPtrField< $type$ >*\n"
- "$classname$::mutable_$name$() {\n"
- " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- "$type_reference_function$"
- " return &$name$_;\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "inline $type$* $classname$::mutable_$name$(int index) {\n"
+ // TODO(dlj): move insertion points
+ " // @@protoc_insertion_point(field_mutable:$full_name$)\n"
+ "$type_reference_function$"
+ " return $name$_.Mutable(index);\n"
+ "}\n"
+ "inline ::$proto_ns$::RepeatedPtrField< $type$ >*\n"
+ "$classname$::mutable_$name$() {\n"
+ " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
+ "$type_reference_function$"
+ " return &$name$_;\n"
+ "}\n");
if (options_.safe_boundary_check) {
- printer->Print(variables_,
- "inline const $type$& $classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_.InternalCheckedGet(index,\n"
- " *reinterpret_cast<const $type$*>(&$type_default_instance$));\n"
- "}\n");
+ format(
+ "inline const $type$& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_.InternalCheckedGet(index,\n"
+ " *reinterpret_cast<const $type$*>(&$type_default_instance$));\n"
+ "}\n");
} else {
- printer->Print(variables_,
- "inline const $type$& $classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- "$type_reference_function$"
- " return $name$_.Get(index);\n"
- "}\n");
+ format(
+ "inline const $type$& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ "$type_reference_function$"
+ " return $name$_.Get(index);\n"
+ "}\n");
}
- printer->Print(variables_,
- "inline $type$* $classname$::add_$name$() {\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\n"
- " return $name$_.Add();\n"
- "}\n");
+ format(
+ "inline $type$* $classname$::add_$name$() {\n"
+ " // @@protoc_insertion_point(field_add:$full_name$)\n"
+ " return $name$_.Add();\n"
+ "}\n");
- printer->Print(variables_,
- "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n"
- "$classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_list:$full_name$)\n"
- "$type_reference_function$"
- " return $name$_;\n"
- "}\n");
+ format(
+ "inline const ::$proto_ns$::RepeatedPtrField< $type$ >&\n"
+ "$classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_list:$full_name$)\n"
+ "$type_reference_function$"
+ " return $name$_;\n"
+ "}\n");
}
void RepeatedMessageFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (implicit_weak_field_) {
- printer->Print(
- variables_,
+ format(
"CastToBase(&$name$_)->Clear<"
- "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>();\n");
+ "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>();\n");
} else {
- printer->Print(variables_, "$name$_.Clear();\n");
+ format("$name$_.Clear();\n");
}
}
void RepeatedMessageFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (implicit_weak_field_) {
- printer->Print(
- variables_,
+ format(
"CastToBase(&$name$_)->MergeFrom<"
- "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase("
+ "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase("
"from.$name$_));\n");
} else {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ format("$name$_.MergeFrom(from.$name$_);\n");
}
}
void RepeatedMessageFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(
- variables_,
- "CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n");
+ Formatter format(printer, variables_);
+ format("CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n");
}
void RepeatedMessageFieldGenerator::
@@ -751,83 +762,85 @@ GenerateConstructorCode(io::Printer* printer) const {
void RepeatedMessageFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) {
if (implicit_weak_field_) {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n"
- " reinterpret_cast<const ::google::protobuf::MessageLite*>(\n"
- " &$type_default_instance$))));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::"
+ "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n"
+ " reinterpret_cast<const ::$proto_ns$::MessageLite*>(\n"
+ " &$type_default_instance$))));\n");
} else {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadMessage(\n"
- " input, add_$name$()));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::"
+ "ReadMessage(\n"
+ " input, add_$name$()));\n");
}
} else {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::"
- "ReadGroup($number$, input, add_$name$()));\n");
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::"
+ "ReadGroup($number$, input, add_$name$()));\n");
}
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- printer->Print(variables_,
- "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$,\n");
+ Formatter format(printer, variables_);
+ format(
+ "for (unsigned int i = 0,\n"
+ " n = static_cast<unsigned int>(this->$name$_size()); i < n; i++) {\n"
+ " ::$proto_ns$::internal::WireFormatLite::Write$stream_writer$(\n"
+ " $number$,\n");
if (implicit_weak_field_) {
- printer->Print(
- variables_,
+ format(
" CastToBase($name$_).Get<"
- "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>("
+ "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>("
"static_cast<int>(i)),\n");
} else {
- printer->Print(variables_,
- " this->$name$(static_cast<int>(i)),\n");
+ format(" this->$name$(static_cast<int>(i)),\n");
}
- printer->Print(variables_,
- " output);\n"
- "}\n");
+ format(
+ " output);\n"
+ "}\n");
}
void RepeatedMessageFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- printer->Print(variables_,
- "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$ToArray(\n"
- " $number$, this->$name$(static_cast<int>(i)), deterministic, target);\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "for (unsigned int i = 0,\n"
+ " n = static_cast<unsigned int>(this->$name$_size()); i < n; i++) {\n"
+ " target = ::$proto_ns$::internal::WireFormatLite::\n"
+ " InternalWrite$declared_type$ToArray(\n"
+ " $number$, this->$name$(static_cast<int>(i)), deterministic, "
+ "target);\n"
+ "}\n");
}
void RepeatedMessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "{\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$Size(\n");
+ Formatter format(printer, variables_);
+ format(
+ "{\n"
+ " unsigned int count = static_cast<unsigned "
+ "int>(this->$name$_size());\n");
+ format.Indent();
+ format(
+ "total_size += $tag_size$UL * count;\n"
+ "for (unsigned int i = 0; i < count; i++) {\n"
+ " total_size +=\n"
+ " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n");
if (implicit_weak_field_) {
- printer->Print(
- variables_,
+ format(
" CastToBase($name$_).Get<"
- "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>("
+ "::$proto_ns$::internal::ImplicitWeakTypeHandler<$type$>>("
"static_cast<int>(i)));\n");
} else {
- printer->Print(variables_,
- " this->$name$(static_cast<int>(i)));\n");
+ format(" this->$name$(static_cast<int>(i)));\n");
}
- printer->Print(variables_, "}\n");
- printer->Outdent();
- printer->Print("}\n");
+ format("}\n");
+ format.Outdent();
+ format("}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/cpp_message_field.h
index 6879539c..eed8e4f5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.h
@@ -48,7 +48,8 @@ namespace cpp {
class MessageFieldGenerator : public FieldGenerator {
public:
MessageFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options, SCCAnalyzer* scc_analyzer);
+ const Options& options,
+ MessageSCCAnalyzer* scc_analyzer);
~MessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
@@ -56,6 +57,8 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
+ void GenerateInternalAccessorDeclarations(io::Printer* printer) const;
+ void GenerateInternalAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMessageClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
@@ -69,9 +72,7 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
protected:
- const FieldDescriptor* descriptor_;
const bool implicit_weak_field_;
- std::map<string, string> variables_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator);
@@ -80,7 +81,8 @@ class MessageFieldGenerator : public FieldGenerator {
class MessageOneofFieldGenerator : public MessageFieldGenerator {
public:
MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
- const Options& options, SCCAnalyzer* scc_analyzer);
+ const Options& options,
+ MessageSCCAnalyzer* scc_analyzer);
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
@@ -103,7 +105,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
public:
RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options,
- SCCAnalyzer* scc_analyzer);
+ MessageSCCAnalyzer* scc_analyzer);
~RepeatedMessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
@@ -121,9 +123,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
- const FieldDescriptor* descriptor_;
const bool implicit_weak_field_;
- std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
};
@@ -131,6 +131,6 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
index d502a6f0..67eeff0a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h
@@ -56,6 +56,6 @@ class MessageLayoutHelper {
} // 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_options.h b/src/google/protobuf/compiler/cpp/cpp_options.h
index f09885be..84c18622 100644
--- a/src/google/protobuf/compiler/cpp/cpp_options.h
+++ b/src/google/protobuf/compiler/cpp/cpp_options.h
@@ -35,7 +35,6 @@
#include <string>
-#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace compiler {
@@ -45,39 +44,28 @@ namespace cpp {
// Generator options (see generator.cc for a description of each):
struct Options {
- Options()
- : safe_boundary_check(false),
- proto_h(false),
- transitive_pb_h(true),
- annotate_headers(false),
- enforce_lite(false),
- table_driven_parsing(false),
- table_driven_serialization(false),
- lite_implicit_weak_fields(false),
- bootstrap(false),
- num_cc_files(0),
- access_info_map(NULL) {}
-
- string dllexport_decl;
- bool safe_boundary_check;
- bool proto_h;
- bool transitive_pb_h;
- bool annotate_headers;
- bool enforce_lite;
- bool table_driven_parsing;
- bool table_driven_serialization;
- bool lite_implicit_weak_fields;
- bool bootstrap;
- int num_cc_files;
- string annotation_pragma_name;
- string annotation_guard_name;
- const AccessInfoMap* access_info_map;
+ std::string dllexport_decl;
+ bool safe_boundary_check = false;
+ bool proto_h = false;
+ bool transitive_pb_h = true;
+ bool annotate_headers = false;
+ bool enforce_lite = false;
+ bool table_driven_parsing = false;
+ bool table_driven_serialization = false;
+ bool lite_implicit_weak_fields = false;
+ bool bootstrap = false;
+ bool opensource_runtime = false;
+ bool opensource_include_paths = false;
+ int num_cc_files = 0;
+ std::string annotation_pragma_name;
+ std::string annotation_guard_name;
+ const AccessInfoMap* access_info_map = nullptr;
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
+} // namespace google
-} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
index e9303865..2f78bda5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc
@@ -106,6 +106,8 @@ class FieldGroup {
// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and
// calls ArenaStringPtr::Destroy on each.
//
+// LAZY_MESSAGE is grouped next, as it interferes with the ability to memset
+// non-repeated fields otherwise.
//
// 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
@@ -122,6 +124,9 @@ void PaddingOptimizer::OptimizeLayout(
enum Family {
REPEATED = 0,
STRING = 1,
+ // Laying out LAZY_MESSAGE before MESSAGE allows a single memset to zero
+ // MESSAGE and ZERO_INITIALIZABLE fields together.
+ LAZY_MESSAGE = 2,
MESSAGE = 3,
ZERO_INITIALIZABLE = 4,
OTHER = 5,
@@ -142,7 +147,9 @@ void PaddingOptimizer::OptimizeLayout(
f = STRING;
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
f = MESSAGE;
-
+ if (IsLazy(field, options)) {
+ f = LAZY_MESSAGE;
+ }
} else if (CanInitializeByZeroing(field)) {
f = ZERO_INITIALIZABLE;
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
index 42a3b5cd..2382081b 100644
--- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
+++ b/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h
@@ -59,6 +59,6 @@ class PaddingOptimizer : public MessageLayoutHelper {
} // 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 ff6ba0f8..4f8a23ed 100644
--- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc
@@ -219,7 +219,7 @@ TEST(CppPluginTest, PluginTest) {
"}\n",
true));
- google::protobuf::compiler::CommandLineInterface cli;
+ CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
CppGenerator cpp_generator;
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
index 701f9d2d..2f6a0504 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
@@ -83,16 +83,16 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
- (*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type());
- (*variables)["default"] = DefaultValue(descriptor);
- (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
+ (*variables)["type"] = PrimitiveTypeName(options, descriptor->cpp_type());
+ (*variables)["default"] = DefaultValue(options, descriptor);
+ (*variables)["tag"] =
+ SimpleItoa(internal::WireFormat::MakeTag(descriptor));
int fixed_size = FixedSize(descriptor->type());
if (fixed_size != -1) {
(*variables)["fixed_size"] = SimpleItoa(fixed_size);
}
- (*variables)["wire_format_field_type"] =
- "::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name(
- static_cast<FieldDescriptorProto_Type>(descriptor->type()));
+ (*variables)["wire_format_field_type"] = FieldDescriptorProto_Type_Name(
+ static_cast<FieldDescriptorProto_Type>(descriptor->type()));
(*variables)["full_name"] = descriptor->full_name();
}
@@ -102,7 +102,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
PrimitiveFieldGenerator::PrimitiveFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetPrimitiveVariables(descriptor, &variables_, options);
}
@@ -110,91 +110,103 @@ PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}
void PrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_, "$type$ $name$_;\n");
+ Formatter format(printer, variables_);
+ format("$type$ $name$_;\n");
}
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$void ${$set_$name$$}$($type$ value);\n");
- printer->Annotate("{", "}", descriptor_);
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$$type$ ${1$$name$$}$() const;\n"
+ "$deprecated_attr$void ${1$set_$name$$}$($type$ value);\n",
+ descriptor_);
}
void PrimitiveFieldGenerator::
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"
- " $set_hasbit$\n"
- " $name$_ = value;\n"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "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"
+ " $set_hasbit$\n"
+ " $name$_ = value;\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n");
}
void PrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = $default$;\n");
+ Formatter format(printer, variables_);
+ format("$name$_ = $default$;\n");
}
void PrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "set_$name$(from.$name$());\n");
+ Formatter format(printer, variables_);
+ format("set_$name$(from.$name$());\n");
}
void PrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "swap($name$_, other->$name$_);\n");
+ Formatter format(printer, variables_);
+ format("swap($name$_, other->$name$_);\n");
}
void PrimitiveFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = $default$;\n");
+ Formatter format(printer, variables_);
+ format("$name$_ = $default$;\n");
}
void PrimitiveFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = from.$name$_;\n");
+ Formatter format(printer, variables_);
+ format("$name$_ = from.$name$_;\n");
}
void PrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "$set_hasbit$\n"
- "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
- " $type$, $wire_format_field_type$>(\n"
- " input, &$name$_)));\n");
+ Formatter format(printer, variables_);
+ format(
+ "$set_hasbit_io$\n"
+ "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
+ " $type$, "
+ "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n"
+ " input, &$name$_)));\n");
}
void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::internal::WireFormatLite::Write$declared_type$("
+ Formatter format(printer, variables_);
+ format(
+ "::$proto_ns$::internal::WireFormatLite::Write$declared_type$("
"$number$, this->$name$(), output);\n");
}
void PrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- printer->Print(variables_,
- "target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray("
+ Formatter format(printer, variables_);
+ format(
+ "target = "
+ "::$proto_ns$::internal::WireFormatLite::Write$declared_type$ToArray("
"$number$, this->$name$(), target);\n");
}
void PrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
+ Formatter format(printer, variables_);
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
- printer->Print(variables_,
- "total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " this->$name$());\n");
+ format(
+ "total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n"
+ " this->$name$());\n");
} else {
- printer->Print(variables_,
- "total_size += $tag_size$ + $fixed_size$;\n");
+ format("total_size += $tag_size$ + $fixed_size$;\n");
}
}
@@ -211,27 +223,29 @@ PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
void PrimitiveOneofFieldGenerator::
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 $field_member$;\n"
- " }\n"
- " return $default$;\n"
- "}\n"
- "inline void $classname$::set_$name$($type$ value) {\n"
- " if (!has_$name$()) {\n"
- " clear_$oneof_name$();\n"
- " set_has_$name$();\n"
- " }\n"
- " $field_member$ = value;\n"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "inline $type$ $classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " if (has_$name$()) {\n"
+ " return $field_member$;\n"
+ " }\n"
+ " return $default$;\n"
+ "}\n"
+ "inline void $classname$::set_$name$($type$ value) {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " }\n"
+ " $field_member$ = value;\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n");
}
void PrimitiveOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$field_member$ = $default$;\n");
+ Formatter format(printer, variables_);
+ format("$field_member$ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
@@ -241,25 +255,27 @@ GenerateSwappingCode(io::Printer* printer) const {
void PrimitiveOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
+ Formatter format(printer, variables_);
+ format("$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "clear_$oneof_name$();\n"
- "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
- " $type$, $wire_format_field_type$>(\n"
- " input, &$field_member$)));\n"
- "set_has_$name$();\n");
+ Formatter format(printer, variables_);
+ format(
+ "clear_$oneof_name$();\n"
+ "DO_((::$proto_ns$::internal::WireFormatLite::ReadPrimitive<\n"
+ " $type$, "
+ "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n"
+ " input, &$field_member$)));\n"
+ "set_has_$name$();\n");
}
// ===================================================================
RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetPrimitiveVariables(descriptor, &variables_, options);
if (descriptor->is_packed()) {
@@ -275,77 +291,72 @@ RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}
void RepeatedPrimitiveFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::RepeatedField< $type$ > $name$_;\n");
+ Formatter format(printer, variables_);
+ format("::$proto_ns$::RepeatedField< $type$ > $name$_;\n");
if (descriptor_->is_packed() &&
HasGeneratedMethods(descriptor_->file(), options_)) {
- printer->Print(variables_,
- "mutable int _$name$_cached_byte_size_;\n");
+ format("mutable std::atomic<int> _$name$_cached_byte_size_;\n");
}
}
void RepeatedPrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
- printer->Print(variables_,
- "$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$::google::protobuf::RepeatedField< $type$ >*\n"
- " ${$mutable_$name$$}$();\n");
- printer->Annotate("{", "}", descriptor_);
+ Formatter format(printer, variables_);
+ format(
+ "$deprecated_attr$$type$ ${1$$name$$}$(int index) const;\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, $type$ value);\n"
+ "$deprecated_attr$void ${1$add_$name$$}$($type$ value);\n"
+ "$deprecated_attr$const ::$proto_ns$::RepeatedField< $type$ >&\n"
+ " ${1$$name$$}$() const;\n"
+ "$deprecated_attr$::$proto_ns$::RepeatedField< $type$ >*\n"
+ " ${1$mutable_$name$$}$();\n",
+ descriptor_);
}
void RepeatedPrimitiveFieldGenerator::
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"
- " $name$_.Set(index, value);\n"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- "}\n"
- "inline void $classname$::add_$name$($type$ value) {\n"
- " $name$_.Add(value);\n"
- " // @@protoc_insertion_point(field_add:$full_name$)\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"
- "$classname$::mutable_$name$() {\n"
- " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- " return &$name$_;\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "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"
+ " $name$_.Set(index, value);\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ "}\n"
+ "inline void $classname$::add_$name$($type$ value) {\n"
+ " $name$_.Add(value);\n"
+ " // @@protoc_insertion_point(field_add:$full_name$)\n"
+ "}\n"
+ "inline const ::$proto_ns$::RepeatedField< $type$ >&\n"
+ "$classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_list:$full_name$)\n"
+ " return $name$_;\n"
+ "}\n"
+ "inline ::$proto_ns$::RepeatedField< $type$ >*\n"
+ "$classname$::mutable_$name$() {\n"
+ " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
+ " return &$name$_;\n"
+ "}\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Clear();\n");
+ Formatter format(printer, variables_);
+ format("$name$_.Clear();\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.InternalSwap(&other->$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
@@ -355,124 +366,135 @@ GenerateConstructorCode(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.CopyFrom(from.$name$_);\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n"
- " $type$, $wire_format_field_type$>(\n"
- " $tag_size$, $tag$u, input, this->mutable_$name$())));\n");
+ Formatter format(printer, variables_);
+ format(
+ "DO_((::$proto_ns$::internal::WireFormatLite::$repeated_reader$<\n"
+ " $type$, "
+ "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n"
+ " $tag_size$, $tag$u, input, this->mutable_$name$())));\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
- printer->Print(variables_,
- "DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n"
- " $type$, $wire_format_field_type$>(\n"
- " input, this->mutable_$name$())));\n");
+ Formatter format(printer, variables_);
+ format(
+ "DO_((::$proto_ns$::internal::WireFormatLite::$packed_reader$<\n"
+ " $type$, "
+ "::$proto_ns$::internal::WireFormatLite::$wire_format_field_type$>(\n"
+ " input, this->mutable_$name$())));\n");
}
void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
+ Formatter format(printer, variables_);
bool array_written = false;
if (descriptor_->is_packed()) {
// Write the tag and the size.
- printer->Print(variables_,
- "if (this->$name$_size() > 0) {\n"
- " ::google::protobuf::internal::WireFormatLite::WriteTag("
- "$number$, "
- "::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
- "output);\n"
- " output->WriteVarint32(static_cast< ::google::protobuf::uint32>(\n"
- " _$name$_cached_byte_size_));\n");
+ format(
+ "if (this->$name$_size() > 0) {\n"
+ " ::$proto_ns$::internal::WireFormatLite::WriteTag("
+ "$number$, "
+ "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
+ "output);\n"
+ " output->WriteVarint32(_$name$_cached_byte_size_.load(\n"
+ " std::memory_order_relaxed));\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");
+ format(
+ " "
+ "::$proto_ns$::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");
+ format("}\n");
}
if (!array_written) {
- printer->Print(variables_,
- "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
+ format("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");
+ format(
+ " "
+ "::$proto_ns$::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");
+ format(
+ " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$(\n"
+ " $number$, this->$name$(i), output);\n");
}
- printer->Print("}\n");
+ format("}\n");
}
}
void RepeatedPrimitiveFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->is_packed()) {
// Write the tag and the size.
- printer->Print(variables_,
- "if (this->$name$_size() > 0) {\n"
- " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n"
- " $number$,\n"
- " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
- " target);\n"
- " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n"
- " static_cast< ::google::protobuf::int32>(\n"
- " _$name$_cached_byte_size_), target);\n"
- " target = ::google::protobuf::internal::WireFormatLite::\n"
- " Write$declared_type$NoTagToArray(this->$name$_, target);\n"
- "}\n");
+ format(
+ "if (this->$name$_size() > 0) {\n"
+ " target = ::$proto_ns$::internal::WireFormatLite::WriteTagToArray(\n"
+ " $number$,\n"
+ " "
+ "::$proto_ns$::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
+ " target);\n"
+ " target = "
+ "::$proto_ns$::io::CodedOutputStream::WriteVarint32ToArray(\n"
+ " _$name$_cached_byte_size_.load(std::memory_order_relaxed),\n"
+ " target);\n"
+ " target = ::$proto_ns$::internal::WireFormatLite::\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$_, target);\n");
+ format(
+ "target = ::$proto_ns$::internal::WireFormatLite::\n"
+ " Write$declared_type$ToArray($number$, this->$name$_, target);\n");
}
}
void RepeatedPrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_, "{\n");
- printer->Indent();
+ Formatter format(printer, variables_);
+ format("{\n");
+ format.Indent();
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
- printer->Print(variables_,
- "size_t data_size = ::google::protobuf::internal::WireFormatLite::\n"
- " $declared_type$Size(this->$name$_);\n");
+ format(
+ "size_t data_size = ::$proto_ns$::internal::WireFormatLite::\n"
+ " $declared_type$Size(this->$name$_);\n");
} else {
- printer->Print(variables_,
- "unsigned int count = static_cast<unsigned int>(this->$name$_size());\n"
- "size_t data_size = $fixed_size$UL * count;\n");
+ format(
+ "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(\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"
- "_$name$_cached_byte_size_ = cached_size;\n"
- "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
- "total_size += data_size;\n");
+ format(
+ "if (data_size > 0) {\n"
+ " total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::Int32Size(\n"
+ " static_cast<$int32$>(data_size));\n"
+ "}\n"
+ "int cached_size = ::$proto_ns$::internal::ToCachedSize(data_size);\n"
+ "_$name$_cached_byte_size_.store(cached_size,\n"
+ " std::memory_order_relaxed);\n"
+ "total_size += data_size;\n");
} else {
- printer->Print(variables_,
- "total_size += $tag_size$ *\n"
- " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
- "total_size += data_size;\n");
+ format(
+ "total_size += $tag_size$ *\n"
+ " "
+ "::$proto_ns$::internal::FromIntSize(this->$name$_size());\n"
+ "total_size += data_size;\n");
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
index d52228e9..77389aa0 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
@@ -64,10 +64,6 @@ class PrimitiveFieldGenerator : public FieldGenerator {
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
void GenerateByteSize(io::Printer* printer) const;
- protected:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator);
};
@@ -111,15 +107,12 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_service.cc b/src/google/protobuf/compiler/cpp/cpp_service.cc
index 95357d9f..677b7374 100644
--- a/src/google/protobuf/compiler/cpp/cpp_service.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_service.cc
@@ -42,151 +42,153 @@ namespace protobuf {
namespace compiler {
namespace cpp {
+namespace {
+
+void InitMethodVariables(const MethodDescriptor* method, Formatter* format) {
+ format->Set("name", method->name());
+ format->Set("input_type", QualifiedClassName(method->input_type()));
+ format->Set("output_type", QualifiedClassName(method->output_type()));
+}
+
+} // namespace
+
ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor,
+ const std::map<string, string>& vars,
const Options& options)
- : descriptor_(descriptor) {
+ : descriptor_(descriptor), vars_(vars) {
vars_["classname"] = descriptor_->name();
- vars_["file_namespace"] = FileLevelNamespace(descriptor_->file()->name());
vars_["full_name"] = descriptor_->full_name();
- if (options.dllexport_decl.empty()) {
- vars_["dllexport"] = "";
- } else {
- vars_["dllexport"] = options.dllexport_decl + " ";
- }
}
ServiceGenerator::~ServiceGenerator() {}
void ServiceGenerator::GenerateDeclarations(io::Printer* printer) {
+ Formatter format(printer, vars_);
// Forward-declare the stub type.
- printer->Print(vars_,
- "class $classname$_Stub;\n"
- "\n");
+ format(
+ "class $classname$_Stub;\n"
+ "\n");
GenerateInterface(printer);
GenerateStubDefinition(printer);
}
void ServiceGenerator::GenerateInterface(io::Printer* printer) {
- printer->Print(vars_,
- "class $dllexport$$classname$ : public ::google::protobuf::Service {\n"
- " protected:\n"
- " // This class should be treated as an abstract interface.\n"
- " inline $classname$() {};\n"
- " public:\n"
- " virtual ~$classname$();\n");
+ Formatter format(printer, vars_);
+ format(
+ "class $dllexport_decl $$classname$ : public ::$proto_ns$::Service {\n"
+ " protected:\n"
+ " // This class should be treated as an abstract interface.\n"
+ " inline $classname$() {};\n"
+ " public:\n"
+ " virtual ~$classname$();\n");
printer->Indent();
- printer->Print(vars_,
- "\n"
- "typedef $classname$_Stub Stub;\n"
- "\n"
- "static const ::google::protobuf::ServiceDescriptor* descriptor();\n"
- "\n");
+ format(
+ "\n"
+ "typedef $classname$_Stub Stub;\n"
+ "\n"
+ "static const ::$proto_ns$::ServiceDescriptor* descriptor();\n"
+ "\n");
GenerateMethodSignatures(VIRTUAL, printer);
- printer->Print(
- "\n"
- "// implements Service ----------------------------------------------\n"
- "\n"
- "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n"
- "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n"
- " ::google::protobuf::RpcController* controller,\n"
- " const ::google::protobuf::Message* request,\n"
- " ::google::protobuf::Message* response,\n"
- " ::google::protobuf::Closure* done);\n"
- "const ::google::protobuf::Message& GetRequestPrototype(\n"
- " const ::google::protobuf::MethodDescriptor* method) const;\n"
- "const ::google::protobuf::Message& GetResponsePrototype(\n"
- " const ::google::protobuf::MethodDescriptor* method) const;\n");
+ format(
+ "\n"
+ "// implements Service ----------------------------------------------\n"
+ "\n"
+ "const ::$proto_ns$::ServiceDescriptor* GetDescriptor();\n"
+ "void CallMethod(const ::$proto_ns$::MethodDescriptor* method,\n"
+ " ::$proto_ns$::RpcController* controller,\n"
+ " const ::$proto_ns$::Message* request,\n"
+ " ::$proto_ns$::Message* response,\n"
+ " ::google::protobuf::Closure* done);\n"
+ "const ::$proto_ns$::Message& GetRequestPrototype(\n"
+ " const ::$proto_ns$::MethodDescriptor* method) const;\n"
+ "const ::$proto_ns$::Message& GetResponsePrototype(\n"
+ " const ::$proto_ns$::MethodDescriptor* method) const;\n");
printer->Outdent();
- printer->Print(vars_,
- "\n"
- " private:\n"
- " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n"
- "};\n"
- "\n");
+ format(
+ "\n"
+ " private:\n"
+ " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n"
+ "};\n"
+ "\n");
}
void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) {
- printer->Print(vars_,
- "class $dllexport$$classname$_Stub : public $classname$ {\n"
- " public:\n");
+ Formatter format(printer, vars_);
+ format(
+ "class $dllexport_decl $$classname$_Stub : public $classname$ {\n"
+ " public:\n");
printer->Indent();
- printer->Print(vars_,
- "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n"
- "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n"
- " ::google::protobuf::Service::ChannelOwnership ownership);\n"
- "~$classname$_Stub();\n"
- "\n"
- "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n"
- "\n"
- "// implements $classname$ ------------------------------------------\n"
- "\n");
+ format(
+ "$classname$_Stub(::$proto_ns$::RpcChannel* channel);\n"
+ "$classname$_Stub(::$proto_ns$::RpcChannel* channel,\n"
+ " ::$proto_ns$::Service::ChannelOwnership ownership);\n"
+ "~$classname$_Stub();\n"
+ "\n"
+ "inline ::$proto_ns$::RpcChannel* channel() { return channel_; }\n"
+ "\n"
+ "// implements $classname$ ------------------------------------------\n"
+ "\n");
GenerateMethodSignatures(NON_VIRTUAL, printer);
printer->Outdent();
- printer->Print(vars_,
- " private:\n"
- " ::google::protobuf::RpcChannel* channel_;\n"
- " bool owns_channel_;\n"
- " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n"
- "};\n"
- "\n");
+ format(
+ " private:\n"
+ " ::$proto_ns$::RpcChannel* channel_;\n"
+ " bool owns_channel_;\n"
+ " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n"
+ "};\n"
+ "\n");
}
-void ServiceGenerator::GenerateMethodSignatures(
- VirtualOrNon virtual_or_non, io::Printer* printer) {
+void ServiceGenerator::GenerateMethodSignatures(VirtualOrNon virtual_or_non,
+ io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
- std::map<string, string> sub_vars;
- sub_vars["name"] = method->name();
- sub_vars["input_type"] = ClassName(method->input_type(), true);
- sub_vars["output_type"] = ClassName(method->output_type(), true);
- sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : "";
-
- printer->Print(sub_vars,
- "$virtual$void $name$(::google::protobuf::RpcController* controller,\n"
- " const $input_type$* request,\n"
- " $output_type$* response,\n"
- " ::google::protobuf::Closure* done);\n");
+ Formatter format(printer, vars_);
+ InitMethodVariables(method, &format);
+ format.Set("virtual", virtual_or_non == VIRTUAL ? "virtual " : "");
+ format(
+ "$virtual$void $name$(::$proto_ns$::RpcController* controller,\n"
+ " const $input_type$* request,\n"
+ " $output_type$* response,\n"
+ " ::google::protobuf::Closure* done);\n");
}
}
// ===================================================================
-void ServiceGenerator::GenerateDescriptorInitializer(
- io::Printer* printer, int index) {
- std::map<string, string> vars;
- vars["classname"] = descriptor_->name();
- vars["index"] = SimpleItoa(index);
-
- printer->Print(vars,
- "$classname$_descriptor_ = file->service($index$);\n");
+void ServiceGenerator::GenerateDescriptorInitializer(io::Printer* printer,
+ int index) {
+ Formatter format(printer, vars_);
+ format("$classname$_descriptor_ = file->service($1$);\n", index);
}
// ===================================================================
void ServiceGenerator::GenerateImplementation(io::Printer* printer) {
- vars_["index"] = SimpleItoa(index_in_metadata_);
- printer->Print(
- vars_,
+ Formatter format(printer, vars_);
+ format(
"$classname$::~$classname$() {}\n"
"\n"
- "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n"
- " $file_namespace$::protobuf_AssignDescriptorsOnce();\n"
- " return $file_namespace$::file_level_service_descriptors[$index$];\n"
+ "const ::$proto_ns$::ServiceDescriptor* $classname$::descriptor() {\n"
+ " "
+ "::$proto_ns$::internal::AssignDescriptors(&$assign_desc_table$);\n"
+ " return $file_level_service_descriptors$[$1$];\n"
"}\n"
"\n"
- "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n"
+ "const ::$proto_ns$::ServiceDescriptor* $classname$::GetDescriptor() {\n"
" return descriptor();\n"
"}\n"
- "\n");
+ "\n",
+ index_in_metadata_);
// Generate methods of the interface.
GenerateNotImplementedMethods(printer);
@@ -195,18 +197,20 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) {
GenerateGetPrototype(RESPONSE, printer);
// Generate stub implementation.
- printer->Print(vars_,
- "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n"
- " : channel_(channel), owns_channel_(false) {}\n"
- "$classname$_Stub::$classname$_Stub(\n"
- " ::google::protobuf::RpcChannel* channel,\n"
- " ::google::protobuf::Service::ChannelOwnership ownership)\n"
- " : channel_(channel),\n"
- " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n"
- "$classname$_Stub::~$classname$_Stub() {\n"
- " if (owns_channel_) delete channel_;\n"
- "}\n"
- "\n");
+ format(
+ "$classname$_Stub::$classname$_Stub(::$proto_ns$::RpcChannel* channel)\n"
+ " : channel_(channel), owns_channel_(false) {}\n"
+ "$classname$_Stub::$classname$_Stub(\n"
+ " ::$proto_ns$::RpcChannel* channel,\n"
+ " ::$proto_ns$::Service::ChannelOwnership ownership)\n"
+ " : channel_(channel),\n"
+ " owns_channel_(ownership == "
+ "::$proto_ns$::Service::STUB_OWNS_CHANNEL) "
+ "{}\n"
+ "$classname$_Stub::~$classname$_Stub() {\n"
+ " if (owns_channel_) delete channel_;\n"
+ "}\n"
+ "\n");
GenerateStubMethods(printer);
}
@@ -214,123 +218,110 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) {
void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
- std::map<string, string> sub_vars;
- sub_vars["classname"] = descriptor_->name();
- sub_vars["name"] = method->name();
- sub_vars["index"] = SimpleItoa(i);
- sub_vars["input_type"] = ClassName(method->input_type(), true);
- sub_vars["output_type"] = ClassName(method->output_type(), true);
-
- printer->Print(sub_vars,
- "void $classname$::$name$(::google::protobuf::RpcController* controller,\n"
- " const $input_type$*,\n"
- " $output_type$*,\n"
- " ::google::protobuf::Closure* done) {\n"
- " controller->SetFailed(\"Method $name$() not implemented.\");\n"
- " done->Run();\n"
- "}\n"
- "\n");
+ Formatter format(printer, vars_);
+ InitMethodVariables(method, &format);
+ format(
+ "void $classname$::$name$(::$proto_ns$::RpcController* controller,\n"
+ " const $input_type$*,\n"
+ " $output_type$*,\n"
+ " ::google::protobuf::Closure* done) {\n"
+ " controller->SetFailed(\"Method $name$() not implemented.\");\n"
+ " done->Run();\n"
+ "}\n"
+ "\n");
}
}
void ServiceGenerator::GenerateCallMethod(io::Printer* printer) {
- printer->Print(
- vars_,
- "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n"
- " ::google::protobuf::RpcController* controller,\n"
- " const ::google::protobuf::Message* request,\n"
- " ::google::protobuf::Message* response,\n"
+ Formatter format(printer, vars_);
+ format(
+ "void $classname$::CallMethod(const ::$proto_ns$::MethodDescriptor* "
+ "method,\n"
+ " ::$proto_ns$::RpcController* controller,\n"
+ " const ::$proto_ns$::Message* request,\n"
+ " ::$proto_ns$::Message* response,\n"
" ::google::protobuf::Closure* done) {\n"
- " GOOGLE_DCHECK_EQ(method->service(), "
- "$file_namespace$::file_level_service_descriptors[$index$]);\n"
- " switch(method->index()) {\n");
+ " GOOGLE_DCHECK_EQ(method->service(), $file_level_service_descriptors$[$1$]);\n"
+ " switch(method->index()) {\n",
+ index_in_metadata_);
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
- std::map<string, string> sub_vars;
- sub_vars["name"] = method->name();
- sub_vars["index"] = SimpleItoa(i);
- sub_vars["input_type"] = ClassName(method->input_type(), true);
- sub_vars["output_type"] = ClassName(method->output_type(), true);
+ Formatter format(printer, vars_);
+ InitMethodVariables(method, &format);
// Note: down_cast does not work here because it only works on pointers,
// not references.
- printer->Print(sub_vars,
- " case $index$:\n"
- " $name$(controller,\n"
- " ::google::protobuf::down_cast<const $input_type$*>(request),\n"
- " ::google::protobuf::down_cast< $output_type$*>(response),\n"
- " done);\n"
- " break;\n");
+ format(
+ " case $1$:\n"
+ " $name$(controller,\n"
+ " ::google::protobuf::down_cast<const $input_type$*>(request),\n"
+ " ::google::protobuf::down_cast< $output_type$*>(response),\n"
+ " done);\n"
+ " break;\n",
+ i);
}
- printer->Print(vars_,
- " default:\n"
- " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n"
- " break;\n"
- " }\n"
- "}\n"
- "\n");
+ format(
+ " default:\n"
+ " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n"
+ " break;\n"
+ " }\n"
+ "}\n"
+ "\n");
}
void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which,
io::Printer* printer) {
+ Formatter format(printer, vars_);
if (which == REQUEST) {
- printer->Print(vars_,
- "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n");
+ format("const ::$proto_ns$::Message& $classname$::GetRequestPrototype(\n");
} else {
- printer->Print(vars_,
- "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n");
+ format("const ::$proto_ns$::Message& $classname$::GetResponsePrototype(\n");
}
- printer->Print(vars_,
- " const ::google::protobuf::MethodDescriptor* method) const {\n"
- " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n"
- " switch(method->index()) {\n");
+ format(
+ " const ::$proto_ns$::MethodDescriptor* method) const {\n"
+ " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n"
+ " switch(method->index()) {\n");
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
const Descriptor* type =
- (which == REQUEST) ? method->input_type() : method->output_type();
-
- std::map<string, string> sub_vars;
- sub_vars["index"] = SimpleItoa(i);
- sub_vars["type"] = ClassName(type, true);
+ (which == REQUEST) ? method->input_type() : method->output_type();
- printer->Print(sub_vars,
- " case $index$:\n"
- " return $type$::default_instance();\n");
+ format(
+ " case $1$:\n"
+ " return $2$::default_instance();\n",
+ i, QualifiedClassName(type));
}
- printer->Print(
- " default:\n"
- " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n"
- " return *::google::protobuf::MessageFactory::generated_factory()\n"
- " ->GetPrototype(method->$input_or_output$_type());\n"
- " }\n"
- "}\n"
- "\n",
- "input_or_output", which == REQUEST ? "input" : "output");
+ format(
+ " default:\n"
+ " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n"
+ " return *::$proto_ns$::MessageFactory::generated_factory()\n"
+ " ->GetPrototype(method->$1$_type());\n"
+ " }\n"
+ "}\n"
+ "\n",
+ which == REQUEST ? "input" : "output");
}
void ServiceGenerator::GenerateStubMethods(io::Printer* printer) {
for (int i = 0; i < descriptor_->method_count(); i++) {
const MethodDescriptor* method = descriptor_->method(i);
- std::map<string, string> sub_vars;
- sub_vars["classname"] = descriptor_->name();
- sub_vars["name"] = method->name();
- sub_vars["index"] = SimpleItoa(i);
- sub_vars["input_type"] = ClassName(method->input_type(), true);
- sub_vars["output_type"] = ClassName(method->output_type(), true);
-
- printer->Print(sub_vars,
- "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n"
- " const $input_type$* request,\n"
- " $output_type$* response,\n"
- " ::google::protobuf::Closure* done) {\n"
- " channel_->CallMethod(descriptor()->method($index$),\n"
- " controller, request, response, done);\n"
- "}\n");
+ Formatter format(printer, vars_);
+ InitMethodVariables(method, &format);
+ format(
+ "void $classname$_Stub::$name$(::$proto_ns$::RpcController* "
+ "controller,\n"
+ " const $input_type$* request,\n"
+ " $output_type$* response,\n"
+ " ::google::protobuf::Closure* done) {\n"
+ " channel_->CallMethod(descriptor()->method($1$),\n"
+ " controller, request, response, done);\n"
+ "}\n",
+ i);
}
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_service.h b/src/google/protobuf/compiler/cpp/cpp_service.h
index 33c02547..2952e413 100644
--- a/src/google/protobuf/compiler/cpp/cpp_service.h
+++ b/src/google/protobuf/compiler/cpp/cpp_service.h
@@ -42,11 +42,13 @@
namespace google {
namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
@@ -55,6 +57,7 @@ class ServiceGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
explicit ServiceGenerator(const ServiceDescriptor* descriptor,
+ const std::map<std::string, std::string>& vars,
const Options& options);
~ServiceGenerator();
@@ -70,7 +73,8 @@ class ServiceGenerator {
// descriptor.
void GenerateDescriptorInitializer(io::Printer* printer, int index);
- // Generate implementations of everything declared by GenerateDeclarations().
+ // Generate implementations of everything declared by
+ // GenerateDeclarations().
void GenerateImplementation(io::Printer* printer);
private:
@@ -105,7 +109,7 @@ class ServiceGenerator {
void GenerateStubMethods(io::Printer* printer);
const ServiceDescriptor* descriptor_;
- std::map<string, string> vars_;
+ std::map<std::string, std::string> vars_;
int index_in_metadata_;
@@ -116,6 +120,6 @@ class ServiceGenerator {
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index cf6c4b33..ecfabe64 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -36,9 +36,9 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
-
#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -50,19 +50,20 @@ void SetStringVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
SetCommonFieldVariables(descriptor, variables, options);
- (*variables)["default"] = DefaultValue(descriptor);
+ (*variables)["default"] = DefaultValue(options, descriptor);
(*variables)["default_length"] =
SimpleItoa(descriptor->default_value_string().length());
string default_variable_string = MakeDefaultName(descriptor);
(*variables)["default_variable_name"] = default_variable_string;
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
- ? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()"
+ ? "&::" + (*variables)["proto_ns"] +
+ "::internal::GetEmptyStringAlreadyInited()"
: "&" + 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";
+ (*variables)["null_check"] = (*variables)["DCHK"] + "(value != NULL);\n";
// NOTE: Escaped here to unblock proto1->proto2 migration.
// TODO(liujisi): Extend this to apply for other conflicting methods.
(*variables)["release_name"] =
@@ -70,7 +71,11 @@ void SetStringVariables(const FieldDescriptor* descriptor,
descriptor, "release_");
(*variables)["full_name"] = descriptor->full_name();
- (*variables)["string_piece"] = "::std::string";
+ if (options.opensource_runtime) {
+ (*variables)["string_piece"] = "::std::string";
+ } else {
+ (*variables)["string_piece"] = "::StringPiece";
+ }
(*variables)["lite"] =
HasDescriptorMethods(descriptor->file(), options) ? "" : "Lite";
@@ -82,8 +87,7 @@ void SetStringVariables(const FieldDescriptor* descriptor,
StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
- : FieldGenerator(options),
- descriptor_(descriptor),
+ : FieldGenerator(descriptor, options),
lite_(!HasDescriptorMethods(descriptor->file(), options)),
inlined_(false) {
@@ -107,9 +111,9 @@ StringFieldGenerator::~StringFieldGenerator() {}
void StringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (inlined_) {
- printer->Print(variables_,
- "::google::protobuf::internal::InlinedStringField $name$_;\n");
+ format("::$proto_ns$::internal::InlinedStringField $name$_;\n");
} else {
// N.B. that we continue to use |ArenaStringPtr| instead of |string*| for
// string fields, even when SupportArenas(descriptor_) == false. Why? The
@@ -123,25 +127,27 @@ GeneratePrivateMembers(io::Printer* printer) const {
// conditionals. It's simpler to stick with this but use lightweight
// accessors that assume arena == NULL. There should be very little
// overhead anyway because it's just a tagged pointer in-memory.
- printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n");
+ format("::$proto_ns$::internal::ArenaStringPtr $name$_;\n");
}
}
void StringFieldGenerator::
GenerateStaticMembers(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (!descriptor_->default_value_string().empty()) {
// We make the default instance public, so it can be initialized by
// non-friend code.
- printer->Print(variables_,
- "public:\n"
- "static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string>"
- " $default_variable_name$;\n"
- "private:\n");
+ format(
+ "public:\n"
+ "static ::$proto_ns$::internal::ExplicitlyConstructed<$string$>"
+ " $default_variable_name$;\n"
+ "private:\n");
}
}
void StringFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// If we're using StringFieldGenerator for a field with a ctype, it's
// because that ctype isn't actually implemented. In particular, this is
// true of ctype=CORD and ctype=STRING_PIECE in the open source release.
@@ -159,90 +165,82 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
// reflection interface since the reflection interface is independent of
// the string's underlying representation.
- bool unknown_ctype =
- descriptor_->options().ctype() != EffectiveStringCType(descriptor_);
+ bool unknown_ctype = descriptor_->options().ctype() !=
+ EffectiveStringCType(descriptor_, options_);
if (unknown_ctype) {
- printer->Outdent();
- printer->Print(
- " private:\n"
- " // Hidden due to unknown ctype option.\n");
- printer->Indent();
+ format.Outdent();
+ format(
+ " private:\n"
+ " // Hidden due to unknown ctype option.\n");
+ format.Indent();
}
- printer->Print(variables_,
- "$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_,
- "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_);
+ format(
+ "$deprecated_attr$const $string$& ${1$$name$$}$() const;\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(const $string$& value);\n"
+ "#if LANG_CXX11\n"
+ "$deprecated_attr$void ${1$set_$name$$}$($string$&& value);\n"
+ "#endif\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(const char* value);\n",
+ descriptor_);
+ if (!options_.opensource_runtime) {
+ format(
+ "$deprecated_attr$void ${1$set_$name$$}$(::StringPiece value);\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(const ::std::string& value);\n"
+ "#endif\n",
+ descriptor_);
+ }
+ format(
+ "$deprecated_attr$void ${1$set_$name$$}$(const $pointer_type$* "
+ "value, size_t size)"
+ ";\n"
+ "$deprecated_attr$$string$* ${1$mutable_$name$$}$();\n"
+ "$deprecated_attr$$string$* ${1$$release_name$$}$();\n"
+ "$deprecated_attr$void ${1$set_allocated_$name$$}$($string$* $name$);\n",
+ descriptor_);
+ if (options_.opensource_runtime) {
+ if (SupportsArenas(descriptor_)) {
+ format(
+ "$GOOGLE_PROTOBUF$_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors "
+ "for\"\n"
+ "\" string fields are deprecated and will be removed in a\"\n"
+ "\" future release.\")\n"
+ "$string$* ${1$unsafe_arena_release_$name$$}$();\n"
+ "$GOOGLE_PROTOBUF$_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors "
+ "for\"\n"
+ "\" string fields are deprecated and will be removed in a\"\n"
+ "\" future release.\")\n"
+ "void ${1$unsafe_arena_set_allocated_$name$$}$(\n"
+ " $string$* $name$);\n",
+ descriptor_);
+ }
}
if (unknown_ctype) {
- printer->Outdent();
- printer->Print(" public:\n");
- printer->Indent();
+ format.Outdent();
+ format(" public:\n");
+ format.Indent();
}
}
void StringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
- printer->Print(
- variables_,
- "inline const ::std::string& $classname$::$name$() const {\n"
+ format(
+ "inline const $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 $string$& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
- "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ "inline void $classname$::set_$name$($string$&& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
@@ -255,7 +253,26 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $name$_.Set$lite$($default_variable$, $string_piece$(value),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
- "}\n"
+ "}\n");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void $classname$::set_$name$(::StringPiece value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.Set$lite$($default_variable$, value, "
+ "GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.Set$lite$($default_variable$, "
+ "::StringPiece(value.data(),\n"
+ " value.size()), GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
+ }
+ format(
"inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
@@ -265,31 +282,32 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "inline ::std::string* $classname$::mutable_$name$() {\n"
+ "inline $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 $string$* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
if (HasFieldPresence(descriptor_->file())) {
- printer->Print(variables_,
- " if (!has_$name$()) {\n"
- " return NULL;\n"
- " }\n"
- " $clear_hasbit$\n"
- " return $name$_.ReleaseNonDefault("
- "$default_variable$, GetArenaNoVirtual());\n");
+ format(
+ " if (!has_$name$()) {\n"
+ " return NULL;\n"
+ " }\n"
+ " $clear_hasbit$\n"
+ " return $name$_.ReleaseNonDefault("
+ "$default_variable$, GetArenaNoVirtual());\n");
} else {
- printer->Print(variables_,
- " $clear_hasbit$\n"
- " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n");
+ format(
+ " $clear_hasbit$\n"
+ " return $name$_.Release($default_variable$, "
+ "GetArenaNoVirtual());\n");
}
- printer->Print(variables_,
+ format(
"}\n"
- "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -298,43 +316,45 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $name$_.SetAllocated($default_variable$, $name$,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\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$::unsafe_arena_set_allocated_$name$(\n"
- " ::std::string* $name$) {\n"
- " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
- " if ($name$ != NULL) {\n"
- " $set_hasbit$\n"
- " } else {\n"
- " $clear_hasbit$\n"
- " }\n"
- " $name$_.UnsafeArenaSetAllocated($default_variable$,\n"
- " $name$, GetArenaNoVirtual());\n"
- " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
- "$full_name$)\n"
"}\n");
+ if (options_.opensource_runtime) {
+ format(
+ "inline $string$* $classname$::unsafe_arena_release_$name$() {\n"
+ " // "
+ "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ " $DCHK$(GetArenaNoVirtual() != NULL);\n"
+ " $clear_hasbit$\n"
+ " return $name$_.UnsafeArenaRelease($default_variable$,\n"
+ " GetArenaNoVirtual());\n"
+ "}\n"
+ "inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
+ " $string$* $name$) {\n"
+ " $DCHK$(GetArenaNoVirtual() != NULL);\n"
+ " if ($name$ != NULL) {\n"
+ " $set_hasbit$\n"
+ " } else {\n"
+ " $clear_hasbit$\n"
+ " }\n"
+ " $name$_.UnsafeArenaSetAllocated($default_variable$,\n"
+ " $name$, GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
+ "$full_name$)\n"
+ "}\n");
+ }
} else {
// No-arena case.
- printer->Print(
- variables_,
- "inline const ::std::string& $classname$::$name$() const {\n"
+ format(
+ "inline const $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 $string$& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
- "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ "inline void $classname$::set_$name$($string$&& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena(\n"
" $default_variable$, ::std::move(value));\n"
@@ -346,7 +366,24 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
- "}\n"
+ "}\n");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void $classname$::set_$name$(::StringPiece value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.SetNoArena($default_variable$, value);\n"
+ " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ " $set_hasbit$\n"
+ " $name$_.SetNoArena($default_variable$,\n"
+ " ::StringPiece(value.data(), value.size()));\n"
+ " // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
+ }
+ format(
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, "
"size_t size) {\n"
@@ -355,30 +392,30 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $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 $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 $string$* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n");
if (HasFieldPresence(descriptor_->file())) {
- printer->Print(variables_,
- " if (!has_$name$()) {\n"
- " return NULL;\n"
- " }\n"
- " $clear_hasbit$\n"
- " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n");
+ format(
+ " if (!has_$name$()) {\n"
+ " return NULL;\n"
+ " }\n"
+ " $clear_hasbit$\n"
+ " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n");
} else {
- printer->Print(variables_,
- " $clear_hasbit$\n"
- " return $name$_.ReleaseNoArena($default_variable$);\n");
+ format(
+ " $clear_hasbit$\n"
+ " return $name$_.ReleaseNoArena($default_variable$);\n");
}
- printer->Print(variables_,
+ format(
"}\n"
- "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -392,41 +429,42 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
void StringFieldGenerator::
GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (!descriptor_->default_value_string().empty()) {
// Initialized in GenerateDefaultInstanceAllocator.
- printer->Print(variables_,
- "::google::protobuf::internal::ExplicitlyConstructed<::std::string> "
- "$classname$::$default_variable_name$;\n");
+ format(
+ "::$proto_ns$::internal::ExplicitlyConstructed<$string$> "
+ "$classname$::$default_variable_name$;\n");
}
}
void StringFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// Two-dimension specialization here: supporting arenas or not, and default
// value is the empty string or not. Complexity here ensures the minimal
// number of branches / amount of extraneous code at runtime (given that the
// below methods are inlined one-liners)!
if (SupportsArenas(descriptor_)) {
if (descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
+ format(
+ "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
} else {
- printer->Print(variables_,
- "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
+ format(
+ "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
}
} else {
if (descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$name$_.ClearToEmptyNoArena($default_variable$);\n");
+ format("$name$_.ClearToEmptyNoArena($default_variable$);\n");
} else {
- printer->Print(variables_,
- "$name$_.ClearToDefaultNoArena($default_variable$);\n");
+ format("$name$_.ClearToDefaultNoArena($default_variable$);\n");
}
}
}
void StringFieldGenerator::
GenerateMessageClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// Two-dimension specialization here: supporting arenas, field presence, or
// not, and default value is the empty string or not. Complexity here ensures
// the minimal number of branches / amount of extraneous code at runtime
@@ -447,67 +485,60 @@ GenerateMessageClearingCode(io::Printer* printer) const {
//
// For non-inlined strings, we distinguish from non-default by comparing
// instances, rather than contents.
- printer->Print(variables_,
- "GOOGLE_DCHECK(!$name$_.IsDefault($default_variable$));\n");
+ format("$DCHK$(!$name$_.IsDefault($default_variable$));\n");
}
if (SupportsArenas(descriptor_)) {
if (descriptor_->default_value_string().empty()) {
if (must_be_present) {
- printer->Print(variables_,
- "$name$_.ClearNonDefaultToEmpty();\n");
+ format("$name$_.ClearNonDefaultToEmpty();\n");
} else {
- printer->Print(variables_,
- "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
+ format(
+ "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
}
} else {
// Clear to a non-empty default is more involved, as we try to use the
// Arena if one is present and may need to reallocate the string.
- printer->Print(variables_,
- "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
+ format(
+ "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n");
}
} else if (must_be_present) {
// When Arenas are disabled and field presence has been checked, we can
// safely treat the ArenaStringPtr as a string*.
if (descriptor_->default_value_string().empty()) {
- printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n");
+ format("$name$_.ClearNonDefaultToEmptyNoArena();\n");
} else {
- printer->Print(
- variables_,
- "$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n");
+ format("$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n");
}
} else {
if (descriptor_->default_value_string().empty()) {
- printer->Print(variables_,
- "$name$_.ClearToEmptyNoArena($default_variable$);\n");
+ format("$name$_.ClearToEmptyNoArena($default_variable$);\n");
} else {
- printer->Print(variables_,
- "$name$_.ClearToDefaultNoArena($default_variable$);\n");
+ format("$name$_.ClearToDefaultNoArena($default_variable$);\n");
}
}
}
void StringFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
// TODO(gpike): improve this
- printer->Print(variables_, "set_$name$(from.$name$());\n");
+ format("set_$name$(from.$name$());\n");
} else {
- printer->Print(variables_,
- "$set_hasbit$\n"
- "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n");
+ format(
+ "$set_hasbit$\n"
+ "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n");
}
}
void StringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (inlined_) {
- printer->Print(
- variables_,
- "$name$_.Swap(&other->$name$_);\n");
+ format("$name$_.Swap(&other->$name$_);\n");
} else {
- printer->Print(
- variables_,
+ format(
"$name$_.Swap(&other->$name$_, $default_variable$,\n"
" GetArenaNoVirtual());\n");
}
@@ -515,6 +546,7 @@ GenerateSwappingCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// TODO(ckennelly): Construct non-empty strings as part of the initializer
// list.
if (inlined_ && descriptor_->default_value_string().empty()) {
@@ -522,125 +554,149 @@ GenerateConstructorCode(io::Printer* printer) const {
return;
}
- printer->Print(variables_,
- "$name$_.UnsafeSetDefault($default_variable$);\n");
+ format("$name$_.UnsafeSetDefault($default_variable$);\n");
}
void StringFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
GenerateConstructorCode(printer);
if (HasFieldPresence(descriptor_->file())) {
- printer->Print(variables_,
- "if (from.has_$name$()) {\n");
+ format("if (from.has_$name$()) {\n");
} else {
- printer->Print(variables_,
- "if (from.$name$().size() > 0) {\n");
+ format("if (from.$name$().size() > 0) {\n");
}
- printer->Indent();
+ format.Indent();
if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
// TODO(gpike): improve this
- printer->Print(variables_,
- "$name$_.Set$lite$($default_variable$, from.$name$(),\n"
- " GetArenaNoVirtual());\n");
+ format(
+ "$name$_.Set$lite$($default_variable$, from.$name$(),\n"
+ " GetArenaNoVirtual());\n");
} else {
- printer->Print(variables_,
- "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n");
+ format("$name$_.AssignWithDefault($default_variable$, from.$name$_);\n");
}
- printer->Outdent();
- printer->Print("}\n");
+ format.Outdent();
+ format("}\n");
}
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (inlined_) {
// The destructor is automatically invoked.
return;
}
- printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n");
+ format("$name$_.DestroyNoArena($default_variable$);\n");
}
bool StringFieldGenerator::GenerateArenaDestructorCode(
io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (!inlined_) {
return false;
}
- printer->Print(variables_,
- "_this->$name$_.DestroyNoArena($default_variable$);\n");
+ format("_this->$name$_.DestroyNoArena($default_variable$);\n");
return true;
}
void StringFieldGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (!descriptor_->default_value_string().empty()) {
- printer->Print(
- variables_,
+ format(
"$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"
- );
+ "$string$($default$, $default_length$);\n"
+ "::$proto_ns$::internal::OnShutdownDestroyString(\n"
+ " $ns$::$classname$::$default_variable_name$.get_mutable());\n");
}
}
void StringFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n"
- " input, this->mutable_$name$()));\n");
+ Formatter format(printer, variables_);
+ // The google3 version of proto2 has ArenaStrings and parses into them
+ // directly, but for the open-source release, we always parse into ::std::string
+ // instances. Note that for lite, we do similarly to the open source release
+ // and use ::std::string, not ArenaString.
+ if (!options_.opensource_runtime && !inlined_ &&
+ SupportsArenas(descriptor_) && !lite_) {
+ // If arena != NULL, the current string is either an ArenaString (no
+ // destructor necessary) or a materialized ::std::string (and is on the Arena's
+ // destructor list). No call to ArenaStringPtr::Destroy is needed.
+ format(
+ "if (arena != NULL) {\n"
+ " ::$proto_ns$::internal::TaggedPtr<$string$> str =\n"
+ " ::$proto_ns$::internal::ReadArenaString(input, arena);\n"
+ " DO_(!str.IsNull());\n"
+ " $set_hasbit_io$\n"
+ " $name$_.UnsafeSetTaggedPointer(str);\n"
+ "} else {\n"
+ " DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n"
+ " input, this->mutable_$name$()));\n"
+ "}\n");
+ } else {
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n"
+ " input, this->mutable_$name$()));\n");
+ }
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, true, variables_,
+ descriptor_, options_, true,
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
- printer);
+ format);
}
}
bool StringFieldGenerator::
MergeFromCodedStreamNeedsArena() const {
- return false;
+ return !lite_ && !inlined_ && !options_.opensource_runtime;
}
void StringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, false, variables_,
+ descriptor_, options_, false,
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
- printer);
+ format);
}
- printer->Print(variables_,
- "::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n"
- " $number$, this->$name$(), output);\n");
+ format(
+ "::$proto_ns$::internal::WireFormatLite::Write$declared_type$"
+ "MaybeAliased(\n"
+ " $number$, this->$name$(), output);\n");
}
void StringFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, false, variables_,
+ descriptor_, options_, false,
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
- printer);
+ format);
}
- printer->Print(variables_,
- "target =\n"
- " ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(\n"
- " $number$, this->$name$(), target);\n");
+ format(
+ "target =\n"
+ " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$ToArray(\n"
+ " $number$, this->$name$(), target);\n");
}
void StringFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
- printer->Print(variables_,
- "total_size += $tag_size$ +\n"
- " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " this->$name$());\n");
+ Formatter format(printer, variables_);
+ format(
+ "total_size += $tag_size$ +\n"
+ " ::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n"
+ " this->$name$());\n");
}
uint32 StringFieldGenerator::CalculateFieldTag() const {
@@ -661,17 +717,17 @@ StringOneofFieldGenerator::~StringOneofFieldGenerator() {}
void StringOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
- printer->Print(
- variables_,
- "inline const ::std::string& $classname$::$name$() const {\n"
+ format(
+ "inline const $string$& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $field_member$.Get();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const $string$& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -682,7 +738,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
- "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ "inline void $classname$::set_$name$($string$&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -704,7 +760,34 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $field_member$.Set$lite$($default_variable$,\n"
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
- "}\n"
+ "}\n");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void $classname$::set_$name$(::StringPiece value) {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $field_member$.Set$lite$($default_variable$, value,\n"
+ " GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $field_member$.Set$lite$($default_variable$,\n"
+ " ::StringPiece(value.data(), value.size()), "
+ "GetArenaNoVirtual());\n"
+ " // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
+ }
+ format(
"inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
@@ -719,7 +802,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "inline ::std::string* $classname$::mutable_$name$() {\n"
+ "inline $string$* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -729,7 +812,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
- "inline ::std::string* $classname$::$release_name$() {\n"
+ "inline $string$* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -739,57 +822,57 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return NULL;\n"
" }\n"
"}\n"
- "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
- " if (!has_$name$()) {\n"
- " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ "inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
+ " if (has_$oneof_name$()) {\n"
+ " clear_$oneof_name$();\n"
" }\n"
- " clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
- " $field_member$.SetAllocated($default_variable$, $name$,\n"
- " GetArenaNoVirtual());\n"
+ " $field_member$.UnsafeSetDefault($name$);\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\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 $field_member$.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"
- " $field_member$.UnsafeSetDefault($default_variable$);\n"
- " }\n"
- " clear_$oneof_name$();\n"
- " if ($name$) {\n"
- " set_has_$name$();\n"
- " $field_member$.UnsafeArenaSetAllocated($default_variable$, "
- "$name$, GetArenaNoVirtual());\n"
- " }\n"
- " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
- "$full_name$)\n"
"}\n");
+ if (options_.opensource_runtime) {
+ format(
+ "inline $string$* $classname$::unsafe_arena_release_$name$() {\n"
+ " // "
+ "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
+ " $DCHK$(GetArenaNoVirtual() != NULL);\n"
+ " if (has_$name$()) {\n"
+ " clear_has_$oneof_name$();\n"
+ " return $field_member$.UnsafeArenaRelease(\n"
+ " $default_variable$, GetArenaNoVirtual());\n"
+ " } else {\n"
+ " return NULL;\n"
+ " }\n"
+ "}\n"
+ "inline void $classname$::unsafe_arena_set_allocated_$name$("
+ "$string$* $name$) {\n"
+ " $DCHK$(GetArenaNoVirtual() != NULL);\n"
+ " if (!has_$name$()) {\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " clear_$oneof_name$();\n"
+ " if ($name$) {\n"
+ " set_has_$name$();\n"
+ " $field_member$.UnsafeArenaSetAllocated($default_variable$, "
+ "$name$, GetArenaNoVirtual());\n"
+ " }\n"
+ " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
+ "$full_name$)\n"
+ "}\n");
+ }
} else {
// No-arena case.
- printer->Print(
- variables_,
- "inline const ::std::string& $classname$::$name$() const {\n"
+ format(
+ "inline const $string$& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $field_member$.GetNoArena();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ "inline void $classname$::set_$name$(const $string$& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -800,7 +883,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
- "inline void $classname$::set_$name$(::std::string&& value) {\n"
+ "inline void $classname$::set_$name$($string$&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -821,7 +904,32 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" $field_member$.SetNoArena($default_variable$,\n"
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
- "}\n"
+ "}\n");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void $classname$::set_$name$(::StringPiece value) {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $field_member$.SetNoArena($default_variable$, value);\n"
+ " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void $classname$::set_$name$(const ::std::string& value) {\n"
+ " if (!has_$name$()) {\n"
+ " clear_$oneof_name$();\n"
+ " set_has_$name$();\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " }\n"
+ " $field_member$.SetNoArena($default_variable$,\n"
+ " ::StringPiece(value.data(), value.size()));\n"
+ " // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
+ }
+ format(
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, size_t "
"size) {\n"
@@ -834,7 +942,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" 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 $string$* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -843,7 +951,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $field_member$.MutableNoArena($default_variable$);\n"
"}\n"
- "inline ::std::string* $classname$::$release_name$() {\n"
+ "inline $string$* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -852,14 +960,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return NULL;\n"
" }\n"
"}\n"
- "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
- " if (!has_$name$()) {\n"
- " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ "inline void $classname$::set_allocated_$name$($string$* $name$) {\n"
+ " if (has_$oneof_name$()) {\n"
+ " clear_$oneof_name$();\n"
" }\n"
- " clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
- " $field_member$.SetAllocatedNoArena($default_variable$, $name$);\n"
+ " $field_member$.UnsafeSetDefault($name$);\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
@@ -868,13 +975,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (SupportsArenas(descriptor_)) {
- printer->Print(variables_,
- "$field_member$.Destroy($default_variable$,\n"
- " GetArenaNoVirtual());\n");
+ format(
+ "$field_member$.Destroy($default_variable$,\n"
+ " GetArenaNoVirtual());\n");
} else {
- printer->Print(variables_,
- "$field_member$.DestroyNoArena($default_variable$);\n");
+ format("$field_member$.DestroyNoArena($default_variable$);\n");
}
}
@@ -890,31 +997,55 @@ GenerateSwappingCode(io::Printer* printer) const {
void StringOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
- printer->Print(
- variables_,
+ Formatter format(printer, variables_);
+ format(
"$ns$::_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n"
" $default_variable$);\n");
}
void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (has_$name$()) {\n"
- " $field_member$.DestroyNoArena($default_variable$);\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "if (has_$name$()) {\n"
+ " $field_member$.DestroyNoArena($default_variable$);\n"
+ "}\n");
}
void StringOneofFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n"
- " input, this->mutable_$name$()));\n");
+ Formatter format(printer, variables_);
+ // See above: ArenaString is not included in the open-source release.
+ if (!options_.opensource_runtime && SupportsArenas(descriptor_) && !lite_) {
+ // If has_$name$(), then the current string is either an ArenaString (no
+ // destructor necessary) or a materialized ::std::string (and is on the Arena's
+ // destructor list). No call to ArenaStringPtr::Destroy is needed.
+ format(
+ "if (arena != NULL) {\n"
+ " clear_$oneof_name$();\n"
+ " if (!has_$name$()) {\n"
+ " $field_member$.UnsafeSetDefault($default_variable$);\n"
+ " set_has_$name$();\n"
+ " }\n"
+ " ::$proto_ns$::internal::TaggedPtr<$string$> new_value =\n"
+ " ::$proto_ns$::internal::ReadArenaString(input, arena);\n"
+ " DO_(!new_value.IsNull());\n"
+ " $field_member$.UnsafeSetTaggedPointer(new_value);\n"
+ "} else {\n"
+ " DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n"
+ " input, this->mutable_$name$()));\n"
+ "}\n");
+ } else {
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n"
+ " input, this->mutable_$name$()));\n");
+ }
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, true, variables_,
+ descriptor_, options_, true,
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
- printer);
+ format);
}
}
@@ -923,7 +1054,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
RepeatedStringFieldGenerator::RepeatedStringFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
- : FieldGenerator(options), descriptor_(descriptor) {
+ : FieldGenerator(descriptor, options) {
SetStringVariables(descriptor, &variables_, options);
}
@@ -931,182 +1062,210 @@ RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {}
void RepeatedStringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "::google::protobuf::RepeatedPtrField< ::std::string> $name$_;\n");
+ Formatter format(printer, variables_);
+ format("::$proto_ns$::RepeatedPtrField<$string$> $name$_;\n");
}
void RepeatedStringFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
+ Formatter format(printer, variables_);
// See comment above about unknown ctypes.
- bool unknown_ctype =
- descriptor_->options().ctype() != EffectiveStringCType(descriptor_);
+ bool unknown_ctype = descriptor_->options().ctype() !=
+ EffectiveStringCType(descriptor_, options_);
if (unknown_ctype) {
- printer->Outdent();
- printer->Print(
- " private:\n"
- " // Hidden due to unknown ctype option.\n");
- printer->Indent();
+ format.Outdent();
+ format(
+ " private:\n"
+ " // Hidden due to unknown ctype option.\n");
+ format.Indent();
}
- printer->Print(variables_,
- "$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_,
+ format(
+ "$deprecated_attr$const $string$& ${1$$name$$}$(int index) const;\n"
+ "$deprecated_attr$$string$* ${1$mutable_$name$$}$(int index);\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, const "
+ "$string$& value);\n"
+ "#if LANG_CXX11\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, $string$&& value);\n"
+ "#endif\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, const "
+ "char* value);\n",
+ descriptor_);
+ if (!options_.opensource_runtime) {
+ format(
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, "
+ "StringPiece value);\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "$deprecated_attr$void ${1$set_$name$$}$(int index, const "
+ "::std::string& value);\n"
+ "#endif\n",
+ descriptor_);
+ }
+ format(
+ "$deprecated_attr$void ${1$set_$name$$}$("
+ "int index, const $pointer_type$* value, size_t size);\n"
+ "$deprecated_attr$$string$* ${1$add_$name$$}$();\n"
+ "$deprecated_attr$void ${1$add_$name$$}$(const $string$& value);\n"
"#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$::google::protobuf::RepeatedPtrField< ::std::string>* "
- "${$mutable_$name$$}$()"
- ";\n");
- printer->Annotate("{", "}", descriptor_);
+ "$deprecated_attr$void ${1$add_$name$$}$($string$&& value);\n"
+ "#endif\n"
+ "$deprecated_attr$void ${1$add_$name$$}$(const char* value);\n",
+ descriptor_);
+ if (!options_.opensource_runtime) {
+ format(
+ "$deprecated_attr$void ${1$add_$name$$}$(StringPiece value);\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "$deprecated_attr$void ${1$add_$name$$}$(const ::std::string& value);\n"
+ "#endif\n",
+ descriptor_);
+ }
+ format(
+ "$deprecated_attr$void ${1$add_$name$$}$(const $pointer_type$* "
+ "value, size_t size)"
+ ";\n"
+ "$deprecated_attr$const ::$proto_ns$::RepeatedPtrField<$string$>& "
+ "${1$$name$$}$() "
+ "const;\n"
+ "$deprecated_attr$::$proto_ns$::RepeatedPtrField<$string$>* "
+ "${1$mutable_$name$$}$()"
+ ";\n",
+ descriptor_);
if (unknown_ctype) {
- printer->Outdent();
- printer->Print(" public:\n");
- printer->Indent();
+ format.Outdent();
+ format(" public:\n");
+ format.Indent();
}
}
void RepeatedStringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
+ Formatter format(printer, variables_);
if (options_.safe_boundary_check) {
- printer->Print(variables_,
- "inline const ::std::string& $classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_.InternalCheckedGet(\n"
- " index, ::google::protobuf::internal::GetEmptyStringAlreadyInited());\n"
- "}\n");
+ format(
+ "inline const $string$& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_.InternalCheckedGet(\n"
+ " index, ::$proto_ns$::internal::GetEmptyStringAlreadyInited());\n"
+ "}\n");
} else {
- printer->Print(variables_,
- "inline const ::std::string& $classname$::$name$(int index) const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n"
- " return $name$_.Get(index);\n"
+ format(
+ "inline const $string$& $classname$::$name$(int index) const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_.Get(index);\n"
+ "}\n");
+ }
+ format(
+ "inline $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 $string$& value) "
+ "{\n"
+ " // @@protoc_insertion_point(field_set:$full_name$)\n"
+ " $name$_.Mutable(index)->assign(value);\n"
+ "}\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::set_$name$(int index, $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");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void "
+ "$classname$::set_$name$(int index, StringPiece value) {\n"
+ " $name$_.Mutable(index)->assign(value.data(), value.size());\n"
+ " // @@protoc_insertion_point(field_set_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void "
+ "$classname$::set_$name$(int index, const std::string& value) {\n"
+ " $name$_.Mutable(index)->assign(value.data(), value.size());\n"
+ " // @@protoc_insertion_point(field_set_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
}
- printer->Print(variables_,
- "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"
- " // @@protoc_insertion_point(field_set:$full_name$)\n"
- " $name$_.Mutable(index)->assign(value);\n"
- "}\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 "
- "$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"
- " // @@protoc_insertion_point(field_add_mutable:$full_name$)\n"
- " return $name$_.Add();\n"
- "}\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"
- "#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 "
- "$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"
- "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"
- "$classname$::mutable_$name$() {\n"
- " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
- " return &$name$_;\n"
- "}\n");
+ format(
+ "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 $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 $string$& value) {\n"
+ " $name$_.Add()->assign(value);\n"
+ " // @@protoc_insertion_point(field_add:$full_name$)\n"
+ "}\n"
+ "#if LANG_CXX11\n"
+ "inline void $classname$::add_$name$($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");
+ if (!options_.opensource_runtime) {
+ format(
+ "inline void $classname$::add_$name$(StringPiece value) {\n"
+ " $name$_.Add()->assign(value.data(), value.size());\n"
+ " // @@protoc_insertion_point(field_add_string_piece:$full_name$)\n"
+ "}\n"
+ "#ifdef HAS_GLOBAL_STRING\n"
+ "inline void $classname$::add_$name$(const ::std::string& value) {\n"
+ " $name$_.Add()->assign(value.data(), value.size());\n"
+ " // @@protoc_insertion_point(field_add_std_string:$full_name$)\n"
+ "}\n"
+ "#endif\n");
+ }
+ format(
+ "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"
+ "inline const ::$proto_ns$::RepeatedPtrField<$string$>&\n"
+ "$classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_list:$full_name$)\n"
+ " return $name$_;\n"
+ "}\n"
+ "inline ::$proto_ns$::RepeatedPtrField<$string$>*\n"
+ "$classname$::mutable_$name$() {\n"
+ " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
+ " return &$name$_;\n"
+ "}\n");
}
void RepeatedStringFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.Clear();\n");
+ Formatter format(printer, variables_);
+ format("$name$_.Clear();\n");
}
void RepeatedStringFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n");
+ Formatter format(printer, variables_);
+ format("$name$_.MergeFrom(from.$name$_);\n");
}
void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_.InternalSwap(CastToBase(&other->$name$_));\n");
+ Formatter format(printer, variables_);
+ format("$name$_.InternalSwap(CastToBase(&other->$name$_));\n");
}
void RepeatedStringFieldGenerator::
@@ -1116,68 +1275,72 @@ GenerateConstructorCode(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateCopyConstructorCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);");
+ Formatter format(printer, variables_);
+ format("$name$_.CopyFrom(from.$name$_);");
}
void RepeatedStringFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
- printer->Print(variables_,
- "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n"
- " input, this->add_$name$()));\n");
+ Formatter format(printer, variables_);
+ format(
+ "DO_(::$proto_ns$::internal::WireFormatLite::Read$declared_type$(\n"
+ " input, this->add_$name$()));\n");
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, true, variables_,
+ descriptor_, options_, true,
"this->$name$(this->$name$_size() - 1).data(),\n"
"static_cast<int>(this->$name$(this->$name$_size() - 1).length()),\n",
- printer);
+ format);
}
}
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
- printer->Indent();
+ Formatter format(printer, variables_);
+ format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
+ format.Indent();
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, false, variables_,
+ descriptor_, options_, false,
"this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
- printer);
+ format);
}
- printer->Outdent();
- printer->Print(variables_,
- " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n"
- " $number$, this->$name$(i), output);\n"
- "}\n");
+ format.Outdent();
+ format(
+ " ::$proto_ns$::internal::WireFormatLite::Write$declared_type$(\n"
+ " $number$, this->$name$(i), output);\n"
+ "}\n");
}
void RepeatedStringFieldGenerator::
GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
- printer->Indent();
+ Formatter format(printer, variables_);
+ format("for (int i = 0, n = this->$name$_size(); i < n; i++) {\n");
+ format.Indent();
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
- descriptor_, options_, false, variables_,
+ descriptor_, options_, false,
"this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
- printer);
+ format);
}
- printer->Outdent();
- printer->Print(variables_,
- " target = ::google::protobuf::internal::WireFormatLite::\n"
- " Write$declared_type$ToArray($number$, this->$name$(i), target);\n"
- "}\n");
+ format.Outdent();
+ format(
+ " target = ::$proto_ns$::internal::WireFormatLite::\n"
+ " Write$declared_type$ToArray($number$, this->$name$(i), target);\n"
+ "}\n");
}
void RepeatedStringFieldGenerator::
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, n = this->$name$_size(); i < n; i++) {\n"
- " total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
- " this->$name$(i));\n"
- "}\n");
+ Formatter format(printer, variables_);
+ format(
+ "total_size += $tag_size$ *\n"
+ " ::$proto_ns$::internal::FromIntSize(this->$name$_size());\n"
+ "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"
+ " total_size += "
+ "::$proto_ns$::internal::WireFormatLite::$declared_type$Size(\n"
+ " this->$name$(i));\n"
+ "}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index 6cbf722f..3a1de551 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -75,8 +75,6 @@ class StringFieldGenerator : public FieldGenerator {
bool MergeFromCodedStreamNeedsArena() const;
protected:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
const bool lite_;
bool inlined_;
@@ -127,15 +125,12 @@ class RepeatedStringFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
- const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
-
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
index 22b759a9..2cf030eb 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
@@ -33,7 +33,7 @@
// Sanjay Ghemawat, Jeff Dean, and others.
//
// To test the code generator, we actually use it to generate code for
-// google/protobuf/unittest.proto, then test that. This means that we
+// net/proto2/internal/unittest.proto, then test that. This means that we
// are actually testing the parser and other parts of the system at the same
// time, and that problems in the generator may show up as compile-time errors
// rather than unittest failures, which may be surprising. However, testing
@@ -60,7 +60,7 @@
#define HELPERS_TEST_NAME HelpersTest
#define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest
-#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto"
+#define UNITTEST_PROTO_PATH "net/proto2/internal/unittest.proto"
#define UNITTEST ::protobuf_unittest
#define UNITTEST_IMPORT ::protobuf_unittest_import
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.h b/src/google/protobuf/compiler/cpp/cpp_unittest.h
index 69c8f44c..c5dc767a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.h
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.h
@@ -46,6 +46,6 @@ namespace google {
namespace protobuf {
namespace protobuf_unittest {}
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
index ff6354f8..898b1fbb 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.inc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.inc
@@ -33,7 +33,7 @@
// Sanjay Ghemawat, Jeff Dean, and others.
//
// To test the code generator, we actually use it to generate code for
-// google/protobuf/unittest.proto, then test that. This means that we
+// net/proto2/internal/unittest.proto, then test that. This means that we
// are actually testing the parser and other parts of the system at the same
// time, and that problems in the generator may show up as compile-time errors
// rather than unittest failures, which may be surprising. However, testing
@@ -50,6 +50,7 @@
#include <vector>
#include <google/protobuf/unittest_no_arena.pb.h>
+
#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
// We exclude this large proto from cmake build because it's too large for
// visual studio to compile (report internal errors).
@@ -57,7 +58,9 @@
#endif
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h>
+#include <google/protobuf/compiler/scc.h>
#include <google/protobuf/compiler/importer.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest_no_generic_services.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -72,8 +75,11 @@
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -110,12 +116,12 @@ TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) {
// Set up the Importer.
MockErrorCollector error_collector;
DiskSourceTree source_tree;
- source_tree.MapPath("", TestSourceDir());
+ source_tree.MapPath("", TestUtil::TestSourceDir());
Importer importer(&source_tree, &error_collector);
// Import (parse) unittest.proto.
const FileDescriptor* parsed_descriptor =
- importer.Import(UNITTEST_PROTO_PATH);
+ importer.Import(TestUtil::MaybeTranslatePath(UNITTEST_PROTO_PATH));
EXPECT_EQ("", error_collector.text_);
ASSERT_TRUE(parsed_descriptor != NULL);
@@ -165,21 +171,6 @@ TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) {
&message.optional_import_message());
}
-#ifndef PROTOBUF_USE_DLLS
-TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) {
- EXPECT_EQ("971", Int32ToString(971));
- EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min));
- EXPECT_EQ("2147483647", Int32ToString(kint32max));
-}
-
-TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) {
- EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971));
- EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min));
- EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min));
- EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max));
-}
-#endif // !PROTOBUF_USE_DLLS
-
TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) {
const UNITTEST::TestExtremeDefaultValues& extreme_default =
UNITTEST::TestExtremeDefaultValues::default_instance();
@@ -214,7 +205,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) {
const UNITTEST::TestExtremeDefaultValues& extreme_default =
UNITTEST::TestExtremeDefaultValues::default_instance();
EXPECT_EQ(~0x7fffffff, kint32min);
- EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min);
+ EXPECT_EQ(PROTOBUF_LONGLONG(~0x7fffffffffffffff), kint64min);
EXPECT_EQ(kint32min, extreme_default.really_small_int32());
EXPECT_EQ(kint64min, extreme_default.really_small_int64());
}
@@ -667,8 +658,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) {
TestUtil::ExpectAllFieldsSet(message2);
}
-#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
- !defined(GOOGLE_PROTOBUF_NO_RTTI)
+#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI
TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) {
// Test the CopyFrom method that takes in the generic const Message&
// parameter.
@@ -676,7 +666,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) {
TestUtil::SetAllFields(&message1);
- const Message* source = implicit_cast<const Message*>(&message1);
+ const Message* source = ::google::protobuf::implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
TestUtil::ExpectAllFieldsSet(message2);
@@ -709,7 +699,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) {
TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) {
// Test merging with a non-empty message. Code is a modified form
- // of that found in google/protobuf/reflection_ops_unittest.cc.
+ // of that found in net/proto2/internal/reflection_ops_unittest.cc.
UNITTEST::TestAllTypes message1, message2;
TestUtil::SetAllFields(&message1);
@@ -741,7 +731,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) {
TestUtil::SetAllFields(&message1);
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -755,7 +745,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) {
TestUtil::SetPackedFields(&packed_message1);
int packed_size = packed_message1.ByteSizeLong();
packed_data.resize(packed_size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&packed_data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&packed_data));
uint8* end = packed_message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(packed_size, end - start);
EXPECT_TRUE(packed_message2.ParseFromString(packed_data));
@@ -772,7 +762,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) {
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -791,7 +781,7 @@ TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) {
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -1872,7 +1862,7 @@ TEST_F(OneofTest, CopyAssignmentOperator) {
EXPECT_EQ(message2.foo_message().qux_int(), 123);
// Make sure that self-assignment does something sane.
- message2 = message2;
+ message2 = *&message2; // Avoid -Wself-assign.
EXPECT_EQ(message2.foo_message().qux_int(), 123);
}
@@ -1883,7 +1873,7 @@ TEST_F(OneofTest, UpcastCopyFrom) {
message1.mutable_foogroup()->set_a(123);
EXPECT_TRUE(message1.has_foogroup());
- const Message* source = implicit_cast<const Message*>(&message1);
+ const Message* source = ::google::protobuf::implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
EXPECT_TRUE(message2.has_foogroup());
@@ -1902,7 +1892,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.set_foo_int(123);
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1916,7 +1906,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.set_foo_string("foo");
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1931,7 +1921,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.set_foo_bytes("qux");
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1945,7 +1935,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.set_foo_enum(UNITTEST::TestOneof2::FOO);
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1959,7 +1949,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.mutable_foo_message()->set_qux_int(234);
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1973,7 +1963,7 @@ TEST_F(OneofTest, SerializationToArray) {
message1.mutable_foogroup()->set_a(345);
int size = message1.ByteSizeLong();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -1998,7 +1988,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2019,7 +2009,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2041,7 +2031,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2062,7 +2052,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2083,7 +2073,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2104,7 +2094,7 @@ TEST_F(OneofTest, SerializationToStream) {
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2161,7 +2151,7 @@ TEST_F(OneofTest, MergeFrom) {
TEST(HELPERS_TEST_NAME, TestSCC) {
UNITTEST::TestMutualRecursionA a;
- SCCAnalyzer scc_analyzer((Options()));
+ MessageSCCAnalyzer scc_analyzer((Options()));
const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor());
std::vector<string> names;
for (int i = 0; i < scc->descriptors.size(); i++) {
@@ -2185,7 +2175,7 @@ TEST(HELPERS_TEST_NAME, TestSCC) {
TEST(HELPERS_TEST_NAME, TestSCCAnalysis) {
{
UNITTEST::TestRecursiveMessage msg;
- SCCAnalyzer scc_analyzer((Options()));
+ MessageSCCAnalyzer scc_analyzer((Options()));
const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
EXPECT_EQ(result.is_recursive, true);
@@ -2195,7 +2185,7 @@ TEST(HELPERS_TEST_NAME, TestSCCAnalysis) {
}
{
UNITTEST::TestAllExtensions msg;
- SCCAnalyzer scc_analyzer((Options()));
+ MessageSCCAnalyzer scc_analyzer((Options()));
const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
EXPECT_EQ(result.is_recursive, false);
@@ -2205,7 +2195,7 @@ TEST(HELPERS_TEST_NAME, TestSCCAnalysis) {
}
{
UNITTEST::TestRequired msg;
- SCCAnalyzer scc_analyzer((Options()));
+ MessageSCCAnalyzer scc_analyzer((Options()));
const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor());
MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc);
EXPECT_EQ(result.is_recursive, false);
@@ -2269,8 +2259,8 @@ TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) {
#endif
EXPECT_EQ(should_have_descriptors,
- DescriptorPool::generated_pool()->InternalIsFileLoaded(
- UNITTEST_PROTO_PATH));
+ DescriptorPool::generated_pool()->InternalIsFileLoaded(
+ TestUtil::MaybeTranslatePath(UNITTEST_PROTO_PATH)));
}
} // namespace cpp_unittest
@@ -2279,3 +2269,5 @@ TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) {
} // namespace compiler
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc
index 2ad4edd2..77636fe9 100644
--- a/src/google/protobuf/compiler/cpp/metadata_test.cc
+++ b/src/google/protobuf/compiler/cpp/metadata_test.cc
@@ -42,11 +42,12 @@
#include <gtest/gtest.h>
namespace google {
-namespace atu = ::google::protobuf::compiler::annotation_test_util;
-
namespace protobuf {
namespace compiler {
namespace cpp {
+
+namespace atu = annotation_test_util;
+
namespace {
class CppMetadataTest : public ::testing::Test {
@@ -59,7 +60,7 @@ class CppMetadataTest : public ::testing::Test {
string* pb_h, GeneratedCodeInfo* pb_h_info,
string* proto_h, GeneratedCodeInfo* proto_h_info,
string* pb_cc) {
- google::protobuf::compiler::CommandLineInterface cli;
+ CommandLineInterface cli;
CppGenerator cpp_generator;
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
string cpp_out =
diff --git a/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
index 8c38e52f..33c56198 100644
--- a/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc
@@ -90,7 +90,7 @@ class MockGeneratorContext : public GeneratorContext {
string actual_contents;
GOOGLE_CHECK_OK(
- File::GetContents(TestSourceDir() + "/" + physical_filename,
+ File::GetContentsAsText(TestSourceDir() + "/" + physical_filename,
&actual_contents, true))
<< "Unable to get " << physical_filename;
EXPECT_TRUE(actual_contents == *expected_contents)
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.h b/src/google/protobuf/compiler/csharp/csharp_enum.h
index 8925cdf2..5170d839 100644
--- a/src/google/protobuf/compiler/csharp/csharp_enum.h
+++ b/src/google/protobuf/compiler/csharp/csharp_enum.h
@@ -35,6 +35,8 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/csharp/csharp_source_generator_base.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.h b/src/google/protobuf/compiler/csharp/csharp_field_base.h
index df26853b..62c25517 100644
--- a/src/google/protobuf/compiler/csharp/csharp_field_base.h
+++ b/src/google/protobuf/compiler/csharp/csharp_field_base.h
@@ -36,6 +36,8 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/csharp/csharp_source_generator_base.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.h b/src/google/protobuf/compiler/csharp/csharp_generator.h
index c8b19529..dc7319b1 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.h
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.h
@@ -37,6 +37,8 @@
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -46,9 +48,9 @@ namespace csharp {
// header. If you create your own protocol compiler binary and you want
// it to support C# output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT Generator
+class PROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
-public:
+ public:
virtual bool Generate(
const FileDescriptor* file,
const string& parameter,
@@ -61,4 +63,6 @@ public:
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.cc b/src/google/protobuf/compiler/csharp/csharp_helpers.cc
index 5bca1ffa..04b61074 100644
--- a/src/google/protobuf/compiler/csharp/csharp_helpers.cc
+++ b/src/google/protobuf/compiler/csharp/csharp_helpers.cc
@@ -169,7 +169,7 @@ std::string UnderscoresToCamelCase(const std::string& input,
}
}
// Add a trailing "_" if the name should be altered.
- if (input[input.size() - 1] == '#') {
+ if (input.size() > 0 && input[input.size() - 1] == '#') {
result += '_';
}
return result;
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.h b/src/google/protobuf/compiler/csharp/csharp_helpers.h
index c317ad0e..ec0b1c77 100644
--- a/src/google/protobuf/compiler/csharp/csharp_helpers.h
+++ b/src/google/protobuf/compiler/csharp/csharp_helpers.h
@@ -42,6 +42,8 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/io/printer.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -96,7 +98,8 @@ std::string UnderscoresToPascalCase(const std::string& input);
// Note that we wouldn't normally want to export this (we're not expecting
// it to be used outside libprotoc itself) but this exposes it for testing.
-std::string LIBPROTOBUF_EXPORT GetEnumValueName(const std::string& enum_name, const std::string& enum_value_name);
+std::string PROTOC_EXPORT GetEnumValueName(const std::string& enum_name,
+ const std::string& enum_value_name);
// TODO(jtattermusch): perhaps we could move this to strutil
std::string StringToBase64(const std::string& input);
@@ -145,4 +148,7 @@ inline bool IsWrapperType(const FieldDescriptor* descriptor) {
} // namespace compiler
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__
diff --git a/src/google/protobuf/compiler/csharp/csharp_names.h b/src/google/protobuf/compiler/csharp/csharp_names.h
index 21758f28..87a16515 100644
--- a/src/google/protobuf/compiler/csharp/csharp_names.h
+++ b/src/google/protobuf/compiler/csharp/csharp_names.h
@@ -41,6 +41,8 @@
#include <string>
#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -57,14 +59,14 @@ namespace csharp {
//
// Returns:
// The namespace to use for given file descriptor.
-string LIBPROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor);
+string PROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor);
// Requires:
// descriptor != NULL
//
// Returns:
// The fully-qualified C# class name.
-string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor);
+string PROTOC_EXPORT GetClassName(const Descriptor* descriptor);
// Requires:
// descriptor != NULL
@@ -73,7 +75,7 @@ string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor);
// The fully-qualified name of the C# class that provides
// access to the file descriptor. Proto compiler generates
// such class for each .proto file processed.
-string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor);
+string PROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor);
// Generates output file name for given file descriptor. If generate_directories
// is true, the output file will be put under directory corresponding to file's
@@ -89,16 +91,16 @@ string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor)
// The file name to use as output file for given file descriptor. In case
// of failure, this function will return empty string and error parameter
// will contain the error message.
-string LIBPROTOC_EXPORT GetOutputFile(
- const google::protobuf::FileDescriptor* descriptor,
- const string file_extension,
- const bool generate_directories,
- const string base_namespace,
- string* error);
+string PROTOC_EXPORT
+GetOutputFile(const google::protobuf::FileDescriptor* descriptor,
+ const string file_extension, const bool generate_directories,
+ const string base_namespace, string* error);
} // namespace csharp
} // namespace compiler
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_NAMES_H__
diff --git a/src/google/protobuf/compiler/csharp/csharp_reflection_class.h b/src/google/protobuf/compiler/csharp/csharp_reflection_class.h
index e0c69f31..3291d65b 100644
--- a/src/google/protobuf/compiler/csharp/csharp_reflection_class.h
+++ b/src/google/protobuf/compiler/csharp/csharp_reflection_class.h
@@ -35,6 +35,8 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/csharp/csharp_source_generator_base.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h
index c741080e..790fb1be 100644
--- a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h
+++ b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h
@@ -34,6 +34,7 @@
#include <string>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/io/printer.h>
namespace google {
namespace protobuf {
diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc
index c3831e72..58498aaa 100644
--- a/src/google/protobuf/compiler/importer.cc
+++ b/src/google/protobuf/compiler/importer.cc
@@ -103,7 +103,7 @@ class SourceTreeDescriptorDatabase::SingleFileErrorCollector
bool had_errors() { return had_errors_; }
// implements ErrorCollector ---------------------------------------
- void AddError(int line, int column, const string& message) {
+ void AddError(int line, int column, const string& message) override {
if (multi_file_error_collector_ != NULL) {
multi_file_error_collector_->AddError(filename_, line, column, message);
}
diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h
index a4ffcf87..cf6b0123 100644
--- a/src/google/protobuf/compiler/importer.h
+++ b/src/google/protobuf/compiler/importer.h
@@ -45,6 +45,8 @@
#include <google/protobuf/descriptor_database.h>
#include <google/protobuf/compiler/parser.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -73,7 +75,7 @@ class DiskSourceTree;
//
// Note: This class does not implement FindFileContainingSymbol() or
// FindFileContainingExtension(); these will always return false.
-class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
+class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase {
public:
SourceTreeDescriptorDatabase(SourceTree* source_tree);
~SourceTreeDescriptorDatabase();
@@ -96,12 +98,13 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas
}
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename, FileDescriptorProto* output);
- bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileByName(const std::string& filename,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingSymbol(const std::string& symbol_name,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
private:
class SingleFileErrorCollector;
@@ -109,23 +112,20 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas
SourceTree* source_tree_;
MultiFileErrorCollector* error_collector_;
- class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector {
+ class PROTOBUF_EXPORT ValidationErrorCollector
+ : public DescriptorPool::ErrorCollector {
public:
ValidationErrorCollector(SourceTreeDescriptorDatabase* owner);
~ValidationErrorCollector();
// implements ErrorCollector ---------------------------------------
- void AddError(const string& filename,
- const string& element_name,
- const Message* descriptor,
- ErrorLocation location,
- const string& message);
-
- virtual void AddWarning(const string& filename,
- const string& element_name,
- const Message* descriptor,
- ErrorLocation location,
- const string& message);
+ void AddError(const std::string& filename, const std::string& element_name,
+ const Message* descriptor, ErrorLocation location,
+ const std::string& message) override;
+
+ void AddWarning(const std::string& filename, const std::string& element_name,
+ const Message* descriptor, ErrorLocation location,
+ const std::string& message) override;
private:
SourceTreeDescriptorDatabase* owner_;
@@ -145,7 +145,7 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas
// You may find that SourceTreeDescriptorDatabase is more flexible.
//
// TODO(kenton): I feel like this class is not well-named.
-class LIBPROTOBUF_EXPORT Importer {
+class PROTOBUF_EXPORT Importer {
public:
Importer(SourceTree* source_tree,
MultiFileErrorCollector* error_collector);
@@ -164,7 +164,7 @@ class LIBPROTOBUF_EXPORT Importer {
// you want to see errors for the same files repeatedly, you can use a
// separate Importer object to import each one (but use the same
// DescriptorPool so that they can be cross-linked).
- const FileDescriptor* Import(const string& filename);
+ const FileDescriptor* Import(const std::string& filename);
// The DescriptorPool in which all imported FileDescriptors and their
// contents are stored.
@@ -172,7 +172,7 @@ class LIBPROTOBUF_EXPORT Importer {
return &pool_;
}
- void AddUnusedImportTrackFile(const string& file_name);
+ void AddUnusedImportTrackFile(const std::string& file_name);
void ClearUnusedImportTrackFiles();
@@ -185,18 +185,18 @@ class LIBPROTOBUF_EXPORT Importer {
// If the importer encounters problems while trying to import the proto files,
// it reports them to a MultiFileErrorCollector.
-class LIBPROTOBUF_EXPORT MultiFileErrorCollector {
+class PROTOBUF_EXPORT MultiFileErrorCollector {
public:
inline MultiFileErrorCollector() {}
virtual ~MultiFileErrorCollector();
// Line and column numbers are zero-based. A line number of -1 indicates
// an error with the entire file (e.g. "not found").
- virtual void AddError(const string& filename, int line, int column,
- const string& message) = 0;
+ virtual void AddError(const std::string& filename, int line, int column,
+ const std::string& message) = 0;
- virtual void AddWarning(const string& filename, int line, int column,
- const string& message) {}
+ virtual void AddWarning(const std::string& filename, int line, int column,
+ const std::string& message) {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector);
@@ -206,7 +206,7 @@ class LIBPROTOBUF_EXPORT MultiFileErrorCollector {
// Used by the default implementation of Importer to resolve import statements
// Most users will probably want to use the DiskSourceTree implementation,
// below.
-class LIBPROTOBUF_EXPORT SourceTree {
+class PROTOBUF_EXPORT SourceTree {
public:
inline SourceTree() {}
virtual ~SourceTree();
@@ -215,14 +215,14 @@ class LIBPROTOBUF_EXPORT SourceTree {
// found. The caller takes ownership of the returned object. The filename
// must be a path relative to the root of the source tree and must not
// contain "." or ".." components.
- virtual io::ZeroCopyInputStream* Open(const string& filename) = 0;
+ virtual io::ZeroCopyInputStream* Open(const std::string& filename) = 0;
// If Open() returns NULL, calling this method immediately will return an
// description of the error.
// Subclasses should implement this method and return a meaningful value for
// better error reporting.
// TODO(xiaofeng): change this to a pure virtual function.
- virtual string GetLastErrorMessage();
+ virtual std::string GetLastErrorMessage();
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree);
@@ -231,7 +231,7 @@ class LIBPROTOBUF_EXPORT SourceTree {
// An implementation of SourceTree which loads files from locations on disk.
// Multiple mappings can be set up to map locations in the DiskSourceTree to
// locations in the physical filesystem.
-class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
+class PROTOBUF_EXPORT DiskSourceTree : public SourceTree {
public:
DiskSourceTree();
~DiskSourceTree();
@@ -252,7 +252,7 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
//
// disk_path may be an absolute path or relative to the current directory,
// just like a path you'd pass to open().
- void MapPath(const string& virtual_path, const string& disk_path);
+ void MapPath(const std::string& virtual_path, const std::string& disk_path);
// Return type for DiskFileToVirtualFile().
enum DiskFileToVirtualFileResult {
@@ -283,45 +283,47 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree {
// * NO_MAPPING: Indicates that no mapping was found which contains this
// file.
DiskFileToVirtualFileResult
- DiskFileToVirtualFile(const string& disk_file,
- string* virtual_file,
- string* shadowing_disk_file);
+ DiskFileToVirtualFile(const std::string& disk_file,
+ std::string* virtual_file,
+ std::string* shadowing_disk_file);
// Given a virtual path, find the path to the file on disk.
// Return true and update disk_file with the on-disk path if the file exists.
// Return false and leave disk_file untouched if the file doesn't exist.
- bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file);
+ bool VirtualFileToDiskFile(const std::string& virtual_file, std::string* disk_file);
// implements SourceTree -------------------------------------------
- virtual io::ZeroCopyInputStream* Open(const string& filename);
+ io::ZeroCopyInputStream* Open(const std::string& filename) override;
- virtual string GetLastErrorMessage();
+ std::string GetLastErrorMessage() override;
private:
struct Mapping {
- string virtual_path;
- string disk_path;
+ std::string virtual_path;
+ std::string disk_path;
- inline Mapping(const string& virtual_path_param,
- const string& disk_path_param)
+ inline Mapping(const std::string& virtual_path_param,
+ const std::string& disk_path_param)
: virtual_path(virtual_path_param), disk_path(disk_path_param) {}
};
std::vector<Mapping> mappings_;
- string last_error_message_;
+ std::string last_error_message_;
// Like Open(), but returns the on-disk path in disk_file if disk_file is
// non-NULL and the file could be successfully opened.
- io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file,
- string* disk_file);
+ io::ZeroCopyInputStream* OpenVirtualFile(const std::string& virtual_file,
+ std::string* disk_file);
// Like Open() but given the actual on-disk path.
- io::ZeroCopyInputStream* OpenDiskFile(const string& filename);
+ io::ZeroCopyInputStream* OpenDiskFile(const std::string& filename);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree);
};
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__
diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc
index 73bef3f4..5108809d 100644
--- a/src/google/protobuf/compiler/importer_unittest.cc
+++ b/src/google/protobuf/compiler/importer_unittest.cc
@@ -34,8 +34,8 @@
#include <google/protobuf/compiler/importer.h>
-#include <google/protobuf/stubs/hash.h>
#include <memory>
+#include <unordered_map>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -112,7 +112,7 @@ class MockSourceTree : public SourceTree {
}
private:
- hash_map<string, const char*> files_;
+ std::unordered_map<string, const char*> files_;
};
// ===================================================================
diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/java_context.h
index 9de7415a..fd41a270 100644
--- a/src/google/protobuf/compiler/java/java_context.h
+++ b/src/google/protobuf/compiler/java/java_context.h
@@ -51,7 +51,9 @@ namespace protobuf {
}
}
} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -106,6 +108,6 @@ class Context {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__
diff --git a/src/google/protobuf/compiler/java/java_doc_comment.h b/src/google/protobuf/compiler/java/java_doc_comment.h
index 7d9535c9..ef9b3a90 100644
--- a/src/google/protobuf/compiler/java/java_doc_comment.h
+++ b/src/google/protobuf/compiler/java/java_doc_comment.h
@@ -37,13 +37,17 @@
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
- namespace io {
- class Printer; // printer.h
- }
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -59,11 +63,13 @@ void WriteMethodDocComment(io::Printer* printer,
const MethodDescriptor* method);
// Exposed for testing only.
-LIBPROTOC_EXPORT string EscapeJavadoc(const string& input);
+PROTOC_EXPORT std::string EscapeJavadoc(const std::string& input);
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__
diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/java_enum.cc
index bef69f1a..1ca7ba95 100644
--- a/src/google/protobuf/compiler/java/java_enum.cc
+++ b/src/google/protobuf/compiler/java/java_enum.cc
@@ -190,10 +190,9 @@ void EnumGenerator::Generate(io::Printer* printer) {
printer->Indent();
for (int i = 0; i < canonical_values_.size(); i++) {
- printer->Print(
- "case $number$: return $name$;\n",
- "name", canonical_values_[i]->name(),
- "number", SimpleItoa(canonical_values_[i]->number()));
+ printer->Print("case $number$: return $name$;\n", "name",
+ canonical_values_[i]->name(), "number",
+ SimpleItoa(canonical_values_[i]->number()));
}
printer->Outdent();
@@ -242,19 +241,22 @@ void EnumGenerator::Generate(io::Printer* printer) {
// extensions in both the mutable and immutable cases. (In the mutable api
// this is accomplished by attempting to load the immutable outer class).
printer->Print(
- " return $file$.getDescriptor().getEnumTypes().get($index$);\n",
- "file", name_resolver_->GetClassName(descriptor_->file(),
- immutable_api_),
- "index", SimpleItoa(descriptor_->index()));
+ " return $file$.getDescriptor().getEnumTypes().get($index$);\n",
+ "file",
+ name_resolver_->GetClassName(descriptor_->file(), immutable_api_),
+ "index", SimpleItoa(descriptor_->index()));
} else {
printer->Print(
" return $parent$.$descriptor$.getEnumTypes().get($index$);\n",
- "parent", name_resolver_->GetClassName(descriptor_->containing_type(),
- immutable_api_),
- "descriptor", descriptor_->containing_type()->options()
- .no_standard_descriptor_accessor()
- ? "getDefaultInstance().getDescriptorForType()"
- : "getDescriptor()",
+ "parent",
+ name_resolver_->GetClassName(descriptor_->containing_type(),
+ immutable_api_),
+ "descriptor",
+ descriptor_->containing_type()
+ ->options()
+ .no_standard_descriptor_accessor()
+ ? "getDefaultInstance().getDescriptorForType()"
+ : "getDescriptor()",
"index", SimpleItoa(descriptor_->index()));
}
diff --git a/src/google/protobuf/compiler/java/java_enum.h b/src/google/protobuf/compiler/java/java_enum.h
index 13dfc32d..d650924c 100644
--- a/src/google/protobuf/compiler/java/java_enum.h
+++ b/src/google/protobuf/compiler/java/java_enum.h
@@ -41,17 +41,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
+namespace compiler {
+ namespace java {
+ class Context; // context.h
+ class ClassNameResolver; // name_resolver.h
}
}
+namespace io {
+ class Printer; // printer.h
+}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -67,9 +69,9 @@ class EnumGenerator {
private:
const EnumDescriptor* descriptor_;
- // The proto language allows multiple enum constants to have the same numeric
- // value. Java, however, does not allow multiple enum constants to be
- // considered equivalent. We treat the first defined constant for any
+ // The proto language allows multiple enum constants to have the same
+ // numeric value. Java, however, does not allow multiple enum constants to
+ // be considered equivalent. We treat the first defined constant for any
// given numeric value as "canonical" and the rest as aliases of that
// canonical value.
std::vector<const EnumValueDescriptor*> canonical_values_;
@@ -93,6 +95,6 @@ class EnumGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__
diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/java_enum_field.cc
index 0686ea0f..9d0bcd2c 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field.cc
@@ -66,10 +66,10 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
(*variables)["mutable_type"] =
name_resolver->GetMutableClassName(descriptor->enum_type());
(*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
- (*variables)["default_number"] = SimpleItoa(
- descriptor->default_value_enum()->number());
- (*variables)["tag"] =
- SimpleItoa(static_cast<int32>(internal::WireFormat::MakeTag(descriptor)));
+ (*variables)["default_number"] =
+ SimpleItoa(descriptor->default_value_enum()->number());
+ (*variables)["tag"] = SimpleItoa(
+ static_cast<int32>(internal::WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = SimpleItoa(
internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
// TODO(birdo): Add @deprecated javadoc when generating javadoc is supported
diff --git a/src/google/protobuf/compiler/java/java_enum_field.h b/src/google/protobuf/compiler/java/java_enum_field.h
index 924ff281..723102d8 100644
--- a/src/google/protobuf/compiler/java/java_enum_field.h
+++ b/src/google/protobuf/compiler/java/java_enum_field.h
@@ -41,26 +41,29 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator {
public:
- explicit ImmutableEnumFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableEnumFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, int builderBitIndex,
+ Context* context);
~ImmutableEnumFieldGenerator();
- // implements ImmutableFieldGenerator ---------------------------------------
+ // implements ImmutableFieldGenerator
+ // ---------------------------------------
int GetNumBitsForMessage() const;
int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
@@ -78,11 +81,11 @@ class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -94,9 +97,9 @@ class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator {
class ImmutableEnumOneofFieldGenerator : public ImmutableEnumFieldGenerator {
public:
- ImmutableEnumOneofFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableEnumOneofFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, int builderBitIndex,
+ Context* context);
~ImmutableEnumOneofFieldGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -139,11 +142,11 @@ class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -155,6 +158,6 @@ class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__
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 f1fe71b0..353a2f6e 100644
--- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_field_lite.cc
@@ -66,10 +66,10 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
(*variables)["mutable_type"] =
name_resolver->GetMutableClassName(descriptor->enum_type());
(*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
- (*variables)["default_number"] = SimpleItoa(
- descriptor->default_value_enum()->number());
- (*variables)["tag"] =
- SimpleItoa(static_cast<int32>(internal::WireFormat::MakeTag(descriptor)));
+ (*variables)["default_number"] =
+ SimpleItoa(descriptor->default_value_enum()->number());
+ (*variables)["tag"] = SimpleItoa(
+ static_cast<int32>(internal::WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = SimpleItoa(
internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
// TODO(birdo): Add @deprecated javadoc when generating javadoc is supported
@@ -120,14 +120,12 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
ImmutableEnumFieldLiteGenerator::
ImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor,
int messageBitIndex,
- int builderBitIndex,
Context* context)
: descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex),
- name_resolver_(context->GetNameResolver()) {
- SetEnumVariables(descriptor, messageBitIndex, builderBitIndex,
- context->GetFieldGeneratorInfo(descriptor),
- name_resolver_, &variables_);
+ context_(context), name_resolver_(context->GetNameResolver()) {
+ SetEnumVariables(descriptor, messageBitIndex, 0,
+ context->GetFieldGeneratorInfo(descriptor), name_resolver_,
+ &variables_);
}
ImmutableEnumFieldLiteGenerator::~ImmutableEnumFieldLiteGenerator() {}
@@ -136,10 +134,6 @@ int ImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const {
return 1;
}
-int ImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void ImmutableEnumFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
@@ -363,13 +357,9 @@ string ImmutableEnumFieldLiteGenerator::GetBoxedType() const {
// ===================================================================
-ImmutableEnumOneofFieldLiteGenerator::
-ImmutableEnumOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableEnumFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
+ImmutableEnumOneofFieldLiteGenerator::ImmutableEnumOneofFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context)
+ : ImmutableEnumFieldLiteGenerator(descriptor, messageBitIndex, context) {
const OneofGeneratorInfo* info =
context->GetOneofGeneratorInfo(descriptor->containing_oneof());
SetCommonOneofVariables(descriptor, info, &variables_);
@@ -570,16 +560,16 @@ GenerateHashCode(io::Printer* printer) const {
// ===================================================================
RepeatedImmutableEnumFieldLiteGenerator::
-RepeatedImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetEnumVariables(descriptor, messageBitIndex, builderBitIndex,
- context->GetFieldGeneratorInfo(descriptor),
- name_resolver_, &variables_);
+ RepeatedImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetEnumVariables(descriptor, messageBitIndex, 0,
+ context->GetFieldGeneratorInfo(descriptor), name_resolver_,
+ &variables_);
}
RepeatedImmutableEnumFieldLiteGenerator::
@@ -589,10 +579,6 @@ int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const {
return 0;
}
-int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void RepeatedImmutableEnumFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.h b/src/google/protobuf/compiler/java/java_enum_field_lite.h
index fa004720..bf25ffaa 100644
--- a/src/google/protobuf/compiler/java/java_enum_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_enum_field_lite.h
@@ -41,28 +41,30 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator {
public:
- explicit ImmutableEnumFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutableEnumFieldLiteGenerator();
- // implements ImmutableFieldLiteGenerator ------------------------------------
+ // implements ImmutableFieldLiteGenerator
+ // ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -77,13 +79,12 @@ class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -94,9 +95,8 @@ class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator {
class ImmutableEnumOneofFieldLiteGenerator
: public ImmutableEnumFieldLiteGenerator {
public:
- ImmutableEnumOneofFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableEnumOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, Context* context);
~ImmutableEnumOneofFieldLiteGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -116,13 +116,11 @@ class RepeatedImmutableEnumFieldLiteGenerator
: public ImmutableFieldLiteGenerator {
public:
explicit RepeatedImmutableEnumFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context);
~RepeatedImmutableEnumFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -138,13 +136,12 @@ class RepeatedImmutableEnumFieldLiteGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -154,6 +151,6 @@ class RepeatedImmutableEnumFieldLiteGenerator
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/java_enum_lite.cc
index 806008ee..deebe523 100644
--- a/src/google/protobuf/compiler/java/java_enum_lite.cc
+++ b/src/google/protobuf/compiler/java/java_enum_lite.cc
@@ -43,6 +43,7 @@
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/map_util.h>
namespace google {
namespace protobuf {
@@ -163,33 +164,47 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
for (int i = 0; i < canonical_values_.size(); i++) {
- printer->Print(
- "case $number$: return $name$;\n",
- "name", canonical_values_[i]->name(),
- "number", SimpleItoa(canonical_values_[i]->number()));
+ printer->Print("case $number$: return $name$;\n", "name",
+ canonical_values_[i]->name(), "number",
+ SimpleItoa(canonical_values_[i]->number()));
}
printer->Outdent();
printer->Outdent();
printer->Print(
- " default: return null;\n"
- " }\n"
- "}\n"
- "\n"
- "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n"
- " internalGetValueMap() {\n"
- " return internalValueMap;\n"
- "}\n"
- "private static final com.google.protobuf.Internal.EnumLiteMap<\n"
- " $classname$> internalValueMap =\n"
- " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n"
- " @java.lang.Override\n"
- " public $classname$ findValueByNumber(int number) {\n"
- " return $classname$.forNumber(number);\n"
- " }\n"
- " };\n"
- "\n",
- "classname", descriptor_->name());
+ " default: return null;\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n"
+ " internalGetValueMap() {\n"
+ " return internalValueMap;\n"
+ "}\n"
+ "private static final com.google.protobuf.Internal.EnumLiteMap<\n"
+ " $classname$> internalValueMap =\n"
+ " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n"
+ " @java.lang.Override\n"
+ " public $classname$ findValueByNumber(int number) {\n"
+ " return $classname$.forNumber(number);\n"
+ " }\n"
+ " };\n"
+ "\n"
+ "public static com.google.protobuf.Internal.EnumVerifier \n"
+ " internalGetVerifier() {\n"
+ " return $classname$Verifier.INSTANCE;\n"
+ "}\n"
+ "\n"
+ "private static final class $classname$Verifier implements \n"
+ " com.google.protobuf.Internal.EnumVerifier { \n"
+ " static final com.google.protobuf.Internal.EnumVerifier "
+ " INSTANCE = new $classname$Verifier();\n"
+ " @java.lang.Override\n"
+ " public boolean isInRange(int number) {\n"
+ " return $classname$.forNumber(number) != null;\n"
+ " }\n"
+ " };\n"
+ "\n",
+ "classname", descriptor_->name());
printer->Print(
"private final int value;\n\n"
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.h b/src/google/protobuf/compiler/java/java_enum_lite.h
index b7be912c..9e20e6fb 100644
--- a/src/google/protobuf/compiler/java/java_enum_lite.h
+++ b/src/google/protobuf/compiler/java/java_enum_lite.h
@@ -41,17 +41,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
+namespace compiler {
+ namespace java {
+ class Context; // context.h
+ class ClassNameResolver; // name_resolver.h
}
}
+namespace io {
+ class Printer; // printer.h
+}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -67,9 +69,9 @@ class EnumLiteGenerator {
private:
const EnumDescriptor* descriptor_;
- // The proto language allows multiple enum constants to have the same numeric
- // value. Java, however, does not allow multiple enum constants to be
- // considered equivalent. We treat the first defined constant for any
+ // The proto language allows multiple enum constants to have the same
+ // numeric value. Java, however, does not allow multiple enum constants to
+ // be considered equivalent. We treat the first defined constant for any
// given numeric value as "canonical" and the rest as aliases of that
// canonical value.
std::vector<const EnumValueDescriptor*> canonical_values_;
@@ -93,6 +95,6 @@ class EnumLiteGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/java_extension.cc
index 3eb1370d..1ee97710 100644
--- a/src/google/protobuf/compiler/java/java_extension.cc
+++ b/src/google/protobuf/compiler/java/java_extension.cc
@@ -151,8 +151,8 @@ int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode(
// Only applies to non-nested extensions.
printer->Print(
"$name$.internalInit(descriptor.getExtensions().get($index$));\n",
- "name", UnderscoresToCamelCase(descriptor_),
- "index", SimpleItoa(descriptor_->index()));
+ "name", UnderscoresToCamelCase(descriptor_), "index",
+ SimpleItoa(descriptor_->index()));
bytecode_estimate += 21;
}
return bytecode_estimate;
diff --git a/src/google/protobuf/compiler/java/java_extension.h b/src/google/protobuf/compiler/java/java_extension.h
index fb8d5201..1f11324c 100644
--- a/src/google/protobuf/compiler/java/java_extension.h
+++ b/src/google/protobuf/compiler/java/java_extension.h
@@ -42,18 +42,20 @@
namespace google {
namespace protobuf {
- class FieldDescriptor; // descriptor.h
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+class FieldDescriptor; // descriptor.h
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -68,18 +70,19 @@ class ExtensionGenerator {
virtual void Generate(io::Printer* printer) = 0;
- // Returns an estimate of the number of bytes the printed code will compile to
+ // Returns an estimate of the number of bytes the printed code will compile
+ // to
virtual int GenerateNonNestedInitializationCode(io::Printer* printer) = 0;
- // Returns an estimate of the number of bytes the printed code will compile to
+ // Returns an estimate of the number of bytes the printed code will compile
+ // to
virtual int GenerateRegistrationCode(io::Printer* printer) = 0;
protected:
static void InitTemplateVars(const FieldDescriptor* descriptor,
- const string& scope,
- bool immutable,
+ const std::string& scope, bool immutable,
ClassNameResolver* name_resolver,
- std::map<string, string>* vars_pointer);
+ std::map<std::string, std::string>* vars_pointer);
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
@@ -99,7 +102,7 @@ class ImmutableExtensionGenerator : public ExtensionGenerator {
const FieldDescriptor* descriptor_;
Context* context_;
ClassNameResolver* name_resolver_;
- string scope_;
+ std::string scope_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionGenerator);
@@ -108,6 +111,6 @@ class ImmutableExtensionGenerator : public ExtensionGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__
diff --git a/src/google/protobuf/compiler/java/java_extension_lite.h b/src/google/protobuf/compiler/java/java_extension_lite.h
index 4cd49bda..eaa90a4b 100644
--- a/src/google/protobuf/compiler/java/java_extension_lite.h
+++ b/src/google/protobuf/compiler/java/java_extension_lite.h
@@ -63,7 +63,7 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator {
const FieldDescriptor* descriptor_;
Context* context_;
ClassNameResolver* name_resolver_;
- string scope_;
+ std::string scope_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionLiteGenerator);
};
@@ -71,6 +71,6 @@ class ImmutableExtensionLiteGenerator : public ExtensionGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/java_field.cc
index 93de0229..fec20a7f 100644
--- a/src/google/protobuf/compiler/java/java_field.cc
+++ b/src/google/protobuf/compiler/java/java_field.cc
@@ -121,58 +121,57 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
}
ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
- const FieldDescriptor* field, int messageBitIndex, int builderBitIndex,
- Context* context) {
+ const FieldDescriptor* field, int messageBitIndex, Context* context) {
if (field->is_repeated()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsMapEntry(field->message_type())) {
- return new ImmutableMapFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ return new ImmutableMapFieldLiteGenerator(field, messageBitIndex,
+ context);
} else {
return new RepeatedImmutableMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
case JAVATYPE_STRING:
return new RepeatedImmutableStringFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
default:
return new RepeatedImmutablePrimitiveFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
}
} else {
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
return new ImmutableMessageOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
case JAVATYPE_STRING:
return new ImmutableStringOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
default:
return new ImmutablePrimitiveOneofFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
}
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
- return new ImmutableMessageFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ return new ImmutableMessageFieldLiteGenerator(field, messageBitIndex,
+ context);
case JAVATYPE_ENUM:
- return new ImmutableEnumFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ return new ImmutableEnumFieldLiteGenerator(field, messageBitIndex,
+ context);
case JAVATYPE_STRING:
- return new ImmutableStringFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ return new ImmutableStringFieldLiteGenerator(field, messageBitIndex,
+ context);
default:
return new ImmutablePrimitiveFieldLiteGenerator(
- field, messageBitIndex, builderBitIndex, context);
+ field, messageBitIndex, context);
}
}
}
@@ -210,9 +209,7 @@ GenerateParsingCodeFromPacked(io::Printer* printer) const {
template <>
FieldGeneratorMap<ImmutableFieldGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
- : descriptor_(descriptor),
- field_generators_(descriptor->field_count()) {
-
+ : descriptor_(descriptor), field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
@@ -232,18 +229,15 @@ FieldGeneratorMap<ImmutableFieldGenerator>::~FieldGeneratorMap() {}
template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
- : descriptor_(descriptor),
- field_generators_(descriptor->field_count()) {
+ : descriptor_(descriptor), field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
- int builderBitIndex = 0;
for (int i = 0; i < descriptor->field_count(); i++) {
ImmutableFieldLiteGenerator* generator = MakeImmutableLiteGenerator(
- descriptor->field(i), messageBitIndex, builderBitIndex, context);
+ descriptor->field(i), messageBitIndex, context);
field_generators_[i].reset(generator);
messageBitIndex += generator->GetNumBitsForMessage();
- builderBitIndex += generator->GetNumBitsForBuilder();
}
}
@@ -276,12 +270,12 @@ void SetCommonOneofVariables(const FieldDescriptor* descriptor,
(*variables)["oneof_capitalized_name"] = info->capitalized_name;
(*variables)["oneof_index"] =
SimpleItoa(descriptor->containing_oneof()->index());
- (*variables)["set_oneof_case_message"] = info->name +
- "Case_ = " + SimpleItoa(descriptor->number());
+ (*variables)["set_oneof_case_message"] =
+ info->name + "Case_ = " + SimpleItoa(descriptor->number());
(*variables)["clear_oneof_case_message"] = info->name +
"Case_ = 0";
- (*variables)["has_oneof_case_message"] = info->name +
- "Case_ == " + SimpleItoa(descriptor->number());
+ (*variables)["has_oneof_case_message"] =
+ info->name + "Case_ == " + SimpleItoa(descriptor->number());
}
void PrintExtraFieldInfo(const std::map<string, string>& variables,
diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/java_field.h
index 7275c099..abefc589 100644
--- a/src/google/protobuf/compiler/java/java_field.h
+++ b/src/google/protobuf/compiler/java/java_field.h
@@ -45,17 +45,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -79,13 +81,13 @@ class ImmutableFieldGenerator {
virtual void GenerateParsingDoneCode(io::Printer* printer) const = 0;
virtual void GenerateSerializationCode(io::Printer* printer) const = 0;
virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0;
- virtual void GenerateFieldBuilderInitializationCode(io::Printer* printer)
- const = 0;
+ virtual void GenerateFieldBuilderInitializationCode(
+ io::Printer* printer) const = 0;
virtual void GenerateEqualsCode(io::Printer* printer) const = 0;
virtual void GenerateHashCode(io::Printer* printer) const = 0;
- virtual string GetBoxedType() const = 0;
+ virtual std::string GetBoxedType() const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldGenerator);
@@ -97,7 +99,6 @@ class ImmutableFieldLiteGenerator {
virtual ~ImmutableFieldLiteGenerator();
virtual int GetNumBitsForMessage() const = 0;
- virtual int GetNumBitsForBuilder() const = 0;
virtual void GenerateInterfaceMembers(io::Printer* printer) const = 0;
virtual void GenerateMembers(io::Printer* printer) const = 0;
virtual void GenerateBuilderMembers(io::Printer* printer) const = 0;
@@ -117,7 +118,7 @@ class ImmutableFieldLiteGenerator {
virtual void GenerateHashCode(io::Printer* printer) const = 0;
- virtual string GetBoxedType() const = 0;
+ virtual std::string GetBoxedType() const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldLiteGenerator);
@@ -170,34 +171,34 @@ FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap();
// Field information used in FieldGeneartors.
struct FieldGeneratorInfo {
- string name;
- string capitalized_name;
- string disambiguated_reason;
+ std::string name;
+ std::string capitalized_name;
+ std::string disambiguated_reason;
};
// Oneof information used in OneofFieldGenerators.
struct OneofGeneratorInfo {
- string name;
- string capitalized_name;
+ std::string name;
+ std::string capitalized_name;
};
// Set some common variables used in variable FieldGenerators.
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
const FieldGeneratorInfo* info,
- std::map<string, string>* variables);
+ std::map<std::string, std::string>* variables);
// Set some common oneof variables used in OneofFieldGenerators.
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
const OneofGeneratorInfo* info,
- std::map<string, string>* variables);
+ std::map<std::string, std::string>* variables);
// Print useful comments before a field's accessors.
-void PrintExtraFieldInfo(const std::map<string, string>& variables,
+void PrintExtraFieldInfo(const std::map<std::string, std::string>& variables,
io::Printer* printer);
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc
index 5583b779..5356512c 100644
--- a/src/google/protobuf/compiler/java/java_file.cc
+++ b/src/google/protobuf/compiler/java/java_file.cc
@@ -172,7 +172,8 @@ void MaybeRestartJavaMethod(io::Printer* printer,
if ((*bytecode_estimate) > bytesPerMethod) {
++(*method_num);
- printer->Print(chain_statement, "method_num", SimpleItoa(*method_num));
+ printer->Print(chain_statement, "method_num",
+ SimpleItoa(*method_num));
printer->Outdent();
printer->Print("}\n");
printer->Print(method_decl, "method_num", SimpleItoa(*method_num));
@@ -231,7 +232,9 @@ bool FileGenerator::Validate(string* error) {
<< "will be ignored by protoc in the future and protoc will always "
<< "generate full runtime code for Java. To use Java Lite runtime, "
<< "users should use the Java Lite plugin instead. See:\n"
- << " https://github.com/google/protobuf/blob/master/java/lite.md";
+ << " "
+ "https://github.com/protocolbuffers/protobuf/blob/master/java/"
+ "lite.md";
}
return true;
}
@@ -545,11 +548,13 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
" $scope$.getExtensions().get($index$),\n"
" (com.google.protobuf.Message) defaultExtensionInstance);\n"
"}\n",
- "scope", scope, "index", SimpleItoa(field->index()), "class",
+ "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()));
+ "scope", scope, "index",
+ SimpleItoa(field->index()));
}
}
printer->Print(
diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/java_file.h
index 78833a45..9dca82bb 100644
--- a/src/google/protobuf/compiler/java/java_file.h
+++ b/src/google/protobuf/compiler/java/java_file.h
@@ -43,22 +43,24 @@
namespace google {
namespace protobuf {
- class FileDescriptor; // descriptor.h
- namespace io {
- class Printer; // printer.h
- }
- namespace compiler {
- class GeneratorContext; // code_generator.h
- namespace java {
- class Context; // context.h
- class MessageGenerator; // message.h
- class GeneratorFactory; // generator_factory.h
- class ExtensionGenerator; // extension.h
- class ClassNameResolver; // name_resolver.h
- }
+class FileDescriptor; // descriptor.h
+namespace io {
+ class Printer; // printer.h
+}
+namespace compiler {
+ class GeneratorContext; // code_generator.h
+ namespace java {
+ class Context; // context.h
+ class MessageGenerator; // message.h
+ class GeneratorFactory; // generator_factory.h
+ class ExtensionGenerator; // extension.h
+ class ClassNameResolver; // name_resolver.h
}
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -72,20 +74,20 @@ class FileGenerator {
// Checks for problems that would otherwise lead to cryptic compile errors.
// Returns true if there are no problems, or writes an error description to
// the given string and returns false otherwise.
- bool Validate(string* error);
+ bool Validate(std::string* error);
void Generate(io::Printer* printer);
// If we aren't putting everything into one file, this will write all the
// files other than the outer file (i.e. one for each message, enum, and
// service type).
- void GenerateSiblings(const string& package_dir,
+ void GenerateSiblings(const std::string& package_dir,
GeneratorContext* generator_context,
- std::vector<string>* file_list,
- std::vector<string>* annotation_list);
+ std::vector<std::string>* file_list,
+ std::vector<std::string>* annotation_list);
- const string& java_package() { return java_package_; }
- const string& classname() { return classname_; }
+ const std::string& java_package() { return java_package_; }
+ const std::string& classname() { return classname_; }
private:
void GenerateDescriptorInitializationCodeForImmutable(io::Printer* printer);
@@ -95,8 +97,8 @@ class FileGenerator {
bool immutable_api_);
const FileDescriptor* file_;
- string java_package_;
- string classname_;
+ std::string java_package_;
+ std::string classname_;
std::vector<std::unique_ptr<MessageGenerator>> message_generators_;
std::vector<std::unique_ptr<ExtensionGenerator>> extension_generators_;
@@ -112,6 +114,6 @@ class FileGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/java_generator.cc
index a5b2e784..fd2591da 100644
--- a/src/google/protobuf/compiler/java/java_generator.cc
+++ b/src/google/protobuf/compiler/java/java_generator.cc
@@ -34,6 +34,7 @@
#include <google/protobuf/compiler/java/java_generator.h>
+
#include <memory>
#include <google/protobuf/compiler/java/java_file.h>
@@ -117,6 +118,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
file_generators.push_back(new FileGenerator(file, file_options,
/* mutable = */ false));
}
+
for (int i = 0; i < file_generators.size(); ++i) {
if (!file_generators[i]->Validate(error)) {
for (int j = 0; j < file_generators.size(); ++j) {
@@ -163,6 +165,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
}
}
+
for (int i = 0; i < file_generators.size(); ++i) {
delete file_generators[i];
}
diff --git a/src/google/protobuf/compiler/java/java_generator.h b/src/google/protobuf/compiler/java/java_generator.h
index 47f76be9..21873581 100644
--- a/src/google/protobuf/compiler/java/java_generator.h
+++ b/src/google/protobuf/compiler/java/java_generator.h
@@ -40,6 +40,8 @@
#include <string>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -49,16 +51,16 @@ namespace java {
// own protocol compiler binary and you want it to support Java output, you
// can do so by registering an instance of this CodeGenerator with the
// CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator {
+class PROTOC_EXPORT JavaGenerator : public CodeGenerator {
public:
JavaGenerator();
~JavaGenerator();
// implements CodeGenerator ----------------------------------------
bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* context,
- string* error) const;
+ std::string* error) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator);
@@ -67,6 +69,8 @@ class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/java/java_generator_factory.h b/src/google/protobuf/compiler/java/java_generator_factory.h
index 55365a9d..505cd3ac 100644
--- a/src/google/protobuf/compiler/java/java_generator_factory.h
+++ b/src/google/protobuf/compiler/java/java_generator_factory.h
@@ -37,19 +37,21 @@
namespace google {
namespace protobuf {
- class FieldDescriptor; // descriptor.h
- class Descriptor; // descriptor.h
- class ServiceDescriptor; // descriptor.h
- namespace compiler {
- namespace java {
- class MessageGenerator; // message.h
- class ExtensionGenerator; // extension.h
- class ServiceGenerator; // service.h
- class Context; // context.h
- }
+class FieldDescriptor; // descriptor.h
+class Descriptor; // descriptor.h
+class ServiceDescriptor; // descriptor.h
+namespace compiler {
+ namespace java {
+ class MessageGenerator; // message.h
+ class ExtensionGenerator; // extension.h
+ class ServiceGenerator; // service.h
+ class Context; // context.h
}
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -96,6 +98,6 @@ class ImmutableGeneratorFactory : public GeneratorFactory {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_FACTORY_H__
diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/java_helpers.cc
index 957076cb..dbd1604a 100644
--- a/src/google/protobuf/compiler/java/java_helpers.cc
+++ b/src/google/protobuf/compiler/java/java_helpers.cc
@@ -33,8 +33,8 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <limits>
+#include <unordered_set>
#include <vector>
#include <google/protobuf/stubs/stringprintf.h>
@@ -135,6 +135,29 @@ void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
printer->Print(ptemplate.c_str(), "annotation_file", annotation_file);
}
+void PrintEnumVerifierLogic(io::Printer* printer,
+ const FieldDescriptor* descriptor,
+ const std::map<string, string>& variables,
+ const char* var_name,
+ const char* terminating_string,
+ bool enforce_lite) {
+ std::string enum_verifier_string =
+ (descriptor->enum_type()->file()->options().optimize_for() ==
+ FileOptions::LITE_RUNTIME) || enforce_lite
+ ? StrCat(var_name, ".internalGetVerifier()")
+ : StrCat(
+ "new com.google.protobuf.Internal.EnumVerifier() {\n"
+ " @java.lang.Override\n"
+ " public boolean isInRange(int number) {\n"
+ " return ", var_name, ".forNumber(number) != null;\n"
+ " }\n"
+ " }"
+ );
+ printer->Print(
+ variables,
+ StrCat(enum_verifier_string, terminating_string).c_str());
+}
+
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
string result;
// Note: I distrust ctype.h due to locales.
@@ -178,6 +201,10 @@ string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) {
return UnderscoresToCamelCase(FieldName(field), true);
}
+string CapitalizedFieldName(const FieldDescriptor* field) {
+ return UnderscoresToCapitalizedCamelCase(field);
+}
+
string UnderscoresToCamelCase(const MethodDescriptor* method) {
return UnderscoresToCamelCase(method->name(), false);
}
@@ -223,6 +250,10 @@ string FileJavaPackage(const FileDescriptor* file, bool immutable) {
return result;
}
+string FileJavaPackage(const FileDescriptor* file) {
+ return FileJavaPackage(file, true /* immutable */);
+}
+
string JavaPackageToDir(string package_name) {
string package_dir =
StringReplace(package_name, ".", "/", true);
@@ -369,6 +400,10 @@ const char* PrimitiveTypeName(JavaType type) {
return NULL;
}
+const char* PrimitiveTypeName(const FieldDescriptor* descriptor) {
+ return PrimitiveTypeName(GetJavaType(descriptor));
+}
+
const char* BoxedPrimitiveTypeName(JavaType type) {
switch (type) {
case JAVATYPE_INT : return "java.lang.Integer";
@@ -389,6 +424,10 @@ const char* BoxedPrimitiveTypeName(JavaType type) {
return NULL;
}
+const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor) {
+ return BoxedPrimitiveTypeName(GetJavaType(descriptor));
+}
+
const char* FieldTypeName(FieldDescriptor::Type field_type) {
switch (field_type) {
@@ -437,11 +476,13 @@ string DefaultValue(const FieldDescriptor* field, bool immutable,
return SimpleItoa(field->default_value_int32());
case FieldDescriptor::CPPTYPE_UINT32:
// Need to print as a signed int since Java has no unsigned.
- return SimpleItoa(static_cast<int32>(field->default_value_uint32()));
+ return SimpleItoa(
+ static_cast<int32>(field->default_value_uint32()));
case FieldDescriptor::CPPTYPE_INT64:
return SimpleItoa(field->default_value_int64()) + "L";
case FieldDescriptor::CPPTYPE_UINT64:
- return SimpleItoa(static_cast<int64>(field->default_value_uint64())) +
+ return SimpleItoa(
+ static_cast<int64>(field->default_value_uint64())) +
"L";
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value = field->default_value_double();
@@ -749,9 +790,8 @@ const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
//
// already_seen is used to avoid checking the same type multiple times
// (and also to protect against recursion).
-bool HasRequiredFields(
- const Descriptor* type,
- hash_set<const Descriptor*>* already_seen) {
+bool HasRequiredFields(const Descriptor* type,
+ std::unordered_set<const Descriptor*>* already_seen) {
if (already_seen->count(type) > 0) {
// The type is already in cache. This means that either:
// a. The type has no required fields.
@@ -786,7 +826,7 @@ bool HasRequiredFields(
}
bool HasRequiredFields(const Descriptor* type) {
- hash_set<const Descriptor*> already_seen;
+ std::unordered_set<const Descriptor*> already_seen;
return HasRequiredFields(type, &already_seen);
}
@@ -932,22 +972,6 @@ void EscapeUtf16ToString(uint16 code, string* output) {
}
}
-std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
- const FieldDescriptor** fields, int count) {
- GOOGLE_CHECK_GT(count, 0);
- int table_driven_number_of_entries = count;
- int look_up_start_field_number = 0;
- for (int i = 0; i < count; i++) {
- const int field_number = fields[i]->number();
- if (ShouldUseTable(fields[0]->number(), field_number, i + 1)) {
- table_driven_number_of_entries =
- field_number - fields[0]->number() + 1 + count - i - 1;
- look_up_start_field_number = field_number + 1;
- }
- }
- return std::make_pair(
- table_driven_number_of_entries, look_up_start_field_number);
-}
} // 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 dd9b65b8..93caa3dc 100644
--- a/src/google/protobuf/compiler/java/java_helpers.h
+++ b/src/google/protobuf/compiler/java/java_helpers.h
@@ -60,79 +60,89 @@ extern const char kThinSeparator[];
// annotation_file should be generated from the filename of the source file
// being annotated (which in turn must be a Java identifier plus ".java").
void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
- const string& annotation_file = "");
+ const std::string& annotation_file = "");
+
+// If a GeneratedMessageLite contains non-lite enums, then its verifier
+// must be instantiated inline, rather than retrieved from the enum class.
+void PrintEnumVerifierLogic(io::Printer* printer,
+ const FieldDescriptor* descriptor,
+ const std::map<std::string, std::string>& variables,
+ const char* var_name,
+ const char* terminating_string,
+ bool enforce_lite);
// Converts a name to camel-case. If cap_first_letter is true, capitalize the
// first letter.
-string UnderscoresToCamelCase(const string& name, bool cap_first_letter);
+std::string UnderscoresToCamelCase(const std::string& name, bool cap_first_letter);
// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes
// "fooBarBaz" or "FooBarBaz", respectively.
-string UnderscoresToCamelCase(const FieldDescriptor* field);
-string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
+std::string UnderscoresToCamelCase(const FieldDescriptor* field);
+std::string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
// Similar, but for method names. (Typically, this merely has the effect
// of lower-casing the first letter of the name.)
-string UnderscoresToCamelCase(const MethodDescriptor* method);
+std::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);
+std::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.
-string UniqueFileScopeIdentifier(const Descriptor* descriptor);
+std::string UniqueFileScopeIdentifier(const Descriptor* descriptor);
// Strips ".proto" or ".protodevel" from the end of a filename.
-string StripProto(const string& filename);
+std::string StripProto(const std::string& filename);
// Gets the unqualified class name for the file. For each .proto file, there
// will be one Java class containing all the immutable messages and another
// Java class containing all the mutable messages.
// TODO(xiaofeng): remove the default value after updating client code.
-string FileClassName(const FileDescriptor* file, bool immutable = true);
+std::string FileClassName(const FileDescriptor* file, bool immutable = true);
// Returns the file's Java package name.
-string FileJavaPackage(const FileDescriptor* file, bool immutable = true);
+std::string FileJavaPackage(const FileDescriptor* file);
+std::string FileJavaPackage(const FileDescriptor* file, bool immutable);
// Returns output directory for the given package name.
-string JavaPackageToDir(string package_name);
+std::string JavaPackageToDir(std::string package_name);
// Converts the given fully-qualified name in the proto namespace to its
// fully-qualified name in the Java namespace, given that it is in the given
// file.
// TODO(xiaofeng): this method is deprecated and should be removed in the
// future.
-string ToJavaName(const string& full_name,
+std::string ToJavaName(const std::string& full_name,
const FileDescriptor* file);
// TODO(xiaofeng): the following methods are kept for they are exposed
-// publicly in //google/protobuf/compiler/java/names.h. They return
+// publicly in //net/proto2/compiler/java/public/names.h. They return
// immutable names only and should be removed after mutable API is
// integrated into google3.
-string ClassName(const Descriptor* descriptor);
-string ClassName(const EnumDescriptor* descriptor);
-string ClassName(const ServiceDescriptor* descriptor);
-string ClassName(const FileDescriptor* descriptor);
+std::string ClassName(const Descriptor* descriptor);
+std::string ClassName(const EnumDescriptor* descriptor);
+std::string ClassName(const ServiceDescriptor* descriptor);
+std::string ClassName(const FileDescriptor* descriptor);
// Comma-separate list of option-specified interfaces implemented by the
// Message, to follow the "implements" declaration of the Message definition.
-string ExtraMessageInterfaces(const Descriptor* descriptor);
+std::string ExtraMessageInterfaces(const Descriptor* descriptor);
// Comma-separate list of option-specified interfaces implemented by the
// MutableMessage, to follow the "implements" declaration of the MutableMessage
// definition.
-string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
+std::string ExtraMutableMessageInterfaces(const Descriptor* descriptor);
// Comma-separate list of option-specified interfaces implemented by the
// Builder, to follow the "implements" declaration of the Builder definition.
-string ExtraBuilderInterfaces(const Descriptor* descriptor);
+std::string ExtraBuilderInterfaces(const Descriptor* descriptor);
// Comma-separate list of option-specified interfaces extended by the
// MessageOrBuilder, to follow the "extends" declaration of the
// MessageOrBuilder definition.
-string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
+std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor);
// Get the unqualified Java class name for mutable messages. i.e. without
// package or outer classnames.
-inline string ShortMutableJavaClassName(const Descriptor* descriptor) {
+inline std::string ShortMutableJavaClassName(const Descriptor* descriptor) {
return descriptor->name();
}
@@ -140,7 +150,8 @@ inline string ShortMutableJavaClassName(const Descriptor* descriptor) {
// 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";
+ return descriptor->file()->name() == "net/proto2/proto/descriptor.proto" ||
+ descriptor->file()->name() == "google/protobuf/descriptor.proto";
}
@@ -168,14 +179,14 @@ inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
// annotation data for that descriptor. `suffix` is usually empty, but may
// (e.g.) be "OrBuilder" for some generated interfaces.
template <typename Descriptor>
-string AnnotationFileName(const Descriptor* descriptor, const string& suffix) {
+std::string AnnotationFileName(const Descriptor* descriptor, const std::string& suffix) {
return descriptor->name() + suffix + ".java.pb.meta";
}
template <typename Descriptor>
void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
Descriptor* descriptor, bool immutable,
- const string& suffix = "") {
+ const std::string& suffix = "") {
if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) {
PrintGeneratedAnnotation(printer, '$',
AnnotationFileName(descriptor, suffix));
@@ -184,7 +195,7 @@ void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer,
// Get the unqualified name that should be used for a field's field
// number constant.
-string FieldConstantName(const FieldDescriptor *field);
+std::string FieldConstantName(const FieldDescriptor *field);
// Returns the type of the FieldDescriptor.
// This does nothing interesting for the open source release, but is used for
@@ -218,9 +229,9 @@ const char* BoxedPrimitiveTypeName(JavaType type);
const char* FieldTypeName(const FieldDescriptor::Type field_type);
class ClassNameResolver;
-string DefaultValue(const FieldDescriptor* field, bool immutable,
+std::string DefaultValue(const FieldDescriptor* field, bool immutable,
ClassNameResolver* name_resolver);
-inline string ImmutableDefaultValue(const FieldDescriptor* field,
+inline std::string ImmutableDefaultValue(const FieldDescriptor* field,
ClassNameResolver* name_resolver) {
return DefaultValue(field, true, name_resolver);
}
@@ -256,50 +267,50 @@ inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) {
// Methods for shared bitfields.
// Gets the name of the shared bitfield for the given index.
-string GetBitFieldName(int index);
+std::string GetBitFieldName(int index);
// Gets the name of the shared bitfield for the given bit index.
// Effectively, GetBitFieldName(bitIndex / 32)
-string GetBitFieldNameForBit(int bitIndex);
+std::string GetBitFieldNameForBit(int bitIndex);
// Generates the java code for the expression that returns the boolean value
// of the bit of the shared bitfields for the given bit index.
// Example: "((bitField1_ & 0x04) == 0x04)"
-string GenerateGetBit(int bitIndex);
+std::string GenerateGetBit(int bitIndex);
// Generates the java code for the expression that sets the bit of the shared
// bitfields for the given bit index.
// Example: "bitField1_ = (bitField1_ | 0x04)"
-string GenerateSetBit(int bitIndex);
+std::string GenerateSetBit(int bitIndex);
// Generates the java code for the expression that clears the bit of the shared
// bitfields for the given bit index.
// Example: "bitField1_ = (bitField1_ & ~0x04)"
-string GenerateClearBit(int bitIndex);
+std::string GenerateClearBit(int bitIndex);
// Does the same as GenerateGetBit but operates on the bit field on a local
// variable. This is used by the builder to copy the value in the builder to
// the message.
// Example: "((from_bitField1_ & 0x04) == 0x04)"
-string GenerateGetBitFromLocal(int bitIndex);
+std::string GenerateGetBitFromLocal(int bitIndex);
// Does the same as GenerateSetBit but operates on the bit field on a local
// variable. This is used by the builder to copy the value in the builder to
// the message.
// Example: "to_bitField1_ = (to_bitField1_ | 0x04)"
-string GenerateSetBitToLocal(int bitIndex);
+std::string GenerateSetBitToLocal(int bitIndex);
// Does the same as GenerateGetBit but operates on the bit field on a local
// variable. This is used by the parsing constructor to record if a repeated
// field is mutable.
// Example: "((mutable_bitField1_ & 0x04) == 0x04)"
-string GenerateGetBitMutableLocal(int bitIndex);
+std::string GenerateGetBitMutableLocal(int bitIndex);
// Does the same as GenerateSetBit but operates on the bit field on a local
// variable. This is used by the parsing constructor to record if a repeated
// field is mutable.
// Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)"
-string GenerateSetBitMutableLocal(int bitIndex);
+std::string GenerateSetBitMutableLocal(int bitIndex);
// Returns whether the JavaType is a reference type.
bool IsReferenceType(JavaType type);
@@ -387,14 +398,10 @@ inline bool CheckUtf8(const FieldDescriptor* descriptor) {
descriptor->file()->options().java_string_check_utf8();
}
-inline string GeneratedCodeVersionSuffix() {
+inline std::string GeneratedCodeVersionSuffix() {
return "V3";
}
-inline bool EnableExperimentalRuntime(Context* context) {
- return false;
-}
-
void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector<uint16>* output);
inline void WriteIntToUtf16CharSequence(int value,
@@ -403,7 +410,7 @@ inline void WriteIntToUtf16CharSequence(int value,
}
// Escape a UTF-16 character so it can be embedded in a Java string literal.
-void EscapeUtf16ToString(uint16 code, string* output);
+void EscapeUtf16ToString(uint16 code, std::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
@@ -422,6 +429,6 @@ std::pair<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__
diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field.cc b/src/google/protobuf/compiler/java/java_lazy_message_field.cc
deleted file mode 100644
index abf8e55c..00000000
--- a/src/google/protobuf/compiler/java/java_lazy_message_field.cc
+++ /dev/null
@@ -1,814 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: niwasaki@google.com (Naoki Iwasaki)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <google/protobuf/compiler/java/java_context.h>
-#include <google/protobuf/compiler/java/java_lazy_message_field.h>
-#include <google/protobuf/compiler/java/java_doc_comment.h>
-#include <google/protobuf/compiler/java/java_helpers.h>
-#include <google/protobuf/io/printer.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace java {
-
-ImmutableLazyMessageFieldGenerator::
-ImmutableLazyMessageFieldGenerator(
- const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableMessageFieldGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
-}
-
-ImmutableLazyMessageFieldGenerator::~ImmutableLazyMessageFieldGenerator() {}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "private com.google.protobuf.LazyFieldLite $name$_ =\n"
- " new com.google.protobuf.LazyFieldLite();\n");
-
- PrintExtraFieldInfo(variables_, printer);
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $get_has_field_bit_message$;\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
-
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
- " return $name$_;\n"
- "}\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateBuilderMembers(io::Printer* printer) const {
- // When using nested-builders, the code initially works just like the
- // non-nested builder case. It only creates a nested builder lazily on
- // demand and then forever delegates to it after creation.
-
- printer->Print(variables_,
- "private com.google.protobuf.LazyFieldLite $name$_ =\n"
- " new com.google.protobuf.LazyFieldLite();\n");
-
- printer->Print(variables_,
- // If this builder is non-null, it is used and the other fields are
- // ignored.
- "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;"
- "\n");
-
- // The comments above the methods below are based on a hypothetical
- // field of type "Field" called "Field".
-
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $get_has_field_bit_builder$;\n"
- "}\n");
-
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$($type$ value)",
-
- "if (value == null) {\n"
- " throw new NullPointerException();\n"
- "}\n"
- "$name$_.setValue(value);\n"
- "$on_changed$\n",
-
- NULL, // Lazy fields are supported only for lite-runtime.
-
- "$set_has_field_bit_builder$;\n"
- "return this;\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " $type$.Builder builderForValue)",
-
- "$name$_.setValue(builderForValue.build());\n"
- "$on_changed$\n",
-
- NULL,
-
- "$set_has_field_bit_builder$;\n"
- "return this;\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder merge$capitalized_name$($type$ value)",
-
- "if ($get_has_field_bit_builder$ &&\n"
- " !$name$_.containsDefaultInstance()) {\n"
- " $name$_.setValue(\n"
- " $type$.newBuilder(\n"
- " get$capitalized_name$()).mergeFrom(value).buildPartial());\n"
- "} else {\n"
- " $name$_.setValue(value);\n"
- "}\n"
- "$on_changed$\n",
-
- NULL,
-
- "$set_has_field_bit_builder$;\n"
- "return this;\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
-
- "$name$_.clear();\n"
- "$on_changed$\n",
-
- NULL,
-
- "$clear_has_field_bit_builder$;\n"
- "return this;\n");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
- " if ($name$Builder_ != null) {\n"
- " return $name$Builder_.getMessageOrBuilder();\n"
- " } else {\n"
- " return $name$_;\n"
- " }\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder> \n"
- " get$capitalized_name$FieldBuilder() {\n"
- " if ($name$Builder_ == null) {\n"
- " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder>(\n"
- " $name$_,\n"
- " getParentForChildren(),\n"
- " isClean());\n"
- " $name$_ = null;\n"
- " }\n"
- " return $name$Builder_;\n"
- "}\n");
-}
-
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateInitializationCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.clear();\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateBuilderClearCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_.clear();\n");
- printer->Print(variables_, "$clear_has_field_bit_builder$;\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (other.has$capitalized_name$()) {\n"
- " $name$_.merge(other.$name$_);\n"
- " $set_has_field_bit_builder$;\n"
- "}\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateBuildingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has_field_bit_from_local$) {\n"
- " $set_has_field_bit_to_local$;\n"
- "}\n");
-
- printer->Print(variables_,
- "result.$name$_.set(\n"
- " $name$_);\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_.setByteString(input.readBytes(), extensionRegistry);\n");
- printer->Print(variables_,
- "$set_has_field_bit_message$;\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- // Do not de-serialize lazy fields.
- printer->Print(variables_,
- "if ($get_has_field_bit_message$) {\n"
- " output.writeBytes($number$, $name$_.toByteString());\n"
- "}\n");
-}
-
-void ImmutableLazyMessageFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($get_has_field_bit_message$) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, $name$_);\n"
- "}\n");
-}
-
-// ===================================================================
-
-ImmutableLazyMessageOneofFieldGenerator::
-ImmutableLazyMessageOneofFieldGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableLazyMessageFieldGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
- const OneofGeneratorInfo* info =
- context->GetOneofGeneratorInfo(descriptor->containing_oneof());
- SetCommonOneofVariables(descriptor, info, &variables_);
- variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite";
-}
-
-ImmutableLazyMessageOneofFieldGenerator::
-~ImmutableLazyMessageOneofFieldGenerator() {}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateMembers(io::Printer* printer) const {
- PrintExtraFieldInfo(variables_, printer);
- 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"
- " if ($has_oneof_case_message$) {\n"
- " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n"
- " $type$.getDefaultInstance());\n"
- " }\n"
- " return $type$.getDefaultInstance();\n"
- "}\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateBuilderMembers(io::Printer* printer) const {
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $has_oneof_case_message$;\n"
- "}\n");
-
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " if ($has_oneof_case_message$) {\n"
- " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n"
- " $type$.getDefaultInstance());\n"
- " }\n"
- " return $type$.getDefaultInstance();\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$($type$ value)",
-
- "if (value == null) {\n"
- " throw new NullPointerException();\n"
- "}\n"
- "if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- "}\n"
- "(($lazy_type$) $oneof_name$_).setValue(value);\n"
- "$on_changed$\n",
-
- NULL, // Lazy fields are supported only for lite-runtime.
-
- "return this;\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " $type$.Builder builderForValue)",
-
- "if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- "}\n"
- "(($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n"
- "$on_changed$\n",
-
- NULL,
-
- "return this;\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder merge$capitalized_name$($type$ value)",
-
- "if ($has_oneof_case_message$ &&\n"
- " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n"
- " (($lazy_type$) $oneof_name$_).setValue(\n"
- " $type$.newBuilder(\n"
- " get$capitalized_name$()).mergeFrom(value).buildPartial());\n"
- "} else {\n"
- " if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- " }\n"
- " (($lazy_type$) $oneof_name$_).setValue(value);\n"
- "}\n"
- "$on_changed$\n",
-
- NULL,
-
- "return this;\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
-
- "if ($has_oneof_case_message$) {\n"
- " $clear_oneof_case_message$;\n"
- " $oneof_name$_ = null;\n"
- " $on_changed$\n"
- "}\n",
-
- NULL,
-
- "return this;\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateMergingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- "}\n"
- "(($lazy_type$) $oneof_name$_).merge(\n"
- " ($lazy_type$) other.$oneof_name$_);\n"
- "$set_oneof_case_message$;\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateBuildingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case_message$) {\n");
- printer->Indent();
-
- printer->Print(variables_,
- "result.$oneof_name$_ = new $lazy_type$();\n"
- "(($lazy_type$) result.$oneof_name$_).set(\n"
- " (($lazy_type$) $oneof_name$_));\n");
- printer->Outdent();
- printer->Print("}\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- "}\n"
- "(($lazy_type$) $oneof_name$_).setByteString(\n"
- " input.readBytes(), extensionRegistry);\n"
- "$set_oneof_case_message$;\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- // Do not de-serialize lazy fields.
- printer->Print(variables_,
- "if ($has_oneof_case_message$) {\n"
- " output.writeBytes(\n"
- " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n"
- "}\n");
-}
-
-void ImmutableLazyMessageOneofFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case_message$) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n"
- "}\n");
-}
-
-// ===================================================================
-
-RepeatedImmutableLazyMessageFieldGenerator::
-RepeatedImmutableLazyMessageFieldGenerator(
- const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : RepeatedImmutableMessageFieldGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
-}
-
-
-RepeatedImmutableLazyMessageFieldGenerator::
-~RepeatedImmutableLazyMessageFieldGenerator() {}
-
-void RepeatedImmutableLazyMessageFieldGenerator::
-GenerateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "private java.util.List<com.google.protobuf.LazyFieldLite> $name$_;\n");
- PrintExtraFieldInfo(variables_, printer);
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<$type$>\n"
- " get$capitalized_name$List() {\n"
- " java.util.List<$type$> list =\n"
- " new java.util.ArrayList<$type$>($name$_.size());\n"
- " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n"
- " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n"
- " }\n"
- " return list;\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<? extends $type$OrBuilder>\n"
- " get$capitalized_name$OrBuilderList() {\n"
- " return get$capitalized_name$List();\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
- " return $name$_.size();\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
- " return ($type$)\n"
- " $name$_.get(index).getValue($type$.getDefaultInstance());\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
- " int index) {\n"
- " return ($type$OrBuilder)\n"
- " $name$_.get(index).getValue($type$.getDefaultInstance());\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldGenerator::
-GenerateBuilderMembers(io::Printer* printer) const {
- // When using nested-builders, the code initially works just like the
- // non-nested builder case. It only creates a nested builder lazily on
- // demand and then forever delegates to it after creation.
-
- printer->Print(variables_,
- "private java.util.List<com.google.protobuf.LazyFieldLite> $name$_ =\n"
- " java.util.Collections.emptyList();\n"
-
- "private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$get_mutable_bit_builder$) {\n"
- " $name$_ =\n"
- " new java.util.ArrayList<com.google.protobuf.LazyFieldLite>(\n"
- " $name$_);\n"
- " $set_mutable_bit_builder$;\n"
- " }\n"
- "}\n"
- "\n");
-
- printer->Print(variables_,
- // If this builder is non-null, it is used and the other fields are
- // ignored.
- "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n"
- "\n");
-
- // The comments above the methods below are based on a hypothetical
- // repeated field of type "Field" called "RepeatedField".
-
- // List<Field> getRepeatedFieldList()
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public java.util.List<$type$> get$capitalized_name$List()",
-
- "java.util.List<$type$> list =\n"
- " new java.util.ArrayList<$type$>($name$_.size());\n"
- "for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n"
- " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n"
- "}\n"
- "return java.util.Collections.unmodifiableList(list);\n",
-
- "return $name$Builder_.getMessageList();\n",
-
- NULL);
-
- // int getRepeatedFieldCount()
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public int get$capitalized_name$Count()",
-
- "return $name$_.size();\n",
- "return $name$Builder_.getCount();\n",
-
- NULL);
-
- // Field getRepeatedField(int index)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public $type$ get$capitalized_name$(int index)",
-
- "return ($type$) $name$_.get(index).getValue(\n"
- " $type$.getDefaultInstance());\n",
-
- "return $name$Builder_.getMessage(index);\n",
-
- NULL);
-
- // Builder setRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " int index, $type$ value)",
- "if (value == null) {\n"
- " throw new NullPointerException();\n"
- "}\n"
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n"
- "$on_changed$\n",
- "$name$Builder_.setMessage(index, value);\n",
- "return this;\n");
-
- // Builder setRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " int index, $type$.Builder builderForValue)",
-
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "$on_changed$\n",
-
- "$name$Builder_.setMessage(index, builderForValue.build());\n",
-
- "return this;\n");
-
- // Builder addRepeatedField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$($type$ value)",
-
- "if (value == null) {\n"
- " throw new NullPointerException();\n"
- "}\n"
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n"
-
- "$on_changed$\n",
-
- "$name$Builder_.addMessage(value);\n",
-
- "return this;\n");
-
- // Builder addRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
- " int index, $type$ value)",
-
- "if (value == null) {\n"
- " throw new NullPointerException();\n"
- "}\n"
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n"
- "$on_changed$\n",
-
- "$name$Builder_.addMessage(index, value);\n",
-
- "return this;\n");
-
- // Builder addRepeatedField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
- " $type$.Builder builderForValue)",
-
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "$on_changed$\n",
-
- "$name$Builder_.addMessage(builderForValue.build());\n",
-
- "return this;\n");
-
- // Builder addRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder add$capitalized_name$(\n"
- " int index, $type$.Builder builderForValue)",
-
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "$on_changed$\n",
-
- "$name$Builder_.addMessage(index, builderForValue.build());\n",
-
- "return this;\n");
-
- // Builder addAllRepeatedField(Iterable<Field> values)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder addAll$capitalized_name$(\n"
- " java.lang.Iterable<? extends $type$> values)",
-
- "ensure$capitalized_name$IsMutable();\n"
- "for (com.google.protobuf.MessageLite v : values) {\n"
- " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n"
- "}\n"
- "$on_changed$\n",
-
- "$name$Builder_.addAllMessages(values);\n",
-
- "return this;\n");
-
- // Builder clearAllRepeatedField()
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder clear$capitalized_name$()",
-
- "$name$_ = java.util.Collections.emptyList();\n"
- "$clear_mutable_bit_builder$;\n"
- "$on_changed$\n",
-
- "$name$Builder_.clear();\n",
-
- "return this;\n");
-
- // Builder removeRepeatedField(int index)
- WriteFieldDocComment(printer, descriptor_);
- PrintNestedBuilderFunction(printer,
- "$deprecation$public Builder remove$capitalized_name$(int index)",
-
- "ensure$capitalized_name$IsMutable();\n"
- "$name$_.remove(index);\n"
- "$on_changed$\n",
-
- "$name$Builder_.remove(index);\n",
-
- "return this;\n");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n"
- " int index) {\n"
- " return get$capitalized_name$FieldBuilder().getBuilder(index);\n"
- "}\n");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
- " int index) {\n"
- " if ($name$Builder_ == null) {\n"
- " return $name$_.get(index);"
- " } else {\n"
- " return $name$Builder_.getMessageOrBuilder(index);\n"
- " }\n"
- "}\n");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<? extends $type$OrBuilder> \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");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n"
- " return get$capitalized_name$FieldBuilder().addBuilder(\n"
- " $type$.getDefaultInstance());\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n"
- " int index) {\n"
- " return get$capitalized_name$FieldBuilder().addBuilder(\n"
- " index, $type$.getDefaultInstance());\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<$type$.Builder> \n"
- " get$capitalized_name$BuilderList() {\n"
- " return get$capitalized_name$FieldBuilder().getBuilderList();\n"
- "}\n"
- "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder> \n"
- " get$capitalized_name$FieldBuilder() {\n"
- " if ($name$Builder_ == null) {\n"
- " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
- " $type$, $type$.Builder, $type$OrBuilder>(\n"
- " $name$_,\n"
- " $get_mutable_bit_builder$,\n"
- " getParentForChildren(),\n"
- " isClean());\n"
- " $name$_ = null;\n"
- " }\n"
- " return $name$Builder_;\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!$get_mutable_bit_parser$) {\n"
- " $name$_ =\n"
- " new java.util.ArrayList<com.google.protobuf.LazyFieldLite>();\n"
- " $set_mutable_bit_parser$;\n"
- "}\n"
- "$name$_.add(new com.google.protobuf.LazyFieldLite(\n"
- " extensionRegistry, input.readBytes()));\n");
-}
-
-void RepeatedImmutableLazyMessageFieldGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0; i < $name$_.size(); i++) {\n"
- " output.writeBytes($number$, $name$_.get(i).toByteString());\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0; i < $name$_.size(); i++) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, $name$_.get(i));\n"
- "}\n");
-}
-
-} // namespace java
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/compiler/java/java_lazy_message_field.h b/src/google/protobuf/compiler/java/java_lazy_message_field.h
deleted file mode 100644
index b1b7f282..00000000
--- a/src/google/protobuf/compiler/java/java_lazy_message_field.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: niwasaki@google.com (Naoki Iwasaki)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__
-
-#include <google/protobuf/compiler/java/java_field.h>
-#include <google/protobuf/compiler/java/java_message_field.h>
-
-namespace google {
-namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- }
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace java {
-
-class ImmutableLazyMessageFieldGenerator
- : public ImmutableMessageFieldGenerator {
- public:
- explicit ImmutableLazyMessageFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~ImmutableLazyMessageFieldGenerator();
-
- // overroads ImmutableMessageFieldGenerator ---------------------------------
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateInitializationCode(io::Printer* printer) const;
- void GenerateBuilderClearCode(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateBuildingCode(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldGenerator);
-};
-
-class ImmutableLazyMessageOneofFieldGenerator
- : public ImmutableLazyMessageFieldGenerator {
- public:
- ImmutableLazyMessageOneofFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~ImmutableLazyMessageOneofFieldGenerator();
-
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateMergingCode(io::Printer* printer) const;
- void GenerateBuildingCode(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldGenerator);
-};
-
-class RepeatedImmutableLazyMessageFieldGenerator
- : public RepeatedImmutableMessageFieldGenerator {
- public:
- explicit RepeatedImmutableLazyMessageFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~RepeatedImmutableLazyMessageFieldGenerator();
-
- // overroads RepeatedImmutableMessageFieldGenerator -------------------------
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldGenerator);
-};
-
-} // namespace java
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__
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
deleted file mode 100644
index 51bb11f1..00000000
--- a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.cc
+++ /dev/null
@@ -1,725 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: niwasaki@google.com (Naoki Iwasaki)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#include <google/protobuf/compiler/java/java_context.h>
-#include <google/protobuf/compiler/java/java_lazy_message_field_lite.h>
-#include <google/protobuf/compiler/java/java_doc_comment.h>
-#include <google/protobuf/compiler/java/java_helpers.h>
-#include <google/protobuf/io/printer.h>
-
-namespace google {
-namespace protobuf {
-namespace compiler {
-namespace java {
-
-ImmutableLazyMessageFieldLiteGenerator::
-ImmutableLazyMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableMessageFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
-}
-
-ImmutableLazyMessageFieldLiteGenerator::
-~ImmutableLazyMessageFieldLiteGenerator() {}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "private com.google.protobuf.LazyFieldLite $name$_;");
-
- PrintExtraFieldInfo(variables_, printer);
- WriteFieldDocComment(printer, descriptor_);
- if (SupportFieldPresence(descriptor_->file())) {
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $get_has_field_bit_message$;\n"
- "}\n");
- } else {
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return $name$_ != null;\n"
- "}\n");
- }
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " if ($name$_ == null) {\n"
- " return $type$.getDefaultInstance();\n"
- " }\n"
- " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$($type$ value) {\n"
- " if (value == null) {\n"
- " throw new NullPointerException();\n"
- " }\n"
- " if ($name$_ == null) {\n"
- " $name$_ = new com.google.protobuf.LazyFieldLite();\n"
- " }\n"
- " $name$_.setValue(value);\n"
- " $set_has_field_bit_message$\n"
- "}\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " if ($name$_ == null) {\n"
- " $name$_ = new com.google.protobuf.LazyFieldLite();\n"
- " }\n"
- " $name$_.setValue(builderForValue.build());\n"
- " $set_has_field_bit_message$\n"
- "}\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void merge$capitalized_name$($type$ value) {\n"
- " if (has$capitalized_name$() &&\n"
- " !$name$_.containsDefaultInstance()) {\n"
- " $name$_.setValue(\n"
- " $type$.newBuilder(\n"
- " get$capitalized_name$()).mergeFrom(value).buildPartial());\n"
- " } else {\n"
- " if ($name$_ == null) {\n"
- " $name$_ = new com.google.protobuf.LazyFieldLite();\n"
- " }\n"
- " $name$_.setValue(value);\n"
- " $set_has_field_bit_message$\n"
- " }\n"
- "}\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void clear$capitalized_name$() {\n"
- " $name$_ = null;\n"
- " $clear_has_field_bit_message$;\n"
- "}\n");
-}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateBuilderMembers(io::Printer* printer) const {
- // The comments above the methods below are based on a hypothetical
- // field of type "Field" called "Field".
-
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return instance.has$capitalized_name$();\n"
- "}\n");
-
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " return instance.get$capitalized_name$();\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
- " copyOnWrite();\n"
- " instance.set$capitalized_name$(value);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " copyOnWrite();\n"
- " instance.set$capitalized_name$(builderForValue);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
- " copyOnWrite();\n"
- " instance.merge$capitalized_name$(value);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
- " copyOnWrite();\n"
- " instance.clear$capitalized_name$();\n"
- " return this;\n"
- "}\n");
-}
-
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateInitializationCode(io::Printer* printer) const {}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateVisitCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$name$_ = visitor.visitLazyMessage($name$_, other.$name$_);\n");
-}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($name$_ == null) {\n"
- " $name$_ = new com.google.protobuf.LazyFieldLite();\n"
- "}\n"
- "$name$_.mergeFrom(input, extensionRegistry);\n");
- printer->Print(variables_,
- "$set_has_field_bit_message$\n");
-}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- // Do not de-serialize lazy fields.
- printer->Print(variables_,
- "if (has$capitalized_name$()) {\n"
- " output.writeBytes($number$, $name$_.toByteString());\n"
- "}\n");
-}
-
-void ImmutableLazyMessageFieldLiteGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (has$capitalized_name$()) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, $name$_);\n"
- "}\n");
-}
-
-
-// ===================================================================
-
-ImmutableLazyMessageOneofFieldLiteGenerator::
-ImmutableLazyMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableLazyMessageFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
- const OneofGeneratorInfo* info =
- context->GetOneofGeneratorInfo(descriptor->containing_oneof());
- SetCommonOneofVariables(descriptor, info, &variables_);
- variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite";
-}
-
-ImmutableLazyMessageOneofFieldLiteGenerator::
-~ImmutableLazyMessageOneofFieldLiteGenerator() {}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateMembers(io::Printer* printer) const {
- PrintExtraFieldInfo(variables_, printer);
- 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"
- " if ($has_oneof_case_message$) {\n"
- " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n"
- " $type$.getDefaultInstance());\n"
- " }\n"
- " return $type$.getDefaultInstance();\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$($type$ value) {\n"
- " if (value == null) {\n"
- " throw new NullPointerException();\n"
- " }\n"
- " if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- " }\n"
- " (($lazy_type$) $oneof_name$_).setValue(value);\n"
- "}\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- " }\n"
- " (($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n"
- "}\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void merge$capitalized_name$($type$ value) {\n"
- " if ($has_oneof_case_message$ &&\n"
- " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n"
- " (($lazy_type$) $oneof_name$_).setValue(\n"
- " $type$.newBuilder(\n"
- " get$capitalized_name$()).mergeFrom(value).buildPartial());\n"
- " } else {\n"
- " if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- " $set_oneof_case_message$;\n"
- " }\n"
- " (($lazy_type$) $oneof_name$_).setValue(value);\n"
- " }\n"
- "}\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void clear$capitalized_name$() {\n"
- " if ($has_oneof_case_message$) {\n"
- " $clear_oneof_case_message$;\n"
- " $oneof_name$_ = null;\n"
- " }\n"
- "}\n");
-}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateBuilderMembers(io::Printer* printer) const {
- // boolean hasField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public boolean has$capitalized_name$() {\n"
- " return instance.has$capitalized_name$();\n"
- "}\n");
-
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$() {\n"
- " return instance.get$capitalized_name$();\n"
- "}\n");
-
- // Field.Builder setField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
- " copyOnWrite();\n"
- " instance.set$capitalized_name$(value);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder setField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder set$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " copyOnWrite();\n"
- " instance.set$capitalized_name$(builderForValue);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder mergeField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
- " copyOnWrite();\n"
- " instance.merge$capitalized_name$(value);\n"
- " return this;\n"
- "}\n");
-
- // Field.Builder clearField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
- " copyOnWrite();\n"
- " instance.clear$capitalized_name$();\n"
- " return this;\n"
- "}\n");
-}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateVisitCode(io::Printer* printer) const {
- printer->Print(variables_,
- "$oneof_name$_ = visitor.visitOneofLazyMessage(\n"
- " $has_oneof_case_message$,\n"
- " ($lazy_type$) $oneof_name$_,\n"
- " ($lazy_type$) other.$oneof_name$_);\n");
-}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!($has_oneof_case_message$)) {\n"
- " $oneof_name$_ = new $lazy_type$();\n"
- "}\n"
- "(($lazy_type$) $oneof_name$_).mergeFrom(input, extensionRegistry);\n"
- "$set_oneof_case_message$;\n");
-}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- // Do not de-serialize lazy fields.
- printer->Print(variables_,
- "if ($has_oneof_case_message$) {\n"
- " output.writeBytes(\n"
- " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n"
- "}\n");
-}
-
-void ImmutableLazyMessageOneofFieldLiteGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if ($has_oneof_case_message$) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n"
- "}\n");
-}
-
-
-// ===================================================================
-
-RepeatedImmutableLazyMessageFieldLiteGenerator::
-RepeatedImmutableLazyMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : RepeatedImmutableMessageFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
-}
-
-
-RepeatedImmutableLazyMessageFieldLiteGenerator::
-~RepeatedImmutableLazyMessageFieldLiteGenerator() {}
-
-void RepeatedImmutableLazyMessageFieldLiteGenerator::
-GenerateMembers(io::Printer* printer) const {
- printer->Print(variables_,
- "private com.google.protobuf.Internal.ProtobufList<\n"
- " com.google.protobuf.LazyFieldLite> $name$_;\n");
- PrintExtraFieldInfo(variables_, printer);
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<$type$>\n"
- " get$capitalized_name$List() {\n"
- " java.util.List<$type$> list =\n"
- " new java.util.ArrayList<$type$>($name$_.size());\n"
- " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n"
- " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n"
- " }\n"
- " return java.util.Collections.unmodifiableList(list);\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public java.util.List<? extends $type$OrBuilder>\n"
- " get$capitalized_name$OrBuilderList() {\n"
- " return get$capitalized_name$List();\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
- " return $name$_.size();\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
- " return ($type$)\n"
- " $name$_.get(index).getValue($type$.getDefaultInstance());\n"
- "}\n");
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
- " int index) {\n"
- " return ($type$OrBuilder)\n"
- " $name$_.get(index).getValue($type$.getDefaultInstance());\n"
- "}\n");
-
- printer->Print(variables_,
- "private void ensure$capitalized_name$IsMutable() {\n"
- " if (!$is_mutable$) {\n"
- " $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
- " }\n"
- "}\n"
- "\n");
-
- // Builder setRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$(\n"
- " int index, $type$ value) {\n"
- " if (value == null) {\n"
- " throw new NullPointerException();\n"
- " }\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.set(\n"
- " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n"
- "}\n");
-
- // Builder setRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void set$capitalized_name$(\n"
- " int index, $type$.Builder builderForValue) {\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "}\n");
-
- // Builder addRepeatedField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void add$capitalized_name$($type$ value) {\n"
- " if (value == null) {\n"
- " throw new NullPointerException();\n"
- " }\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n"
- "}\n");
-
- // Builder addRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void add$capitalized_name$(\n"
- " int index, $type$ value) {\n"
- " if (value == null) {\n"
- " throw new NullPointerException();\n"
- " }\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.add(\n"
- " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n"
- "}\n");
-
- // Builder addRepeatedField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void add$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "}\n");
-
- // Builder addRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void add$capitalized_name$(\n"
- " int index, $type$.Builder builderForValue) {\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n"
- " builderForValue.build()));\n"
- "}\n");
-
- // Builder addAllRepeatedField(Iterable<Field> values)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void addAll$capitalized_name$(\n"
- " java.lang.Iterable<? extends $type$> values) {\n"
- " ensure$capitalized_name$IsMutable();\n"
- " for (com.google.protobuf.MessageLite v : values) {\n"
- " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n"
- " }\n"
- "}\n");
-
- // Builder clearAllRepeatedField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void clear$capitalized_name$() {\n"
- " $name$_ = emptyProtobufList();\n"
- "}\n");
-
- // Builder removeRepeatedField(int index)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "private void remove$capitalized_name$(int index) {\n"
- " ensure$capitalized_name$IsMutable();\n"
- " $name$_.remove(index);\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldLiteGenerator::
-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"
- " return java.util.Collections.unmodifiableList(\n"
- " instance.get$capitalized_name$List());\n"
- "}\n");
-
- // int getRepeatedFieldCount()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public int get$capitalized_name$Count() {\n"
- " return instance.get$capitalized_name$Count();\n"
- "}\n");
-
- // Field getRepeatedField(int index)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
- " return instance.get$capitalized_name$(index);\n"
- "}\n");
-
- // Builder setRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
-
- // Builder setRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
-
- // Builder addRepeatedField(Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
- " copyOnWrite();\n"
- " instance.add$capitalized_name$(value);\n"
- " return this;\n"
- "}\n");
-
- // Builder addRepeatedField(int index, Field value)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
-
- // Builder addRepeatedField(Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder add$capitalized_name$(\n"
- " $type$.Builder builderForValue) {\n"
- " copyOnWrite();\n"
- " instance.add$capitalized_name$(builderForValue);\n"
- " return this;\n"
- "}\n");
-
- // Builder addRepeatedField(int index, Field.Builder builderForValue)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
-
- // Builder addAllRepeatedField(Iterable<Field> values)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$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");
-
- // Builder clearAllRepeatedField()
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder clear$capitalized_name$() {\n"
- " copyOnWrite();\n"
- " instance.clear$capitalized_name$();\n"
- " return this;\n"
- "}\n");
-
- // Builder removeRepeatedField(int index)
- WriteFieldDocComment(printer, descriptor_);
- printer->Print(variables_,
- "$deprecation$public Builder remove$capitalized_name$(int index) {\n"
- " copyOnWrite();\n"
- " instance.remove$capitalized_name$(index);\n"
- " return this;\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldLiteGenerator::
-GenerateParsingCode(io::Printer* printer) const {
- printer->Print(variables_,
- "if (!$is_mutable$) {\n"
- " $name$_ =\n"
- " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"
- "}\n"
- "$name$_.add(new com.google.protobuf.LazyFieldLite(\n"
- " extensionRegistry, input.readBytes()));\n");
-}
-
-void RepeatedImmutableLazyMessageFieldLiteGenerator::
-GenerateSerializationCode(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0; i < $name$_.size(); i++) {\n"
- " output.writeBytes($number$, $name$_.get(i).toByteString());\n"
- "}\n");
-}
-
-void RepeatedImmutableLazyMessageFieldLiteGenerator::
-GenerateSerializedSizeCode(io::Printer* printer) const {
- printer->Print(variables_,
- "for (int i = 0; i < $name$_.size(); i++) {\n"
- " size += com.google.protobuf.CodedOutputStream\n"
- " .computeLazyFieldSize($number$, $name$_.get(i));\n"
- "}\n");
-}
-
-
-} // namespace java
-} // namespace compiler
-} // namespace protobuf
-} // namespace google
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
deleted file mode 100644
index 65b84fbc..00000000
--- a/src/google/protobuf/compiler/java/java_lazy_message_field_lite.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: niwasaki@google.com (Naoki Iwasaki)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-
-#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__
-#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__
-
-#include <google/protobuf/compiler/java/java_field.h>
-#include <google/protobuf/compiler/java/java_message_field_lite.h>
-
-namespace google {
-namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- }
- }
-}
-
-namespace protobuf {
-namespace compiler {
-namespace java {
-
-class ImmutableLazyMessageFieldLiteGenerator
- : public ImmutableMessageFieldLiteGenerator {
- public:
- explicit ImmutableLazyMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~ImmutableLazyMessageFieldLiteGenerator();
-
- // overroads ImmutableMessageFieldLiteGenerator ------------------------------
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateInitializationCode(io::Printer* printer) const;
- void GenerateVisitCode(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldLiteGenerator);
-};
-
-class ImmutableLazyMessageOneofFieldLiteGenerator
- : public ImmutableLazyMessageFieldLiteGenerator {
- public:
- ImmutableLazyMessageOneofFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~ImmutableLazyMessageOneofFieldLiteGenerator();
-
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateVisitCode(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldLiteGenerator);
-};
-
-class RepeatedImmutableLazyMessageFieldLiteGenerator
- : public RepeatedImmutableMessageFieldLiteGenerator {
- public:
- explicit RepeatedImmutableLazyMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
- ~RepeatedImmutableLazyMessageFieldLiteGenerator();
-
- // overroads RepeatedImmutableMessageFieldLiteGenerator ----------------------
- void GenerateMembers(io::Printer* printer) const;
- void GenerateBuilderMembers(io::Printer* printer) const;
- void GenerateParsingCode(io::Printer* printer) const;
- void GenerateSerializationCode(io::Printer* printer) const;
- void GenerateSerializedSizeCode(io::Printer* printer) const;
-
-
- private:
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldLiteGenerator);
-};
-
-} // namespace java
-} // namespace compiler
-} // namespace protobuf
-
-} // namespace google
-#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_map_field.h b/src/google/protobuf/compiler/java/java_map_field.h
index 47021740..b123b041 100644
--- a/src/google/protobuf/compiler/java/java_map_field.h
+++ b/src/google/protobuf/compiler/java/java_map_field.h
@@ -63,11 +63,11 @@ class ImmutableMapFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
ClassNameResolver* name_resolver_;
void GenerateMapGetters(io::Printer* printer) const;
};
@@ -75,6 +75,6 @@ class ImmutableMapFieldGenerator : public ImmutableFieldGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__
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 e2e68076..569c38d7 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc
@@ -142,12 +142,12 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
ImmutableMapFieldLiteGenerator::
ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor,
int messageBitIndex,
- int builderBitIndex,
Context* context)
- : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) {
- SetMessageVariables(descriptor, messageBitIndex, builderBitIndex,
- context->GetFieldGeneratorInfo(descriptor),
- context, &variables_);
+ : descriptor_(descriptor), context_(context),
+ name_resolver_(context->GetNameResolver()){
+ SetMessageVariables(descriptor, messageBitIndex, 0,
+ context->GetFieldGeneratorInfo(descriptor), context,
+ &variables_);
}
ImmutableMapFieldLiteGenerator::
@@ -157,10 +157,6 @@ int ImmutableMapFieldLiteGenerator::GetNumBitsForMessage() const {
return 0;
}
-int ImmutableMapFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void ImmutableMapFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, 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 94aa4813..df5fe64d 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.h
@@ -40,14 +40,13 @@ namespace java {
class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator {
public:
- explicit ImmutableMapFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutableMapFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -63,17 +62,18 @@ class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
+ Context* context_;
ClassNameResolver* name_resolver_;
};
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc
index 209c0b2a..15142231 100644
--- a/src/google/protobuf/compiler/java/java_message.cc
+++ b/src/google/protobuf/compiler/java/java_message.cc
@@ -35,7 +35,6 @@
#include <google/protobuf/compiler/java/java_message.h>
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#include <vector>
@@ -53,8 +52,8 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
namespace google {
@@ -377,10 +376,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"}\n");
if (context_->HasGeneratedMethods(descriptor_)) {
- if (!EnableExperimentalRuntime(context_) ||
- IsDescriptorProto(descriptor_)) {
- GenerateParsingConstructor(printer);
- }
+ GenerateParsingConstructor(printer);
}
GenerateDescriptorMethods(printer);
@@ -421,7 +417,8 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
descriptor_->oneof_decl(i))->name;
vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->capitalized_name;
- vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
+ vars["oneof_index"] =
+ SimpleItoa(descriptor_->oneof_decl(i)->index());
// oneofCase_ and oneof_
printer->Print(vars,
"private int $oneof_name$Case_ = 0;\n"
@@ -434,11 +431,10 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
printer->Print(
- "$deprecation$$field_name$($field_number$),\n",
- "deprecation",
- field->options().deprecated() ? "@java.lang.Deprecated " : "",
- "field_name", ToUpper(field->name()),
- "field_number", SimpleItoa(field->number()));
+ "$deprecation$$field_name$($field_number$),\n", "deprecation",
+ field->options().deprecated() ? "@java.lang.Deprecated " : "",
+ "field_name", ToUpper(field->name()), "field_number",
+ SimpleItoa(field->number()));
}
printer->Print(
"$cap_oneof_name$_NOT_SET(0);\n",
@@ -462,12 +458,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
" switch (value) {\n");
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- " case $field_number$: return $field_name$;\n",
- "field_number",
- SimpleItoa(field->number()),
- "field_name",
- ToUpper(field->name()));
+ printer->Print(" case $field_number$: return $field_name$;\n",
+ "field_number", SimpleItoa(field->number()),
+ "field_name", ToUpper(field->name()));
}
printer->Print(
" case 0: return $cap_oneof_name$_NOT_SET;\n"
@@ -497,8 +490,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
// Fields
for (int i = 0; i < descriptor_->field_count(); i++) {
printer->Print("public static final int $constant_name$ = $number$;\n",
- "constant_name", FieldConstantName(descriptor_->field(i)),
- "number", SimpleItoa(descriptor_->field(i)->number()));
+ "constant_name", FieldConstantName(descriptor_->field(i)),
+ "number",
+ SimpleItoa(descriptor_->field(i)->number()));
field_generators_.get(descriptor_->field(i)).GenerateMembers(printer);
printer->Print("\n");
}
@@ -591,58 +585,54 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
" throws java.io.IOException {\n");
printer->Indent();
- 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");
- }
-
- 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 (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());
}
+ }
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print("unknownFields.writeAsMessageSetTo(output);\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 {
- printer->Print("unknownFields.writeTo(output);\n");
+ GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
}
}
+ 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"
@@ -653,39 +643,33 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
" if (size != -1) return size;\n"
"\n");
printer->Indent();
- if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
- printer->Print(
- "memoizedSize = getSerializedSizeInternal();\n"
- "return memoizedSize;\n");
- } else {
- printer->Print("size = 0;\n");
+ printer->Print("size = 0;\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");
- }
- }
+ 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 += unknownFields.getSerializedSizeAsMessageSet();\n");
+ printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
} else {
- printer->Print("size += unknownFields.getSerializedSize();\n");
+ printer->Print("size += extensionsSerializedSize();\n");
}
+ }
+ if (descriptor_->options().message_set_wire_format()) {
printer->Print(
- "memoizedSize = size;\n"
- "return size;\n");
+ "size += unknownFields.getSerializedSizeAsMessageSet();\n");
+ } else {
+ printer->Print("size += unknownFields.getSerializedSize();\n");
}
+ printer->Print(
+ "memoizedSize = size;\n"
+ "return size;\n");
+
printer->Outdent();
printer->Print(
"}\n"
@@ -779,9 +763,8 @@ void ImmutableMessageGenerator::GenerateSerializeOneField(
void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange(
io::Printer* printer, const Descriptor::ExtensionRange* range) {
- printer->Print(
- "extensionWriter.writeUntil($end$, output);\n",
- "end", SimpleItoa(range->end));
+ printer->Print("extensionWriter.writeUntil($end$, output);\n", "end",
+ SimpleItoa(range->end));
}
// ===================================================================
@@ -853,10 +836,10 @@ GenerateDescriptorMethods(io::Printer* printer) {
const FieldDescriptor* field = map_fields[i];
const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
printer->Print(
- "case $number$:\n"
- " return internalGet$capitalized_name$();\n",
- "number", SimpleItoa(field->number()),
- "capitalized_name", info->capitalized_name);
+ "case $number$:\n"
+ " return internalGet$capitalized_name$();\n",
+ "number", SimpleItoa(field->number()), "capitalized_name",
+ info->capitalized_name);
}
printer->Print(
"default:\n"
@@ -944,10 +927,9 @@ void ImmutableMessageGenerator::GenerateIsInitialized(
const OneofDescriptor* oneof = field->containing_oneof();
const OneofGeneratorInfo* oneof_info =
context_->GetOneofGeneratorInfo(oneof);
- printer->Print(
- "if ($oneof_name$Case_ == $field_number$) {\n",
- "oneof_name", oneof_info->name,
- "field_number", SimpleItoa(field->number()));
+ printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
+ "oneof_name", oneof_info->name, "field_number",
+ SimpleItoa(field->number()));
} else {
printer->Print(
"if (has$name$()) {\n",
@@ -1080,10 +1062,8 @@ GenerateEqualsAndHashCode(io::Printer* printer) {
printer->Indent();
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- "case $field_number$:\n",
- "field_number",
- SimpleItoa(field->number()));
+ printer->Print("case $field_number$:\n", "field_number",
+ SimpleItoa(field->number()));
printer->Indent();
field_generators_.get(field).GenerateEqualsCode(printer);
printer->Print("break;\n");
@@ -1164,10 +1144,8 @@ GenerateEqualsAndHashCode(io::Printer* printer) {
printer->Indent();
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
- printer->Print(
- "case $field_number$:\n",
- "field_number",
- SimpleItoa(field->number()));
+ printer->Print("case $field_number$:\n", "field_number",
+ SimpleItoa(field->number()));
printer->Indent();
field_generators_.get(field).GenerateHashCode(printer);
printer->Print("break;\n");
@@ -1273,9 +1251,8 @@ GenerateParsingConstructor(io::Printer* printer) {
uint32 tag = WireFormatLite::MakeTag(field->number(),
WireFormat::WireTypeForFieldType(field->type()));
- printer->Print(
- "case $tag$: {\n",
- "tag", SimpleItoa(static_cast<int32>(tag)));
+ printer->Print("case $tag$: {\n", "tag",
+ SimpleItoa(static_cast<int32>(tag)));
printer->Indent();
field_generators_.get(field).GenerateParsingCode(printer);
@@ -1290,9 +1267,8 @@ GenerateParsingConstructor(io::Printer* printer) {
// 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>(packed_tag)));
printer->Indent();
field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
@@ -1306,15 +1282,12 @@ GenerateParsingConstructor(io::Printer* printer) {
printer->Print(
"default: {\n"
- " if (!parseUnknownField$suffix$(\n"
+ " if (!parseUnknownField(\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"
- : "");
+ "}\n");
printer->Outdent();
printer->Outdent();
@@ -1369,16 +1342,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
" com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n",
"classname", descriptor_->name());
- if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
- printer->Indent();
- printer->Print(
- "$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_)) {
+ if (context_->HasGeneratedMethods(descriptor_)) {
printer->Print(" return new $classname$(input, extensionRegistry);\n",
"classname", descriptor_->name());
} else {
diff --git a/src/google/protobuf/compiler/java/java_message.h b/src/google/protobuf/compiler/java/java_message.h
index da1447c1..ac0c7659 100644
--- a/src/google/protobuf/compiler/java/java_message.h
+++ b/src/google/protobuf/compiler/java/java_message.h
@@ -41,17 +41,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -66,8 +68,8 @@ class MessageGenerator {
// All static variables have to be declared at the top-level of the file
// so that we can control initialization order, which is important for
// DescriptorProto bootstrapping to work.
- virtual void GenerateStaticVariables(
- io::Printer* printer, int* bytecode_estimate) = 0;
+ virtual void GenerateStaticVariables(io::Printer* printer,
+ int* bytecode_estimate) = 0;
// Output code which initializes the static variables generated by
// GenerateStaticVariables(). Returns an estimate of bytecode size.
@@ -76,7 +78,8 @@ class MessageGenerator {
// Generate the class itself.
virtual void Generate(io::Printer* printer) = 0;
- // Generates the base interface that both the class and its builder implement
+ // Generates the base interface that both the class and its builder
+ // implement
virtual void GenerateInterface(io::Printer* printer) = 0;
// Generate code to register all contained extensions with an
@@ -137,6 +140,6 @@ class ImmutableMessageGenerator : public MessageGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index 4c67e806..0b9db222 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder.cc
@@ -35,7 +35,6 @@
#include <google/protobuf/compiler/java/java_message_builder.h>
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#include <vector>
@@ -51,8 +50,8 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
namespace google {
@@ -126,7 +125,8 @@ Generate(io::Printer* printer) {
descriptor_->oneof_decl(i))->name;
vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->capitalized_name;
- vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
+ vars["oneof_index"] =
+ SimpleItoa(descriptor_->oneof_decl(i)->index());
// oneofCase_ and oneof_
printer->Print(vars,
"private int $oneof_name$Case_ = 0;\n"
@@ -169,8 +169,6 @@ Generate(io::Printer* printer) {
.GenerateBuilderMembers(printer);
}
- 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
@@ -180,7 +178,7 @@ Generate(io::Printer* printer) {
"@java.lang.Override\n"
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
- " return super.setUnknownFields$suffix$(unknownFields);\n"
+ " return super.setUnknownFields(unknownFields);\n"
"}\n"
"\n"
"@java.lang.Override\n"
@@ -188,8 +186,7 @@ Generate(io::Printer* printer) {
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.mergeUnknownFields(unknownFields);\n"
"}\n"
- "\n",
- "suffix", is_proto3 ? "Proto3" : "");
+ "\n");
printer->Print(
"\n"
@@ -234,10 +231,10 @@ GenerateDescriptorMethods(io::Printer* printer) {
const FieldDescriptor* field = map_fields[i];
const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
printer->Print(
- "case $number$:\n"
- " return internalGet$capitalized_name$();\n",
- "number", SimpleItoa(field->number()),
- "capitalized_name", info->capitalized_name);
+ "case $number$:\n"
+ " return internalGet$capitalized_name$();\n",
+ "number", SimpleItoa(field->number()), "capitalized_name",
+ info->capitalized_name);
}
printer->Print(
"default:\n"
@@ -260,10 +257,10 @@ GenerateDescriptorMethods(io::Printer* printer) {
const FieldGeneratorInfo* info =
context_->GetFieldGeneratorInfo(field);
printer->Print(
- "case $number$:\n"
- " return internalGetMutable$capitalized_name$();\n",
- "number", SimpleItoa(field->number()),
- "capitalized_name", info->capitalized_name);
+ "case $number$:\n"
+ " return internalGetMutable$capitalized_name$();\n",
+ "number", SimpleItoa(field->number()), "capitalized_name",
+ info->capitalized_name);
}
printer->Print(
"default:\n"
@@ -686,10 +683,9 @@ void MessageBuilderGenerator::GenerateIsInitialized(
const OneofDescriptor* oneof = field->containing_oneof();
const OneofGeneratorInfo* oneof_info =
context_->GetOneofGeneratorInfo(oneof);
- printer->Print(
- "if ($oneof_name$Case_ == $field_number$) {\n",
- "oneof_name", oneof_info->name,
- "field_number", SimpleItoa(field->number()));
+ printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
+ "oneof_name", oneof_info->name, "field_number",
+ SimpleItoa(field->number()));
} else {
printer->Print(
"if (has$name$()) {\n",
diff --git a/src/google/protobuf/compiler/java/java_message_builder.h b/src/google/protobuf/compiler/java/java_message_builder.h
index 015ea062..d67a9c9d 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.h
+++ b/src/google/protobuf/compiler/java/java_message_builder.h
@@ -41,17 +41,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -81,6 +83,6 @@ class MessageBuilderGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__
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 f04d394e..b9a12d4a 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.cc
@@ -35,7 +35,6 @@
#include <google/protobuf/compiler/java/java_message_builder_lite.h>
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#include <vector>
@@ -51,8 +50,8 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
namespace google {
namespace protobuf {
@@ -102,7 +101,8 @@ Generate(io::Printer* printer) {
descriptor_->oneof_decl(i))->name;
vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo(
descriptor_->oneof_decl(i))->capitalized_name;
- vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
+ vars["oneof_index"] =
+ SimpleItoa(descriptor_->oneof_decl(i)->index());
// oneofCase() and clearOneof()
printer->Print(vars,
@@ -120,20 +120,6 @@ Generate(io::Printer* printer) {
"\n");
}
- if (GenerateHasBits(descriptor_)) {
- // Integers for bit fields.
- int totalBits = 0;
- for (int i = 0; i < descriptor_->field_count(); i++) {
- totalBits += field_generators_.get(descriptor_->field(i))
- .GetNumBitsForBuilder();
- }
- int totalInts = (totalBits + 31) / 32;
- for (int i = 0; i < totalInts; i++) {
- printer->Print("private int $bit_field_name$;\n",
- "bit_field_name", GetBitFieldName(i));
- }
- }
-
for (int i = 0; i < descriptor_->field_count(); i++) {
printer->Print("\n");
field_generators_.get(descriptor_->field(i))
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.h b/src/google/protobuf/compiler/java/java_message_builder_lite.h
index 8597b2e6..079d86a9 100644
--- a/src/google/protobuf/compiler/java/java_message_builder_lite.h
+++ b/src/google/protobuf/compiler/java/java_message_builder_lite.h
@@ -41,17 +41,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -59,7 +61,7 @@ namespace java {
class MessageBuilderLiteGenerator {
public:
explicit MessageBuilderLiteGenerator(const Descriptor* descriptor,
- Context* context);
+ Context* context);
virtual ~MessageBuilderLiteGenerator();
virtual void Generate(io::Printer* printer);
@@ -78,6 +80,6 @@ class MessageBuilderLiteGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/java_message_field.cc
index baa7f872..92425d06 100644
--- a/src/google/protobuf/compiler/java/java_message_field.cc
+++ b/src/google/protobuf/compiler/java/java_message_field.cc
@@ -254,8 +254,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
bool support_field_presence = SupportFieldPresence(descriptor_->file());
- printer->Print(variables_,
- "private $type$ $name$_ = null;\n");
+ printer->Print(variables_, "private $type$ $name$_;\n");
printer->Print(variables_,
// If this builder is non-null, it is used and the other fields are
@@ -443,16 +442,18 @@ GenerateMergingCode(io::Printer* printer) const {
void ImmutableMessageFieldGenerator::
GenerateBuildingCode(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
+ printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n");
+ printer->Indent();
+ PrintNestedBuilderCondition(printer, "result.$name$_ = $name$_;\n",
+ "result.$name$_ = $name$Builder_.build();\n");
+ printer->Outdent();
printer->Print(variables_,
- "if ($get_has_field_bit_from_local$) {\n"
- " $set_has_field_bit_to_local$;\n"
- "}\n");
+ " $set_has_field_bit_to_local$;\n"
+ "}\n");
+ } else {
+ PrintNestedBuilderCondition(printer, "result.$name$_ = $name$_;\n",
+ "result.$name$_ = $name$Builder_.build();\n");
}
-
- PrintNestedBuilderCondition(printer,
- "result.$name$_ = $name$_;\n",
-
- "result.$name$_ = $name$Builder_.build();\n");
}
void ImmutableMessageFieldGenerator::
diff --git a/src/google/protobuf/compiler/java/java_message_field.h b/src/google/protobuf/compiler/java/java_message_field.h
index 7ee0edb2..58344e55 100644
--- a/src/google/protobuf/compiler/java/java_message_field.h
+++ b/src/google/protobuf/compiler/java/java_message_field.h
@@ -41,26 +41,30 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator {
public:
- explicit ImmutableMessageFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableMessageFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ int builderBitIndex,
+ Context* context);
~ImmutableMessageFieldGenerator();
- // implements ImmutableFieldGenerator ---------------------------------------
+ // implements ImmutableFieldGenerator
+ // ---------------------------------------
int GetNumBitsForMessage() const;
int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
@@ -78,22 +82,24 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
void PrintNestedBuilderCondition(io::Printer* printer,
- const char* regular_case, const char* nested_builder_case) const;
+ const char* regular_case,
+ const char* nested_builder_case) const;
void PrintNestedBuilderFunction(io::Printer* printer,
- const char* method_prototype, const char* regular_case,
- const char* nested_builder_case,
- const char* trailing_code) const;
+ const char* method_prototype,
+ const char* regular_case,
+ const char* nested_builder_case,
+ const char* trailing_code) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageFieldGenerator);
@@ -102,9 +108,9 @@ class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator {
class ImmutableMessageOneofFieldGenerator
: public ImmutableMessageFieldGenerator {
public:
- ImmutableMessageOneofFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableMessageOneofFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, int builderBitIndex,
+ Context* context);
~ImmutableMessageOneofFieldGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -144,22 +150,24 @@ class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
void PrintNestedBuilderCondition(io::Printer* printer,
- const char* regular_case, const char* nested_builder_case) const;
+ const char* regular_case,
+ const char* nested_builder_case) const;
void PrintNestedBuilderFunction(io::Printer* printer,
- const char* method_prototype, const char* regular_case,
- const char* nested_builder_case,
- const char* trailing_code) const;
+ const char* method_prototype,
+ const char* regular_case,
+ const char* nested_builder_case,
+ const char* trailing_code) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableMessageFieldGenerator);
@@ -168,6 +176,6 @@ class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__
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 9cf6f363..7bf6426e 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc
@@ -104,17 +104,15 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
// ===================================================================
-ImmutableMessageFieldLiteGenerator::
-ImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetMessageVariables(descriptor, messageBitIndex, builderBitIndex,
- context->GetFieldGeneratorInfo(descriptor),
- name_resolver_, &variables_);
+ImmutableMessageFieldLiteGenerator::ImmutableMessageFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetMessageVariables(descriptor, messageBitIndex, 0,
+ context->GetFieldGeneratorInfo(descriptor),
+ name_resolver_, &variables_);
}
ImmutableMessageFieldLiteGenerator::~ImmutableMessageFieldLiteGenerator() {}
@@ -123,10 +121,6 @@ int ImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const {
return 1;
}
-int ImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void ImmutableMessageFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
@@ -387,12 +381,10 @@ string ImmutableMessageFieldLiteGenerator::GetBoxedType() const {
// ===================================================================
ImmutableMessageOneofFieldLiteGenerator::
-ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableMessageFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
+ ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context)
+ : ImmutableMessageFieldLiteGenerator(descriptor, messageBitIndex, context) {
const OneofGeneratorInfo* info =
context->GetOneofGeneratorInfo(descriptor->containing_oneof());
SetCommonOneofVariables(descriptor, info, &variables_);
@@ -593,14 +585,14 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
// ===================================================================
RepeatedImmutableMessageFieldLiteGenerator::
-RepeatedImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetMessageVariables(descriptor, messageBitIndex, builderBitIndex,
+ RepeatedImmutableMessageFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex,
+ Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetMessageVariables(descriptor, messageBitIndex, 0,
context->GetFieldGeneratorInfo(descriptor),
name_resolver_, &variables_);
}
@@ -612,10 +604,6 @@ int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const {
return 0;
}
-int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void RepeatedImmutableMessageFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
// TODO(jonp): In the future, consider having methods specific to the
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 7c814c6d..7e78ca4f 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.h
@@ -41,28 +41,30 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator {
public:
- explicit ImmutableMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutableMessageFieldLiteGenerator();
- // implements ImmutableFieldLiteGenerator ------------------------------------
+ // implements ImmutableFieldLiteGenerator
+ // ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -77,13 +79,12 @@ class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -94,9 +95,9 @@ class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator {
class ImmutableMessageOneofFieldLiteGenerator
: public ImmutableMessageFieldLiteGenerator {
public:
- ImmutableMessageOneofFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutableMessageOneofFieldLiteGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -115,13 +116,11 @@ class RepeatedImmutableMessageFieldLiteGenerator
: public ImmutableFieldLiteGenerator {
public:
explicit RepeatedImmutableMessageFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context);
~RepeatedImmutableMessageFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -137,13 +136,12 @@ class RepeatedImmutableMessageFieldLiteGenerator
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -154,6 +152,6 @@ class RepeatedImmutableMessageFieldLiteGenerator
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc
index 3a512e8d..a131e8cc 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_lite.cc
@@ -35,7 +35,6 @@
#include <google/protobuf/compiler/java/java_message_lite.h>
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#include <vector>
@@ -53,8 +52,8 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
-#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/substitute.h>
namespace google {
@@ -266,12 +265,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
for (int j = 0; j < oneof->field_count(); j++) {
const FieldDescriptor* field = oneof->field(j);
- printer->Print(
- "$field_name$($field_number$),\n",
- "field_name",
- ToUpper(field->name()),
- "field_number",
- SimpleItoa(field->number()));
+ printer->Print("$field_name$($field_number$),\n", "field_name",
+ ToUpper(field->name()), "field_number",
+ SimpleItoa(field->number()));
}
printer->Print(
"$cap_oneof_name$_NOT_SET(0);\n",
@@ -295,12 +291,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
" switch (value) {\n");
for (int j = 0; j < oneof->field_count(); j++) {
const FieldDescriptor* field = oneof->field(j);
- printer->Print(
- " case $field_number$: return $field_name$;\n",
- "field_number",
- SimpleItoa(field->number()),
- "field_name",
- ToUpper(field->name()));
+ printer->Print(" case $field_number$: return $field_name$;\n",
+ "field_number", SimpleItoa(field->number()),
+ "field_name", ToUpper(field->name()));
}
printer->Print(
" case 0: return $cap_oneof_name$_NOT_SET;\n"
@@ -333,16 +326,14 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
// Fields
for (int i = 0; i < descriptor_->field_count(); i++) {
printer->Print("public static final int $constant_name$ = $number$;\n",
- "constant_name", FieldConstantName(descriptor_->field(i)),
- "number", SimpleItoa(descriptor_->field(i)->number()));
+ "constant_name", FieldConstantName(descriptor_->field(i)),
+ "number",
+ SimpleItoa(descriptor_->field(i)->number()));
field_generators_.get(descriptor_->field(i)).GenerateMembers(printer);
printer->Print("\n");
}
- if (!EnableExperimentalRuntime(context_)) {
- GenerateMessageSerializationMethods(printer);
- }
-
+ GenerateMessageSerializationMethods(printer);
GenerateParseFromMethods(printer);
GenerateBuilder(printer);
@@ -737,23 +728,22 @@ void ImmutableMessageLiteGenerator::GenerateSerializeOneField(
void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange(
io::Printer* printer, const Descriptor::ExtensionRange* range) {
- printer->Print(
- "extensionWriter.writeUntil($end$, output);\n",
- "end", SimpleItoa(range->end));
+ printer->Print("extensionWriter.writeUntil($end$, output);\n", "end",
+ SimpleItoa(range->end));
}
// ===================================================================
void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) {
printer->Print(
- "public static Builder newBuilder() {\n"
- " return (Builder) DEFAULT_INSTANCE.createBuilder();\n"
- "}\n"
- "public static Builder newBuilder($classname$ prototype) {\n"
- " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n"
- "}\n"
- "\n",
- "classname", name_resolver_->GetImmutableClassName(descriptor_));
+ "public static Builder newBuilder() {\n"
+ " return (Builder) DEFAULT_INSTANCE.createBuilder();\n"
+ "}\n"
+ "public static Builder newBuilder($classname$ prototype) {\n"
+ " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n"
+ "}\n"
+ "\n",
+ "classname", name_resolver_->GetImmutableClassName(descriptor_));
MessageBuilderLiteGenerator builderGenerator(descriptor_, context_);
builderGenerator.Generate(printer);
@@ -818,10 +808,9 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
const OneofDescriptor* oneof = field->containing_oneof();
const OneofGeneratorInfo* oneof_info =
context_->GetOneofGeneratorInfo(oneof);
- printer->Print(
- "if ($oneof_name$Case_ == $field_number$) {\n",
- "oneof_name", oneof_info->name,
- "field_number", SimpleItoa(field->number()));
+ printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
+ "oneof_name", oneof_info->name, "field_number",
+ SimpleItoa(field->number()));
} else {
printer->Print(
"if (has$name$()) {\n",
@@ -1002,102 +991,96 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
printer->Print(
"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(
+ "boolean done = false;\n"
+ "while (!done) {\n");
+ printer->Indent();
- printer->Print(
- "int tag = input.readTag();\n"
- "switch (tag) {\n");
+ 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");
+
+ std::unique_ptr<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();
- printer->Print(
- "case 0:\n" // zero signals EOF / limit reached
- " done = true;\n"
- " break;\n");
+ field_generators_.get(field).GenerateParsingCode(printer);
- std::unique_ptr<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->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>(tag)));
+ SimpleItoa(static_cast<int32>(packed_tag)));
printer->Indent();
- field_generators_.get(field).GenerateParsingCode(printer);
+ field_generators_.get(field).GenerateParsingCodeFromPacked(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");
- }
+ " break;\n"
+ "}\n");
}
+ }
- if (descriptor_->extension_range_count() > 0) {
- if (descriptor_->options().message_set_wire_format()) {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownFieldAsMessageSet(\n"
- " getDefaultInstanceForType(), input, extensionRegistry,\n"
- " tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- } else {
- printer->Print(
- "default: {\n"
- " if (!parseUnknownField(getDefaultInstanceForType(),\n"
- " input, extensionRegistry, tag)) {\n"
- " done = true;\n" // it's an endgroup tag
- " }\n"
- " break;\n"
- "}\n");
- }
+ if (descriptor_->extension_range_count() > 0) {
+ if (descriptor_->options().message_set_wire_format()) {
+ printer->Print(
+ "default: {\n"
+ " if (!parseUnknownFieldAsMessageSet(\n"
+ " getDefaultInstanceForType(), input, extensionRegistry,\n"
+ " tag)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
} else {
printer->Print(
"default: {\n"
- " if (!parseUnknownField(tag, input)) {\n"
+ " if (!parseUnknownField(getDefaultInstanceForType(),\n"
+ " input, extensionRegistry, tag)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\n");
}
-
- printer->Outdent();
- printer->Outdent();
+ } else {
printer->Print(
- " }\n" // switch (tag)
- "}\n"); // while (!done)
+ "default: {\n"
+ " if (!parseUnknownField(tag, input)) {\n"
+ " done = true;\n" // it's an endgroup tag
+ " }\n"
+ " break;\n"
+ "}\n");
}
printer->Outdent();
+ printer->Outdent();
+ printer->Print(
+ " }\n" // switch (tag)
+ "}\n"); // while (!done)
+
+ printer->Outdent();
printer->Print(
"} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n"
" throw new RuntimeException(e.setUnfinishedMessage(this));\n"
diff --git a/src/google/protobuf/compiler/java/java_message_lite.h b/src/google/protobuf/compiler/java/java_message_lite.h
index 1e319c6d..d38c54a7 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.h
+++ b/src/google/protobuf/compiler/java/java_message_lite.h
@@ -87,6 +87,6 @@ class ImmutableMessageLiteGenerator : public MessageGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_name_resolver.h b/src/google/protobuf/compiler/java/java_name_resolver.h
index 28b049d1..aa19f007 100644
--- a/src/google/protobuf/compiler/java/java_name_resolver.h
+++ b/src/google/protobuf/compiler/java/java_name_resolver.h
@@ -56,63 +56,63 @@ class ClassNameResolver {
~ClassNameResolver();
// Gets the unqualified outer class name for the file.
- string GetFileClassName(const FileDescriptor* file, bool immutable);
+ std::string GetFileClassName(const FileDescriptor* file, bool immutable);
// Gets the unqualified immutable outer class name of a file.
- string GetFileImmutableClassName(const FileDescriptor* file);
+ std::string GetFileImmutableClassName(const FileDescriptor* file);
// Gets the unqualified default immutable outer class name of a file
// (converted from the proto file's name).
- string GetFileDefaultImmutableClassName(const FileDescriptor* file);
+ std::string GetFileDefaultImmutableClassName(const FileDescriptor* file);
// Check whether there is any type defined in the proto file that has
// the given class name.
bool HasConflictingClassName(const FileDescriptor* file,
- const string& classname);
+ const std::string& classname);
// Gets the name of the outer class that holds descriptor information.
// Descriptors are shared between immutable messages and mutable messages.
// Since both of them are generated optionally, the descriptors need to be
// put in another common place.
- string GetDescriptorClassName(const FileDescriptor* file);
+ std::string GetDescriptorClassName(const FileDescriptor* file);
// Gets the fully-qualified class name corresponding to the given descriptor.
- string GetClassName(const Descriptor* descriptor, bool immutable);
- string GetClassName(const EnumDescriptor* descriptor, bool immutable);
- string GetClassName(const ServiceDescriptor* descriptor, bool immutable);
- string GetClassName(const FileDescriptor* descriptor, bool immutable);
+ std::string GetClassName(const Descriptor* descriptor, bool immutable);
+ std::string GetClassName(const EnumDescriptor* descriptor, bool immutable);
+ std::string GetClassName(const ServiceDescriptor* descriptor, bool immutable);
+ std::string GetClassName(const FileDescriptor* descriptor, bool immutable);
template<class DescriptorType>
- string GetImmutableClassName(const DescriptorType* descriptor) {
+ std::string GetImmutableClassName(const DescriptorType* descriptor) {
return GetClassName(descriptor, true);
}
template<class DescriptorType>
- string GetMutableClassName(const DescriptorType* descriptor) {
+ std::string GetMutableClassName(const DescriptorType* descriptor) {
return GetClassName(descriptor, false);
}
// Gets the fully qualified name of an extension identifier.
- string GetExtensionIdentifierName(const FieldDescriptor* descriptor,
+ std::string GetExtensionIdentifierName(const FieldDescriptor* descriptor,
bool immutable);
// Gets the fully qualified name for generated classes in Java convention.
// Nested classes will be separated using '$' instead of '.'
// For example:
// com.package.OuterClass$OuterMessage$InnerMessage
- string GetJavaImmutableClassName(const Descriptor* descriptor);
- string GetJavaImmutableClassName(const EnumDescriptor* descriptor);
+ std::string GetJavaImmutableClassName(const Descriptor* descriptor);
+ std::string GetJavaImmutableClassName(const EnumDescriptor* descriptor);
private:
// Get the full name of a Java class by prepending the Java package name
// or outer class name.
- string GetClassFullName(const string& name_without_package,
+ std::string GetClassFullName(const std::string& name_without_package,
const FileDescriptor* file,
bool immutable,
bool multiple_files);
// Get the Java Class style full name of a message.
- string GetJavaClassFullName(
- const string& name_without_package,
+ std::string GetJavaClassFullName(
+ const std::string& name_without_package,
const FileDescriptor* file,
bool immutable);
// Caches the result to provide better performance.
- std::map<const FileDescriptor*, string> file_immutable_outer_class_names_;
+ std::map<const FileDescriptor*, std::string> file_immutable_outer_class_names_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ClassNameResolver);
};
@@ -120,6 +120,6 @@ class ClassNameResolver {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAME_RESOLVER_H__
diff --git a/src/google/protobuf/compiler/java/java_names.h b/src/google/protobuf/compiler/java/java_names.h
index 0d614335..a8efbb49 100644
--- a/src/google/protobuf/compiler/java/java_names.h
+++ b/src/google/protobuf/compiler/java/java_names.h
@@ -46,6 +46,7 @@ namespace protobuf {
class Descriptor;
class EnumDescriptor;
class FileDescriptor;
+class FieldDescriptor;
class ServiceDescriptor;
namespace compiler {
@@ -56,32 +57,56 @@ namespace java {
//
// Returns:
// The fully-qualified Java class name.
-string ClassName(const Descriptor* descriptor);
+std::string ClassName(const Descriptor* descriptor);
// Requires:
// descriptor != NULL
//
// Returns:
// The fully-qualified Java class name.
-string ClassName(const EnumDescriptor* descriptor);
+std::string ClassName(const EnumDescriptor* descriptor);
// Requires:
// descriptor != NULL
//
// Returns:
// The fully-qualified Java class name.
-string ClassName(const FileDescriptor* descriptor);
+std::string ClassName(const FileDescriptor* descriptor);
// Requires:
// descriptor != NULL
//
// Returns:
// The fully-qualified Java class name.
-string ClassName(const ServiceDescriptor* descriptor);
+std::string ClassName(const ServiceDescriptor* descriptor);
+
+// Requires:
+// descriptor != NULL
+//
+// Returns:
+// Java package name.
+std::string FileJavaPackage(const FileDescriptor* descriptor);
+
+// Requires:
+// descriptor != NULL
+// Returns:
+// Captialized camel case name field name.
+std::string CapitalizedFieldName(const FieldDescriptor* descriptor);
+
+// Requires:
+// descriptor != NULL
+// Returns:
+// Primitive Java type name for the field.
+const char* PrimitiveTypeName(const FieldDescriptor* descriptor);
+
+// Requires:
+// descriptor != NULL
+// Returns:
+// Boes primitive Java type name for the field.
+const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor);
} // namespace java
} // namespace compiler
} // namespace protobuf
} // namespace google
-
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAMES_H__
diff --git a/src/google/protobuf/compiler/java/java_options.h b/src/google/protobuf/compiler/java/java_options.h
index e4e7d5e2..6c29be15 100644
--- a/src/google/protobuf/compiler/java/java_options.h
+++ b/src/google/protobuf/compiler/java/java_options.h
@@ -68,6 +68,6 @@ struct Options {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_OPTIONS_H__
diff --git a/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/src/google/protobuf/compiler/java/java_plugin_unittest.cc
index 87f687da..644d0685 100644
--- a/src/google/protobuf/compiler/java/java_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/java/java_plugin_unittest.cc
@@ -95,7 +95,7 @@ TEST(JavaPluginTest, PluginTest) {
"enum Qux { BLAH = 1; }\n",
true));
- google::protobuf::compiler::CommandLineInterface cli;
+ CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
JavaGenerator java_generator;
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/java_primitive_field.cc
index 71ee0992..c98c8b3a 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field.cc
@@ -56,6 +56,14 @@ using internal::WireFormatLite;
namespace {
+bool EnableJavaPrimitiveExperiment() {
+#ifdef PROTOBUF_JAVA_PRIMITIVE_EXPERIMENT
+ return PROTOBUF_JAVA_PRIMITIVE_EXPERIMENT;
+#else // PROTOBUF_JAVA_PRIMITIVE_EXPERIMENT
+ return false;
+#endif // !PROTOBUF_JAVA_PRIMITIVE_EXPERIMENT
+}
+
void SetPrimitiveVariables(const FieldDescriptor* descriptor,
int messageBitIndex,
int builderBitIndex,
@@ -63,13 +71,51 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
ClassNameResolver* name_resolver,
std::map<string, string>* variables) {
SetCommonFieldVariables(descriptor, info, variables);
+ JavaType javaType = GetJavaType(descriptor);
- (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor));
- (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
+ (*variables)["type"] = PrimitiveTypeName(javaType);
+ (*variables)["boxed_type"] = BoxedPrimitiveTypeName(javaType);
(*variables)["field_type"] = (*variables)["type"];
- (*variables)["field_list_type"] = "java.util.List<" +
- (*variables)["boxed_type"] + ">";
- (*variables)["empty_list"] = "java.util.Collections.emptyList()";
+
+ if (EnableJavaPrimitiveExperiment() &&
+ (javaType == JAVATYPE_BOOLEAN ||
+ javaType == JAVATYPE_DOUBLE ||
+ javaType == JAVATYPE_FLOAT ||
+ javaType == JAVATYPE_INT ||
+ javaType == JAVATYPE_LONG)) {
+ string capitalized_type = UnderscoresToCamelCase(
+ PrimitiveTypeName(javaType), /*cap_first_letter=*/true);
+ (*variables)["field_list_type"] =
+ "com.google.protobuf.Internal." + capitalized_type + "List";
+ (*variables)["empty_list"] = "empty" + capitalized_type + "List()";
+ (*variables)["create_list"] = "new" + capitalized_type + "List()";
+ (*variables)["mutable_copy_list"] =
+ "mutableCopy(" + (*variables)["name"] + "_)";
+ (*variables)["name_make_immutable"] =
+ (*variables)["name"] + "_.makeImmutable()";
+ (*variables)["repeated_get"] =
+ (*variables)["name"] + "_.get" + capitalized_type;
+ (*variables)["repeated_add"] =
+ (*variables)["name"] + "_.add" + capitalized_type;
+ (*variables)["repeated_set"] =
+ (*variables)["name"] + "_.set" + capitalized_type;
+ } else {
+ (*variables)["field_list_type"] =
+ "java.util.List<" + (*variables)["boxed_type"] + ">";
+ (*variables)["create_list"] =
+ "new java.util.ArrayList<" + (*variables)["boxed_type"] + ">()";
+ (*variables)["mutable_copy_list"] = "new java.util.ArrayList<" +
+ (*variables)["boxed_type"] + ">(" +
+ (*variables)["name"] + "_)";
+ (*variables)["empty_list"] = "java.util.Collections.emptyList()";
+ (*variables)["name_make_immutable"] =
+ (*variables)["name"] + "_ = java.util.Collections.unmodifiableList(" +
+ (*variables)["name"] + "_)";
+ (*variables)["repeated_get"] = (*variables)["name"] + "_.get";
+ (*variables)["repeated_add"] = (*variables)["name"] + "_.add";
+ (*variables)["repeated_set"] = (*variables)["name"] + "_.set";
+ }
+
(*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
(*variables)["default_init"] = IsDefaultValueJavaDefault(descriptor) ?
"" : ("= " + ImmutableDefaultValue(descriptor, name_resolver));
@@ -264,7 +310,9 @@ GenerateFieldBuilderInitializationCode(io::Printer* printer) const {
void ImmutablePrimitiveFieldGenerator::
GenerateInitializationCode(io::Printer* printer) const {
- printer->Print(variables_, "$name$_ = $default$;\n");
+ if (!IsDefaultValueJavaDefault(descriptor_)) {
+ printer->Print(variables_, "$name$_ = $default$;\n");
+ }
}
void ImmutablePrimitiveFieldGenerator::
@@ -292,13 +340,22 @@ GenerateMergingCode(io::Printer* printer) const {
void ImmutablePrimitiveFieldGenerator::
GenerateBuildingCode(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
- printer->Print(variables_,
- "if ($get_has_field_bit_from_local$) {\n"
- " $set_has_field_bit_to_local$;\n"
- "}\n");
+ if (IsDefaultValueJavaDefault(descriptor_)) {
+ printer->Print(variables_,
+ "if ($get_has_field_bit_from_local$) {\n"
+ " result.$name$_ = $name$_;\n"
+ " $set_has_field_bit_to_local$;\n"
+ "}\n");
+ } else {
+ printer->Print(variables_,
+ "if ($get_has_field_bit_from_local$) {\n"
+ " $set_has_field_bit_to_local$;\n"
+ "}\n"
+ "result.$name$_ = $name$_;\n");
+ }
+ } else {
+ printer->Print(variables_, "result.$name$_ = $name$_;\n");
}
- printer->Print(variables_,
- "result.$name$_ = $name$_;\n");
}
void ImmutablePrimitiveFieldGenerator::
@@ -629,7 +686,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
- " return $name$_.get(index);\n"
+ " return $repeated_get$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
@@ -656,7 +713,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
" if (!$get_mutable_bit_builder$) {\n"
- " $name$_ = new java.util.ArrayList<$boxed_type$>($name$_);\n"
+ " $name$_ = $mutable_copy_list$;\n"
" $set_mutable_bit_builder$;\n"
" }\n"
"}\n");
@@ -669,7 +726,8 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
" ${$get$capitalized_name$List$}$() {\n"
- " return java.util.Collections.unmodifiableList($name$_);\n"
+ " return $get_mutable_bit_builder$ ?\n"
+ " java.util.Collections.unmodifiableList($name$_) : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
@@ -681,7 +739,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
- " return $name$_.get(index);\n"
+ " return $repeated_get$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
@@ -690,7 +748,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" int index, $type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
- " $name$_.set(index, value);\n"
+ " $repeated_set$(index, value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
@@ -700,7 +758,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
- " $name$_.add(value);\n"
+ " $repeated_add$(value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
@@ -770,7 +828,7 @@ GenerateBuildingCode(io::Printer* printer) const {
// list is immutable, we can just reuse it. If not, we make it immutable.
printer->Print(variables_,
"if ($get_mutable_bit_builder$) {\n"
- " $name$_ = java.util.Collections.unmodifiableList($name$_);\n"
+ " $name_make_immutable$;\n"
" $clear_mutable_bit_builder$;\n"
"}\n"
"result.$name$_ = $name$_;\n");
@@ -780,10 +838,10 @@ void RepeatedImmutablePrimitiveFieldGenerator::
GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"if (!$get_mutable_bit_parser$) {\n"
- " $name$_ = new java.util.ArrayList<$boxed_type$>();\n"
+ " $name$_ = $create_list$;\n"
" $set_mutable_bit_parser$;\n"
"}\n"
- "$name$_.add(input.read$capitalized_type$());\n");
+ "$repeated_add$(input.read$capitalized_type$());\n");
}
void RepeatedImmutablePrimitiveFieldGenerator::
@@ -792,11 +850,11 @@ GenerateParsingCodeFromPacked(io::Printer* printer) const {
"int length = input.readRawVarint32();\n"
"int limit = input.pushLimit(length);\n"
"if (!$get_mutable_bit_parser$ && input.getBytesUntilLimit() > 0) {\n"
- " $name$_ = new java.util.ArrayList<$boxed_type$>();\n"
+ " $name$_ = $create_list$;\n"
" $set_mutable_bit_parser$;\n"
"}\n"
"while (input.getBytesUntilLimit() > 0) {\n"
- " $name$_.add(input.read$capitalized_type$());\n"
+ " $repeated_add$(input.read$capitalized_type$());\n"
"}\n"
"input.popLimit(limit);\n");
}
@@ -805,7 +863,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::
GenerateParsingDoneCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($get_mutable_bit_parser$) {\n"
- " $name$_ = java.util.Collections.unmodifiableList($name$_);\n"
+ " $name_make_immutable$; // C\n"
"}\n");
}
@@ -821,12 +879,12 @@ GenerateSerializationCode(io::Printer* printer) const {
" output.writeUInt32NoTag($name$MemoizedSerializedSize);\n"
"}\n"
"for (int i = 0; i < $name$_.size(); i++) {\n"
- " output.write$capitalized_type$NoTag($name$_.get(i));\n"
+ " output.write$capitalized_type$NoTag($repeated_get$(i));\n"
"}\n");
} else {
printer->Print(variables_,
"for (int i = 0; i < $name$_.size(); i++) {\n"
- " output.write$capitalized_type$($number$, $name$_.get(i));\n"
+ " output.write$capitalized_type$($number$, $repeated_get$(i));\n"
"}\n");
}
}
@@ -842,7 +900,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(variables_,
"for (int i = 0; i < $name$_.size(); i++) {\n"
" dataSize += com.google.protobuf.CodedOutputStream\n"
- " .compute$capitalized_type$SizeNoTag($name$_.get(i));\n"
+ " .compute$capitalized_type$SizeNoTag($repeated_get$(i));\n"
"}\n");
} else {
printer->Print(variables_,
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.h b/src/google/protobuf/compiler/java/java_primitive_field.h
index 7ac9bbfb..185a268e 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field.h
+++ b/src/google/protobuf/compiler/java/java_primitive_field.h
@@ -41,26 +41,30 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator {
public:
- explicit ImmutablePrimitiveFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ int builderBitIndex,
+ Context* context);
~ImmutablePrimitiveFieldGenerator();
- // implements ImmutableFieldGenerator ---------------------------------------
+ // implements ImmutableFieldGenerator
+ // ---------------------------------------
int GetNumBitsForMessage() const;
int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
@@ -78,11 +82,11 @@ class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -95,9 +99,9 @@ class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator {
class ImmutablePrimitiveOneofFieldGenerator
: public ImmutablePrimitiveFieldGenerator {
public:
- ImmutablePrimitiveOneofFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutablePrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ int builderBitIndex, Context* context);
~ImmutablePrimitiveOneofFieldGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -139,11 +143,11 @@ class RepeatedImmutablePrimitiveFieldGenerator
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -155,6 +159,6 @@ class RepeatedImmutablePrimitiveFieldGenerator
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__
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 d2ebc567..034a0865 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.cc
@@ -172,15 +172,13 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
// ===================================================================
-ImmutablePrimitiveFieldLiteGenerator::
-ImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
+ImmutablePrimitiveFieldLiteGenerator::ImmutablePrimitiveFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetPrimitiveVariables(descriptor, messageBitIndex, 0,
context->GetFieldGeneratorInfo(descriptor),
name_resolver_, &variables_);
}
@@ -191,10 +189,6 @@ int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const {
return 1;
}
-int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void ImmutablePrimitiveFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
@@ -472,12 +466,11 @@ string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
// ===================================================================
ImmutablePrimitiveOneofFieldLiteGenerator::
-ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutablePrimitiveFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
+ ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context)
+ : ImmutablePrimitiveFieldLiteGenerator(descriptor, messageBitIndex,
+ context) {
const OneofGeneratorInfo* info =
context->GetOneofGeneratorInfo(descriptor->containing_oneof());
SetCommonOneofVariables(descriptor, info, &variables_);
@@ -609,14 +602,14 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
// ===================================================================
RepeatedImmutablePrimitiveFieldLiteGenerator::
-RepeatedImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
+ RepeatedImmutablePrimitiveFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex,
+ Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetPrimitiveVariables(descriptor, messageBitIndex, 0,
context->GetFieldGeneratorInfo(descriptor),
name_resolver_, &variables_);
}
@@ -628,10 +621,6 @@ int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const {
return 0;
}
-int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void RepeatedImmutablePrimitiveFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
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 93416f0b..6c05521f 100644
--- a/src/google/protobuf/compiler/java/java_primitive_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_primitive_field_lite.h
@@ -41,14 +41,16 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -57,13 +59,12 @@ class ImmutablePrimitiveFieldLiteGenerator
: public ImmutableFieldLiteGenerator {
public:
explicit ImmutablePrimitiveFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context);
~ImmutablePrimitiveFieldLiteGenerator();
- // implements ImmutableFieldLiteGenerator ------------------------------------
+ // implements ImmutableFieldLiteGenerator
+ // ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -81,13 +82,12 @@ class ImmutablePrimitiveFieldLiteGenerator
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -98,9 +98,9 @@ class ImmutablePrimitiveFieldLiteGenerator
class ImmutablePrimitiveOneofFieldLiteGenerator
: public ImmutablePrimitiveFieldLiteGenerator {
public:
- ImmutablePrimitiveOneofFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutablePrimitiveOneofFieldLiteGenerator();
void GenerateMembers(io::Printer* printer) const;
@@ -120,13 +120,11 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator
: public ImmutableFieldLiteGenerator {
public:
explicit RepeatedImmutablePrimitiveFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context);
virtual ~RepeatedImmutablePrimitiveFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -145,13 +143,12 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -161,6 +158,6 @@ class RepeatedImmutablePrimitiveFieldLiteGenerator
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/java/java_service.cc b/src/google/protobuf/compiler/java/java_service.cc
index 988e1942..53a9017d 100644
--- a/src/google/protobuf/compiler/java/java_service.cc
+++ b/src/google/protobuf/compiler/java/java_service.cc
@@ -84,13 +84,13 @@ void ImmutableServiceGenerator::Generate(io::Printer* printer) {
// Generate getDescriptor() and getDescriptorForType().
printer->Print(
- "public static final\n"
- " com.google.protobuf.Descriptors.ServiceDescriptor\n"
- " getDescriptor() {\n"
- " return $file$.getDescriptor().getServices().get($index$);\n"
- "}\n",
- "file", name_resolver_->GetImmutableClassName(descriptor_->file()),
- "index", SimpleItoa(descriptor_->index()));
+ "public static final\n"
+ " com.google.protobuf.Descriptors.ServiceDescriptor\n"
+ " getDescriptor() {\n"
+ " return $file$.getDescriptor().getServices().get($index$);\n"
+ "}\n",
+ "file", name_resolver_->GetImmutableClassName(descriptor_->file()),
+ "index", SimpleItoa(descriptor_->index()));
GenerateGetDescriptorForType(printer);
// Generate more stuff.
diff --git a/src/google/protobuf/compiler/java/java_service.h b/src/google/protobuf/compiler/java/java_service.h
index 12b3f942..24b0ccaa 100644
--- a/src/google/protobuf/compiler/java/java_service.h
+++ b/src/google/protobuf/compiler/java/java_service.h
@@ -40,17 +40,19 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -123,7 +125,7 @@ class ImmutableServiceGenerator : public ServiceGenerator {
const MethodDescriptor* method);
// Return the output type of the method.
- string GetOutput(const MethodDescriptor* method);
+ std::string GetOutput(const MethodDescriptor* method);
Context* context_;
ClassNameResolver* name_resolver_;
@@ -133,6 +135,6 @@ class ImmutableServiceGenerator : public ServiceGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
+} // namespace google
#endif // NET_PROTO2_COMPILER_JAVA_SERVICE_H__
-} // namespace google
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 58a31f5d..2f09c3a9 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.h
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.h
@@ -44,18 +44,20 @@
namespace google {
namespace protobuf {
- class FileDescriptor; // descriptor.h
- namespace compiler {
- class GeneratorContext; // code_generator.h
- namespace java {
- class ClassNameResolver; // name_resolver.h
- }
- }
- namespace io {
- class Printer; // printer.h
- }
+class FileDescriptor; // descriptor.h
+namespace compiler {
+class GeneratorContext; // code_generator.h
+namespace java {
+class ClassNameResolver; // name_resolver.h
}
+} // namespace compiler
+namespace io {
+class Printer; // printer.h
+}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
@@ -68,8 +70,8 @@ class SharedCodeGenerator {
~SharedCodeGenerator();
void Generate(GeneratorContext* generator_context,
- std::vector<string>* file_list,
- std::vector<string>* annotation_file_list);
+ std::vector<std::string>* file_list,
+ std::vector<std::string>* annotation_file_list);
void GenerateDescriptors(io::Printer* printer);
@@ -84,6 +86,6 @@ class SharedCodeGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/java/java_string_field.h b/src/google/protobuf/compiler/java/java_string_field.h
index 0f7c705b..38fb8365 100644
--- a/src/google/protobuf/compiler/java/java_string_field.h
+++ b/src/google/protobuf/compiler/java/java_string_field.h
@@ -42,26 +42,29 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableStringFieldGenerator : public ImmutableFieldGenerator {
public:
- explicit ImmutableStringFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableStringFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ int builderBitIndex, Context* context);
~ImmutableStringFieldGenerator();
- // implements ImmutableFieldGenerator ---------------------------------------
+ // implements ImmutableFieldGenerator
+ // ---------------------------------------
int GetNumBitsForMessage() const;
int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
@@ -79,11 +82,11 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -96,9 +99,9 @@ class ImmutableStringFieldGenerator : public ImmutableFieldGenerator {
class ImmutableStringOneofFieldGenerator
: public ImmutableStringFieldGenerator {
public:
- ImmutableStringOneofFieldGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, int builderBitIndex,
+ Context* context);
~ImmutableStringOneofFieldGenerator();
private:
@@ -138,11 +141,11 @@ class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator {
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
const int builderBitIndex_;
Context* context_;
@@ -154,6 +157,6 @@ class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator {
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__
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 a238c67d..5ce31517 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.cc
@@ -119,15 +119,13 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
// ===================================================================
-ImmutableStringFieldLiteGenerator::
-ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
+ImmutableStringFieldLiteGenerator::ImmutableStringFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetPrimitiveVariables(descriptor, messageBitIndex, 0,
context->GetFieldGeneratorInfo(descriptor),
name_resolver_, &variables_);
}
@@ -138,10 +136,6 @@ int ImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const {
return 1;
}
-int ImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
// A note about how strings are handled. In the SPEED and CODE_SIZE runtimes,
// strings are not stored as java.lang.String in the Message because of two
// issues:
@@ -403,13 +397,9 @@ string ImmutableStringFieldLiteGenerator::GetBoxedType() const {
// ===================================================================
-ImmutableStringOneofFieldLiteGenerator::
-ImmutableStringOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : ImmutableStringFieldLiteGenerator(
- descriptor, messageBitIndex, builderBitIndex, context) {
+ImmutableStringOneofFieldLiteGenerator::ImmutableStringOneofFieldLiteGenerator(
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context)
+ : ImmutableStringFieldLiteGenerator(descriptor, messageBitIndex, context) {
const OneofGeneratorInfo* info =
context->GetOneofGeneratorInfo(descriptor->containing_oneof());
SetCommonOneofVariables(descriptor, info, &variables_);
@@ -603,14 +593,14 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
// ===================================================================
RepeatedImmutableStringFieldLiteGenerator::
-RepeatedImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor,
- int messageBitIndex,
- int builderBitIndex,
- Context* context)
- : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
- builderBitIndex_(builderBitIndex), context_(context),
- name_resolver_(context->GetNameResolver()) {
- SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
+ RepeatedImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context)
+ : descriptor_(descriptor),
+ messageBitIndex_(messageBitIndex),
+ context_(context),
+ name_resolver_(context->GetNameResolver()) {
+ SetPrimitiveVariables(descriptor, messageBitIndex, 0,
context->GetFieldGeneratorInfo(descriptor),
name_resolver_, &variables_);
}
@@ -622,10 +612,6 @@ int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const {
return 0;
}
-int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const {
- return 0;
-}
-
void RepeatedImmutableStringFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
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 b7fb6409..89d5c1ae 100644
--- a/src/google/protobuf/compiler/java/java_string_field_lite.h
+++ b/src/google/protobuf/compiler/java/java_string_field_lite.h
@@ -42,28 +42,30 @@
namespace google {
namespace protobuf {
- namespace compiler {
- namespace java {
- class Context; // context.h
- class ClassNameResolver; // name_resolver.h
- }
- }
-}
+namespace compiler {
+namespace java {
+class Context; // context.h
+class ClassNameResolver; // name_resolver.h
+} // namespace java
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
namespace java {
class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator {
public:
- explicit ImmutableStringFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ explicit ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex,
+ Context* context);
~ImmutableStringFieldLiteGenerator();
- // implements ImmutableFieldLiteGenerator ------------------------------------
+ // implements ImmutableFieldLiteGenerator
+ // ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -79,13 +81,12 @@ class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator {
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
protected:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -96,9 +97,8 @@ class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator {
class ImmutableStringOneofFieldLiteGenerator
: public ImmutableStringFieldLiteGenerator {
public:
- ImmutableStringOneofFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ ImmutableStringOneofFieldLiteGenerator(const FieldDescriptor* descriptor,
+ int messageBitIndex, Context* context);
~ImmutableStringOneofFieldLiteGenerator();
private:
@@ -117,13 +117,11 @@ class RepeatedImmutableStringFieldLiteGenerator
: public ImmutableFieldLiteGenerator {
public:
explicit RepeatedImmutableStringFieldLiteGenerator(
- const FieldDescriptor* descriptor, int messageBitIndex,
- int builderBitIndex, Context* context);
+ const FieldDescriptor* descriptor, int messageBitIndex, Context* context);
~RepeatedImmutableStringFieldLiteGenerator();
// implements ImmutableFieldLiteGenerator ------------------------------------
int GetNumBitsForMessage() const;
- int GetNumBitsForBuilder() const;
void GenerateInterfaceMembers(io::Printer* printer) const;
void GenerateMembers(io::Printer* printer) const;
void GenerateBuilderMembers(io::Printer* printer) const;
@@ -139,13 +137,12 @@ class RepeatedImmutableStringFieldLiteGenerator
void GenerateHashCode(io::Printer* printer) const;
- string GetBoxedType() const;
+ std::string GetBoxedType() const;
private:
const FieldDescriptor* descriptor_;
- std::map<string, string> variables_;
+ std::map<std::string, std::string> variables_;
const int messageBitIndex_;
- const int builderBitIndex_;
Context* context_;
ClassNameResolver* name_resolver_;
@@ -155,6 +152,6 @@ class RepeatedImmutableStringFieldLiteGenerator
} // namespace java
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_LITE_H__
diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc
index b5771f26..5779d5e2 100755..100644
--- a/src/google/protobuf/compiler/js/js_generator.cc
+++ b/src/google/protobuf/compiler/js/js_generator.cc
@@ -42,12 +42,12 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/compiler/js/well_known_types_embed.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>
namespace google {
@@ -220,8 +220,8 @@ string GetNestedMessageName(const Descriptor* descriptor) {
if (descriptor == NULL) {
return "";
}
- string result =
- StripPrefixString(descriptor->full_name(), descriptor->file()->package());
+ string result = StripPrefixString(descriptor->full_name(),
+ descriptor->file()->package());
// Add a leading dot if one is not already present.
if (!result.empty() && result[0] != '.') {
result = "." + result;
@@ -276,7 +276,8 @@ string GetEnumPath(const GeneratorOptions& options,
string MaybeCrossFileRef(const GeneratorOptions& options,
const FileDescriptor* from_file,
const Descriptor* to_message) {
- if (options.import_style == GeneratorOptions::kImportCommonJs &&
+ if ((options.import_style == GeneratorOptions::kImportCommonJs ||
+ options.import_style == GeneratorOptions::kImportCommonJsStrict) &&
from_file != to_message->file()) {
// Cross-file ref in CommonJS needs to use the module alias instead of
// the global name.
@@ -438,9 +439,10 @@ string GetMessageId(const Descriptor* desc) {
bool IgnoreExtensionField(const FieldDescriptor* field) {
// Exclude descriptor extensions from output "to avoid clutter" (from original
// codegen).
- return field->is_extension() &&
- field->containing_type()->file()->name() ==
- "google/protobuf/descriptor.proto";
+ if (!field->is_extension()) return false;
+ const FileDescriptor* file = field->containing_type()->file();
+ return file->name() == "net/proto2/proto/descriptor.proto" ||
+ file->name() == "google/protobuf/descriptor.proto";
}
@@ -452,19 +454,9 @@ bool IgnoreField(const FieldDescriptor* field) {
}
-// Used inside Google only -- do not remove.
-bool ShouldTreatMapsAsRepeatedFields(const FileDescriptor& descriptor) {
- return false;
-}
-
// Do we ignore this message type?
-bool IgnoreMessage(const GeneratorOptions& options, const Descriptor* d) {
- return d->options().map_entry() &&
- !ShouldTreatMapsAsRepeatedFields(*d->file());
-}
-
-bool IsMap(const GeneratorOptions& options, const FieldDescriptor* field) {
- return field->is_map() && !ShouldTreatMapsAsRepeatedFields(*field->file());
+bool IgnoreMessage(const Descriptor* d) {
+ return d->options().map_entry();
}
// Does JSPB ignore this entire oneof? True only if all fields are ignored.
@@ -489,7 +481,7 @@ string JSIdent(const GeneratorOptions& options, const FieldDescriptor* field,
ToUpperCamel(ParseLowerUnderscore(field->name())) :
ToLowerCamel(ParseLowerUnderscore(field->name()));
}
- if (is_map || IsMap(options, field)) {
+ if (is_map || field->is_map()) {
// JSPB-style or proto3-style map.
result += "Map";
} else if (!drop_list && field->is_repeated()) {
@@ -568,7 +560,8 @@ string JSFieldIndex(const FieldDescriptor* field) {
for (int i = 0; i < parent_type->field_count(); i++) {
if (parent_type->field(i)->type() == FieldDescriptor::TYPE_GROUP &&
parent_type->field(i)->message_type() == containing_type) {
- return SimpleItoa(field->number() - parent_type->field(i)->number());
+ return SimpleItoa(field->number() -
+ parent_type->field(i)->number());
}
}
}
@@ -780,7 +773,7 @@ bool IsIntegralFieldWithStringJSType(const FieldDescriptor* field) {
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;
+ return field->options().jstype() == FieldOptions::JS_STRING;
default:
return false;
}
@@ -803,15 +796,15 @@ string JSFieldDefault(const FieldDescriptor* field) {
// The original codegen is in Java, and Java protobufs store unsigned
// integer values as signed integer values. In order to exactly match the
// output, we need to reinterpret as base-2 signed. Ugh.
- return MaybeNumberString(
- field, SimpleItoa(static_cast<int32>(field->default_value_uint32())));
+ return MaybeNumberString(field, SimpleItoa(static_cast<int32>(
+ field->default_value_uint32())));
case FieldDescriptor::CPPTYPE_INT64:
return MaybeNumberString(
field, SimpleItoa(field->default_value_int64()));
case FieldDescriptor::CPPTYPE_UINT64:
// See above note for uint32 -- reinterpreting as signed.
- return MaybeNumberString(
- field, SimpleItoa(static_cast<int64>(field->default_value_uint64())));
+ return MaybeNumberString(field, SimpleItoa(static_cast<int64>(
+ field->default_value_uint64())));
case FieldDescriptor::CPPTYPE_ENUM:
return SimpleItoa(field->default_value_enum()->number());
case FieldDescriptor::CPPTYPE_BOOL:
@@ -1013,11 +1006,11 @@ string JSFieldTypeAnnotation(const GeneratorOptions& options,
bool is_setter_argument,
bool force_present,
bool singular_if_not_packed,
- BytesMode bytes_mode = BYTES_DEFAULT) {
- GOOGLE_CHECK(!(is_setter_argument && force_present));
+ BytesMode bytes_mode = BYTES_DEFAULT,
+ bool force_singular = false) {
string jstype = JSTypeName(options, field, bytes_mode);
- if (field->is_repeated() &&
+ if (!force_singular && field->is_repeated() &&
(field->is_packed() || !singular_if_not_packed)) {
if (field->type() == FieldDescriptor::TYPE_BYTES &&
bytes_mode == BYTES_DEFAULT) {
@@ -1135,7 +1128,7 @@ string JSReturnDoc(const GeneratorOptions& options,
bool HasRepeatedFields(const GeneratorOptions& options,
const Descriptor* desc) {
for (int i = 0; i < desc->field_count(); i++) {
- if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) {
+ if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) {
return true;
}
}
@@ -1173,7 +1166,7 @@ string RepeatedFieldNumberList(const GeneratorOptions& options,
const Descriptor* desc) {
std::vector<string> numbers;
for (int i = 0; i < desc->field_count(); i++) {
- if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) {
+ if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) {
numbers.push_back(JSFieldIndex(desc->field(i)));
}
}
@@ -1259,7 +1252,7 @@ const FieldDescriptor* MapFieldValue(const FieldDescriptor* field) {
string FieldDefinition(const GeneratorOptions& options,
const FieldDescriptor* field) {
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
string key_type = ProtoTypeName(options, key_field);
@@ -1351,7 +1344,7 @@ bool HasExtensions(const FileDescriptor* file) {
bool HasMap(const GeneratorOptions& options, const Descriptor* desc) {
for (int i = 0; i < desc->field_count(); i++) {
- if (IsMap(options, desc->field(i))) {
+ if (desc->field(i)->is_map()) {
return true;
}
}
@@ -1617,7 +1610,7 @@ void Generator::FindProvidesForMessage(
io::Printer* printer,
const Descriptor* desc,
std::set<string>* provided) const {
- if (IgnoreMessage(options, desc)) {
+ if (IgnoreMessage(desc)) {
return;
}
@@ -1675,8 +1668,19 @@ void Generator::GenerateProvides(const GeneratorOptions& options,
//
// // Later generated code expects foo.bar = {} to exist:
// foo.bar.Baz = function() { /* ... */ }
- printer->Print("goog.exportSymbol('$name$', null, global);\n", "name",
- *it);
+
+ // Do not use global scope in strict mode
+ if (options.import_style == GeneratorOptions::kImportCommonJsStrict) {
+ string namespaceObject = *it;
+ // Remove "proto." from the namespace object
+ GOOGLE_CHECK_EQ(0, namespaceObject.compare(0, 6, "proto."));
+ namespaceObject.erase(0, 6);
+ printer->Print("goog.exportSymbol('$name$', null, proto);\n", "name",
+ namespaceObject);
+ } else {
+ printer->Print("goog.exportSymbol('$name$', null, global);\n", "name",
+ *it);
+ }
}
}
}
@@ -1712,7 +1716,7 @@ void Generator::GenerateRequiresForLibrary(
for (int i = 0; i < files.size(); i++) {
for (int j = 0; j < files[i]->message_type_count(); j++) {
const Descriptor* desc = files[i]->message_type(j);
- if (!IgnoreMessage(options, desc)) {
+ if (!IgnoreMessage(desc)) {
FindRequiresForMessage(options, desc, &required, &forwards,
&have_message);
}
@@ -1857,7 +1861,7 @@ void Generator::FindRequiresForField(const GeneratorOptions& options,
forwards->insert(GetEnumPath(options, field->enum_type()));
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- if (!IgnoreMessage(options, field->message_type())) {
+ if (!IgnoreMessage(field->message_type())) {
required->insert(GetMessagePath(options, field->message_type()));
}
}
@@ -1895,7 +1899,7 @@ void Generator::GenerateClassesAndEnums(const GeneratorOptions& options,
void Generator::GenerateClass(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc) const {
- if (IgnoreMessage(options, desc)) {
+ if (IgnoreMessage(desc)) {
return;
}
@@ -2217,7 +2221,7 @@ void Generator::GenerateClassFieldToObject(const GeneratorOptions& options,
printer->Print("$fieldname$: ",
"fieldname", JSObjectFieldName(options, field));
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* value_field = MapFieldValue(field);
// If the map values are of a message type, we must provide their static
// toObject() method; otherwise we pass undefined for that argument.
@@ -2285,7 +2289,7 @@ void Generator::GenerateClassFromObject(const GeneratorOptions& options,
" * @return {!$classname$}\n"
" */\n"
"$classname$.fromObject = function(obj) {\n"
- " var f, msg = new $classname$();\n",
+ " var msg = new $classname$();\n",
"classname", GetMessagePath(options, desc));
for (int i = 0; i < desc->field_count(); i++) {
@@ -2303,7 +2307,7 @@ void Generator::GenerateClassFieldFromObject(
const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* value_field = MapFieldValue(field);
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
// Since the map values are of message type, we have to do some extra work
@@ -2415,7 +2419,7 @@ void GenerateBytesWrapper(const GeneratorOptions& options,
void Generator::GenerateClassField(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
// Map field: special handling to instantiate the map object on demand.
@@ -2695,7 +2699,7 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
// Generate clearFoo() method for map fields, repeated fields, and other
// fields with presence.
- if (IsMap(options, field)) {
+ if (field->is_map()) {
printer->Print(
"$class$.prototype.$clearername$ = function() {\n"
" this.$gettername$().clear();$returnvalue$\n"
@@ -2750,7 +2754,7 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
printer->Print(
"/**\n"
" * Returns whether this field is set.\n"
- " * @return {!boolean}\n"
+ " * @return {boolean}\n"
" */\n"
"$class$.prototype.$hasername$ = function() {\n"
" return jspb.Message.getField(this, $index$) != null;\n"
@@ -2770,7 +2774,7 @@ void Generator::GenerateRepeatedPrimitiveHelperMethods(
// clang-format off
printer->Print(
"/**\n"
- " * @param {!$optionaltype$} value\n"
+ " * @param {$optionaltype$} value\n"
" * @param {number=} opt_index$returndoc$\n"
" */\n"
"$class$.prototype.$addername$ = function(value, opt_index) {\n"
@@ -2778,7 +2782,14 @@ void Generator::GenerateRepeatedPrimitiveHelperMethods(
"class", GetMessagePath(options, field->containing_type()), "addername",
"add" + JSGetterName(options, field, BYTES_DEFAULT,
/* drop_list = */ true),
- "optionaltype", JSTypeName(options, field, BYTES_DEFAULT),
+ "optionaltype",
+ JSFieldTypeAnnotation(
+ options, field,
+ /* is_setter_argument = */ false,
+ /* force_present = */ true,
+ /* singular_if_not_packed = */ false,
+ BYTES_DEFAULT,
+ /* force_singular = */ true),
"index", JSFieldIndex(field),
"returndoc", JSReturnDoc(options, field));
printer->Annotate("addername", field);
@@ -2942,11 +2953,10 @@ void Generator::GenerateClassDeserializeBinaryField(
const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
+ printer->Print(" case $num$:\n", "num",
+ SimpleItoa(field->number()));
- printer->Print(" case $num$:\n",
- "num", SimpleItoa(field->number()));
-
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
printer->Print(
@@ -2976,11 +2986,12 @@ void Generator::GenerateClassDeserializeBinaryField(
" var value = new $fieldclass$;\n"
" reader.read$msgOrGroup$($grpfield$value,"
"$fieldclass$.deserializeBinaryFromReader);\n",
- "fieldclass", SubmessageTypeRef(options, field),
- "msgOrGroup", (field->type() == FieldDescriptor::TYPE_GROUP) ?
- "Group" : "Message",
- "grpfield", (field->type() == FieldDescriptor::TYPE_GROUP) ?
- (SimpleItoa(field->number()) + ", ") : "");
+ "fieldclass", SubmessageTypeRef(options, field), "msgOrGroup",
+ (field->type() == FieldDescriptor::TYPE_GROUP) ? "Group" : "Message",
+ "grpfield",
+ (field->type() == FieldDescriptor::TYPE_GROUP)
+ ? (SimpleItoa(field->number()) + ", ")
+ : "");
} else {
printer->Print(
" var value = /** @type {$fieldtype$} */ "
@@ -3078,12 +3089,12 @@ void Generator::GenerateClassSerializeBinaryField(
" f = message.get$name$($nolazy$);\n",
"name", JSGetterName(options, field, BYTES_U8),
// No lazy creation for maps containers -- fastpath the empty case.
- "nolazy", IsMap(options, field) ? "true" : "");
+ "nolazy", field->is_map() ? "true" : "");
}
// Print an `if (condition)` statement that evaluates to true if the field
// goes on the wire.
- if (IsMap(options, field)) {
+ if (field->is_map()) {
printer->Print(
" if (f && f.getLength() > 0) {\n");
} else if (field->is_repeated()) {
@@ -3136,15 +3147,15 @@ void Generator::GenerateClassSerializeBinaryField(
}
// Write the field on the wire.
- if (IsMap(options, field)) {
+ if (field->is_map()) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
printer->Print(
" f.serializeBinary($index$, writer, "
- "$keyWriterFn$, $valueWriterFn$",
- "index", SimpleItoa(field->number()),
- "keyWriterFn", JSBinaryWriterMethodName(options, key_field),
- "valueWriterFn", JSBinaryWriterMethodName(options, value_field));
+ "$keyWriterFn$, $valueWriterFn$",
+ "index", SimpleItoa(field->number()), "keyWriterFn",
+ JSBinaryWriterMethodName(options, key_field), "valueWriterFn",
+ JSBinaryWriterMethodName(options, value_field));
if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) {
printer->Print(", $messageType$.serializeBinaryToWriter",
@@ -3161,7 +3172,7 @@ void Generator::GenerateClassSerializeBinaryField(
"index", SimpleItoa(field->number()));
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
- !IsMap(options, field)) {
+ !field->is_map()) {
printer->Print(
",\n"
" $submsg$.serializeBinaryToWriter\n",
@@ -3193,11 +3204,10 @@ void Generator::GenerateEnum(const GeneratorOptions& options,
for (int i = 0; i < enumdesc->value_count(); i++) {
const EnumValueDescriptor* value = enumdesc->value(i);
- printer->Print(
- " $name$: $value$$comma$\n",
- "name", ToEnumCase(value->name()),
- "value", SimpleItoa(value->number()),
- "comma", (i == enumdesc->value_count() - 1) ? "" : ",");
+ printer->Print(" $name$: $value$$comma$\n", "name",
+ ToEnumCase(value->name()), "value",
+ SimpleItoa(value->number()), "comma",
+ (i == enumdesc->value_count() - 1) ? "" : ",");
printer->Annotate("name", value);
}
@@ -3240,13 +3250,15 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
"!Object} */ (\n"
" $toObject$),\n"
" $repeated$);\n",
- "index", SimpleItoa(field->number()),
- "name", extension_object_name,
- "ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ?
- SubmessageTypeRef(options, field) : string("null")),
- "toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ?
- (SubmessageTypeRef(options, field) + ".toObject") :
- string("null")),
+ "index", SimpleItoa(field->number()), "name",
+ extension_object_name, "ctor",
+ (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE
+ ? SubmessageTypeRef(options, field)
+ : string("null")),
+ "toObject",
+ (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE
+ ? (SubmessageTypeRef(options, field) + ".toObject")
+ : string("null")),
"repeated", (field->is_repeated() ? "1" : "0"));
printer->Print(
@@ -3259,8 +3271,8 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
" $binaryMessageDeserializeFn$,\n",
"extendName",
JSExtensionsObjectName(options, field->file(), field->containing_type()),
- "index", SimpleItoa(field->number()), "class", extension_scope, "name",
- extension_object_name, "binaryReaderFn",
+ "index", SimpleItoa(field->number()), "class", extension_scope,
+ "name", extension_object_name, "binaryReaderFn",
JSBinaryReaderMethodName(options, field), "binaryWriterFn",
JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn",
(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
@@ -3279,10 +3291,9 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
"// toObject() will function correctly.\n"
"$extendName$[$index$] = $class$.$name$;\n"
"\n",
- "extendName", JSExtensionsObjectName(options, field->file(),
- field->containing_type()),
- "index", SimpleItoa(field->number()),
- "class", extension_scope,
+ "extendName",
+ JSExtensionsObjectName(options, field->file(), field->containing_type()),
+ "index", SimpleItoa(field->number()), "class", extension_scope,
"name", extension_object_name);
}
@@ -3325,6 +3336,8 @@ bool GeneratorOptions::ParseFromOptions(
import_style = kImportClosure;
} else if (options[i].second == "commonjs") {
import_style = kImportCommonJs;
+ } else if (options[i].second == "commonjs_strict") {
+ import_style = kImportCommonJsStrict;
} else if (options[i].second == "browser") {
import_style = kImportBrowser;
} else if (options[i].second == "es6") {
@@ -3434,17 +3447,24 @@ void Generator::GenerateFile(const GeneratorOptions& options,
GenerateHeader(options, printer);
// Generate "require" statements.
- if (options.import_style == GeneratorOptions::kImportCommonJs) {
+ if ((options.import_style == GeneratorOptions::kImportCommonJs ||
+ options.import_style == GeneratorOptions::kImportCommonJsStrict)) {
printer->Print("var jspb = require('google-protobuf');\n");
printer->Print("var goog = jspb;\n");
- printer->Print("var global = Function('return this')();\n\n");
+
+ // Do not use global scope in strict mode
+ if (options.import_style == GeneratorOptions::kImportCommonJsStrict) {
+ printer->Print("var proto = {};\n\n");
+ } else {
+ printer->Print("var global = Function('return this')();\n\n");
+ }
for (int i = 0; i < file->dependency_count(); i++) {
const string& name = file->dependency(i)->name();
printer->Print(
- "var $alias$ = require('$file$');\n",
- "alias", ModuleAlias(name),
- "file",
+ "var $alias$ = require('$file$');\n"
+ "goog.object.extend(proto, $alias$);\n",
+ "alias", ModuleAlias(name), "file",
GetRootPath(file->name(), name) + GetJSFilename(options, name));
}
}
@@ -3481,9 +3501,14 @@ void Generator::GenerateFile(const GeneratorOptions& options,
GenerateExtension(options, printer, *it);
}
- if (options.import_style == GeneratorOptions::kImportCommonJs) {
+ // if provided is empty, do not export anything
+ if (options.import_style == GeneratorOptions::kImportCommonJs &&
+ !provided.empty()) {
printer->Print("goog.object.extend(exports, $package$);\n",
"package", GetFilePath(options, file));
+ } else if (options.import_style == GeneratorOptions::kImportCommonJsStrict) {
+ printer->Print("goog.object.extend(exports, proto);\n", "package",
+ GetFilePath(options, file));
}
// Emit well-known type methods.
@@ -3641,7 +3666,7 @@ bool Generator::GenerateAll(const std::vector<const FileDescriptor*>& files,
// Generate one output file per input (.proto) file.
for (int i = 0; i < files.size(); i++) {
- const google::protobuf::FileDescriptor* file = files[i];
+ const FileDescriptor* file = files[i];
string filename =
options.output_dir + "/" + GetJSFilename(options, file->name());
diff --git a/src/google/protobuf/compiler/js/js_generator.h b/src/google/protobuf/compiler/js/js_generator.h
index 3cc60e22..4567b07a 100755..100644
--- a/src/google/protobuf/compiler/js/js_generator.h
+++ b/src/google/protobuf/compiler/js/js_generator.h
@@ -40,6 +40,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -56,17 +58,18 @@ namespace js {
struct GeneratorOptions {
// Output path.
- string output_dir;
+ std::string output_dir;
// Namespace prefix.
- string namespace_prefix;
+ std::string namespace_prefix;
// Enable binary-format support?
bool binary;
// What style of imports should be used.
enum ImportStyle {
- kImportClosure, // goog.require()
- kImportCommonJs, // require()
- kImportBrowser, // no import statements
- kImportEs6, // import { member } from ''
+ kImportClosure, // goog.require()
+ kImportCommonJs, // require()
+ kImportCommonJsStrict, // require() with no global export
+ kImportBrowser, // no import statements
+ kImportEs6, // import { member } from ''
} import_style;
GeneratorOptions()
@@ -83,11 +86,11 @@ struct GeneratorOptions {
annotate_code(false) {}
bool ParseFromOptions(
- const std::vector< std::pair< string, string > >& options,
- string* error);
+ const std::vector< std::pair< std::string, std::string > >& options,
+ std::string* error);
// Returns the file name extension to use for generated code.
- string GetFileNameExtension() const {
+ std::string GetFileNameExtension() const {
return import_style == kImportClosure ? extension : "_pb.js";
}
@@ -112,11 +115,11 @@ struct GeneratorOptions {
bool testonly;
// Create a library with name <name>_lib.js rather than a separate .js file
// per type?
- string library;
+ std::string library;
// Error if there are two types that would generate the same output file?
bool error_on_name_conflict;
// The extension to use for output file names.
- string extension;
+ std::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
@@ -128,15 +131,15 @@ struct GeneratorOptions {
// header. If you create your own protocol compiler binary and you want it to
// support JavaScript output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT Generator : public CodeGenerator {
+class PROTOC_EXPORT Generator : public CodeGenerator {
public:
Generator() {}
virtual ~Generator() {}
virtual bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* context,
- string* error) const {
+ std::string* error) const {
*error = "Unimplemented Generate() method. Call GenerateAll() instead.";
return false;
}
@@ -144,9 +147,9 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
virtual bool HasGenerateAll() const { return true; }
virtual bool GenerateAll(const std::vector<const FileDescriptor*>& files,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* context,
- string* error) const;
+ std::string* error) const;
private:
void GenerateHeader(const GeneratorOptions& options,
@@ -156,28 +159,28 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void FindProvides(const GeneratorOptions& options,
io::Printer* printer,
const std::vector<const FileDescriptor*>& file,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
void FindProvidesForFile(const GeneratorOptions& options,
io::Printer* printer,
const FileDescriptor* file,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
void FindProvidesForMessage(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
void FindProvidesForEnum(const GeneratorOptions& options,
io::Printer* printer,
const EnumDescriptor* enumdesc,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
// For extension fields at file scope.
void FindProvidesForFields(const GeneratorOptions& options,
io::Printer* printer,
const std::vector<const FieldDescriptor*>& fields,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
// Print the goog.provides() found by the methods above.
void GenerateProvides(const GeneratorOptions& options,
io::Printer* printer,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
// Generate goog.setTestOnly() if indicated.
void GenerateTestOnly(const GeneratorOptions& options,
@@ -187,34 +190,34 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void GenerateRequiresForLibrary(
const GeneratorOptions& options, io::Printer* printer,
const std::vector<const FileDescriptor*>& files,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
void GenerateRequiresForMessage(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
// For extension fields at file scope.
void GenerateRequiresForExtensions(
const GeneratorOptions& options, io::Printer* printer,
const std::vector<const FieldDescriptor*>& fields,
- std::set<string>* provided) const;
+ std::set<std::string>* provided) const;
void GenerateRequiresImpl(const GeneratorOptions& options,
- io::Printer* printer, std::set<string>* required,
- std::set<string>* forwards,
- std::set<string>* provided, bool require_jspb,
+ io::Printer* printer, std::set<std::string>* required,
+ std::set<std::string>* forwards,
+ std::set<std::string>* provided, bool require_jspb,
bool require_extension, bool require_map) const;
void FindRequiresForMessage(const GeneratorOptions& options,
const Descriptor* desc,
- std::set<string>* required,
- std::set<string>* forwards,
+ std::set<std::string>* required,
+ std::set<std::string>* forwards,
bool* have_message) const;
void FindRequiresForField(const GeneratorOptions& options,
const FieldDescriptor* field,
- std::set<string>* required,
- std::set<string>* forwards) const;
+ std::set<std::string>* required,
+ std::set<std::string>* forwards) const;
void FindRequiresForExtension(const GeneratorOptions& options,
const FieldDescriptor* field,
- std::set<string>* required,
- std::set<string>* forwards) const;
+ std::set<std::string>* required,
+ std::set<std::string>* forwards) const;
void GenerateFile(const GeneratorOptions& options,
io::Printer* printer,
@@ -328,6 +331,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
} // namespace js
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/js/well_known_types/struct.js b/src/google/protobuf/compiler/js/well_known_types/struct.js
deleted file mode 100644
index 30e3d02a..00000000
--- a/src/google/protobuf/compiler/js/well_known_types/struct.js
+++ /dev/null
@@ -1,168 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/* This code will be inserted into generated code for
- * google/protobuf/struct.proto. */
-
-/**
- * Typedef representing plain JavaScript values that can go into a
- * Struct.
- * @typedef {null|number|string|boolean|Array|Object}
- */
-proto.google.protobuf.JavaScriptValue;
-
-
-/**
- * Converts this Value object to a plain JavaScript value.
- * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript
- * value representing this Struct.
- */
-proto.google.protobuf.Value.prototype.toJavaScript = function() {
- var kindCase = proto.google.protobuf.Value.KindCase;
- switch (this.getKindCase()) {
- case kindCase.NULL_VALUE:
- return null;
- case kindCase.NUMBER_VALUE:
- return this.getNumberValue();
- case kindCase.STRING_VALUE:
- return this.getStringValue();
- case kindCase.BOOL_VALUE:
- return this.getBoolValue();
- case kindCase.STRUCT_VALUE:
- return this.getStructValue().toJavaScript();
- case kindCase.LIST_VALUE:
- return this.getListValue().toJavaScript();
- default:
- throw new Error('Unexpected struct type');
- }
-};
-
-
-/**
- * Converts this JavaScript value to a new Value proto.
- * @param {!proto.google.protobuf.JavaScriptValue} value The value to
- * convert.
- * @return {!proto.google.protobuf.Value} The newly constructed value.
- */
-proto.google.protobuf.Value.fromJavaScript = function(value) {
- var ret = new proto.google.protobuf.Value();
- switch (goog.typeOf(value)) {
- case 'string':
- ret.setStringValue(/** @type {string} */ (value));
- break;
- case 'number':
- ret.setNumberValue(/** @type {number} */ (value));
- break;
- case 'boolean':
- ret.setBoolValue(/** @type {boolean} */ (value));
- break;
- case 'null':
- ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);
- break;
- case 'array':
- ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(
- /** @type{!Array} */ (value)));
- break;
- case 'object':
- ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(
- /** @type{!Object} */ (value)));
- break;
- default:
- throw new Error('Unexpected struct type.');
- }
-
- return ret;
-};
-
-
-/**
- * Converts this ListValue object to a plain JavaScript array.
- * @return {!Array} a plain JavaScript array representing this List.
- */
-proto.google.protobuf.ListValue.prototype.toJavaScript = function() {
- var ret = [];
- var values = this.getValuesList();
-
- for (var i = 0; i < values.length; i++) {
- ret[i] = values[i].toJavaScript();
- }
-
- return ret;
-};
-
-
-/**
- * Constructs a ListValue protobuf from this plain JavaScript array.
- * @param {!Array} array a plain JavaScript array
- * @return {proto.google.protobuf.ListValue} a new ListValue object
- */
-proto.google.protobuf.ListValue.fromJavaScript = function(array) {
- var ret = new proto.google.protobuf.ListValue();
-
- for (var i = 0; i < array.length; i++) {
- ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));
- }
-
- return ret;
-};
-
-
-/**
- * Converts this Struct object to a plain JavaScript object.
- * @return {!Object<string, !proto.google.protobuf.JavaScriptValue>} a plain
- * JavaScript object representing this Struct.
- */
-proto.google.protobuf.Struct.prototype.toJavaScript = function() {
- var ret = {};
-
- this.getFieldsMap().forEach(function(value, key) {
- ret[key] = value.toJavaScript();
- });
-
- return ret;
-};
-
-
-/**
- * Constructs a Struct protobuf from this plain JavaScript object.
- * @param {!Object} obj a plain JavaScript object
- * @return {proto.google.protobuf.Struct} a new Struct object
- */
-proto.google.protobuf.Struct.fromJavaScript = function(obj) {
- var ret = new proto.google.protobuf.Struct();
- var map = ret.getFieldsMap();
-
- for (var property in obj) {
- var val = obj[property];
- map.set(property, proto.google.protobuf.Value.fromJavaScript(val));
- }
-
- return ret;
-};
diff --git a/src/google/protobuf/compiler/js/well_known_types_embed.cc b/src/google/protobuf/compiler/js/well_known_types_embed.cc
index e5ee5510..c00c60cb 100644
--- a/src/google/protobuf/compiler/js/well_known_types_embed.cc
+++ b/src/google/protobuf/compiler/js/well_known_types_embed.cc
@@ -1,3 +1,33 @@
+// 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/js/well_known_types_embed.h>
struct FileToc well_known_types_js[] = {
diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc
index 1db35441..8be2652a 100644
--- a/src/google/protobuf/compiler/main.cc
+++ b/src/google/protobuf/compiler/main.cc
@@ -30,71 +30,80 @@
// Author: kenton@google.com (Kenton Varda)
-#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
-
-#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
-#include <google/protobuf/compiler/python/python_generator.h>
#include <google/protobuf/compiler/java/java_generator.h>
-#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
+#include <google/protobuf/compiler/command_line_interface.h>
+#include <google/protobuf/compiler/python/python_generator.h>
-#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
#include <google/protobuf/compiler/csharp/csharp_generator.h>
#include <google/protobuf/compiler/js/js_generator.h>
#include <google/protobuf/compiler/objectivec/objectivec_generator.h>
#include <google/protobuf/compiler/php/php_generator.h>
#include <google/protobuf/compiler/ruby/ruby_generator.h>
-#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
-int main(int argc, char* argv[]) {
+namespace google {
+namespace protobuf {
+namespace compiler {
- google::protobuf::compiler::CommandLineInterface cli;
+int ProtobufMain(int argc, char* argv[]) {
+
+ CommandLineInterface cli;
cli.AllowPlugins("protoc-");
// Proto2 C++
- google::protobuf::compiler::cpp::CppGenerator cpp_generator;
+ cpp::CppGenerator cpp_generator;
cli.RegisterGenerator("--cpp_out", "--cpp_opt", &cpp_generator,
"Generate C++ header and source.");
-#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
+#ifdef GOOGLE_PROTOBUF_USE_OPENSOURCE_GOOGLE3_RUNTIME
+ cpp_generator.set_runtime(cpp::CppGenerator::Runtime::kOpensourceGoogle3);
+#elif defined(GOOGLE_PROTOBUF_USE_OPENSOURCE_RUNTIME)
+ cpp_generator.set_runtime(cpp::CppGenerator::Runtime::kOpensource);
+#endif
+
// Proto2 Java
- google::protobuf::compiler::java::JavaGenerator java_generator;
+ java::JavaGenerator java_generator;
cli.RegisterGenerator("--java_out", "--java_opt", &java_generator,
"Generate Java source file.");
-#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
-#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
// Proto2 Python
- google::protobuf::compiler::python::Generator py_generator;
+ python::Generator py_generator;
cli.RegisterGenerator("--python_out", &py_generator,
"Generate Python source file.");
// PHP
- google::protobuf::compiler::php::Generator php_generator;
+ php::Generator php_generator;
cli.RegisterGenerator("--php_out", &php_generator,
"Generate PHP source file.");
// Ruby
- google::protobuf::compiler::ruby::Generator rb_generator;
+ ruby::Generator rb_generator;
cli.RegisterGenerator("--ruby_out", &rb_generator,
"Generate Ruby source file.");
// CSharp
- google::protobuf::compiler::csharp::Generator csharp_generator;
+ csharp::Generator csharp_generator;
cli.RegisterGenerator("--csharp_out", "--csharp_opt", &csharp_generator,
"Generate C# source file.");
// Objective C
- google::protobuf::compiler::objectivec::ObjectiveCGenerator objc_generator;
+ objectivec::ObjectiveCGenerator objc_generator;
cli.RegisterGenerator("--objc_out", "--objc_opt", &objc_generator,
"Generate Objective C header and source.");
// JavaScript
- google::protobuf::compiler::js::Generator js_generator;
+ js::Generator js_generator;
cli.RegisterGenerator("--js_out", &js_generator,
"Generate JavaScript source.");
-#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
return cli.Run(argc, argv);
}
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
+int main(int argc, char* argv[]) {
+ return google::protobuf::compiler::ProtobufMain(argc, argv);
+}
diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc
index e150f97d..4bb1d872 100644
--- a/src/google/protobuf/compiler/mock_code_generator.cc
+++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -36,9 +36,9 @@
#include <iostream>
#include <memory>
#include <vector>
+#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -179,7 +179,7 @@ bool MockCodeGenerator::Generate(
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(),
- "MockCodeGenerator_");
+ "MockCodeGenerator_");
if (command == "Error") {
*error = "Saw message type MockCodeGenerator_Error.";
return false;
@@ -223,8 +223,8 @@ bool MockCodeGenerator::Generate(
if (HasPrefixString(parameter, "insert=")) {
std::vector<string> insert_into;
- SplitStringUsing(StripPrefixString(parameter, "insert="),
- ",", &insert_into);
+ SplitStringUsing(StripPrefixString(parameter, "insert="), ",",
+ &insert_into);
for (size_t i = 0; i < insert_into.size(); i++) {
{
diff --git a/src/google/protobuf/compiler/mock_code_generator.h b/src/google/protobuf/compiler/mock_code_generator.h
index cdd9138c..e6370b34 100644
--- a/src/google/protobuf/compiler/mock_code_generator.h
+++ b/src/google/protobuf/compiler/mock_code_generator.h
@@ -41,7 +41,9 @@ namespace google {
namespace protobuf {
class FileDescriptor;
} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace compiler {
@@ -72,7 +74,7 @@ namespace compiler {
// that can later be verified with CheckGeneratedAnnotations.
class MockCodeGenerator : public CodeGenerator {
public:
- MockCodeGenerator(const string& name);
+ MockCodeGenerator(const std::string& name);
virtual ~MockCodeGenerator();
// Expect (via gTest) that a MockCodeGenerator with the given name was called
@@ -82,49 +84,49 @@ class MockCodeGenerator : public CodeGenerator {
// should have inserted lines into this file.
// |parsed_file_list| is a comma-separated list of names of the files
// that are being compiled together in this run.
- static void ExpectGenerated(const string& name,
- const string& parameter,
- const string& insertions,
- const string& file,
- const string& first_message_name,
- const string& parsed_file_list,
- const string& output_directory);
+ static void ExpectGenerated(const std::string& name,
+ const std::string& parameter,
+ const std::string& insertions,
+ const std::string& file,
+ const std::string& first_message_name,
+ const std::string& parsed_file_list,
+ const std::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);
+ static void CheckGeneratedAnnotations(const std::string& name,
+ const std::string& file,
+ const std::string& output_directory);
// Get the name of the file which would be written by the given generator.
- static string GetOutputFileName(const string& generator_name,
+ static std::string GetOutputFileName(const std::string& generator_name,
const FileDescriptor* file);
- static string GetOutputFileName(const string& generator_name,
- const string& file);
+ static std::string GetOutputFileName(const std::string& generator_name,
+ const std::string& file);
// implements CodeGenerator ----------------------------------------
virtual bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* context,
- string* error) const;
+ std::string* error) const;
private:
- string name_;
+ std::string name_;
- static string GetOutputFileContent(const string& generator_name,
- const string& parameter,
+ static std::string GetOutputFileContent(const std::string& generator_name,
+ const std::string& parameter,
const FileDescriptor* file,
GeneratorContext *context);
- static string GetOutputFileContent(const string& generator_name,
- const string& parameter,
- const string& file,
- const string& parsed_file_list,
- const string& first_message_name);
+ static std::string GetOutputFileContent(const std::string& generator_name,
+ const std::string& parameter,
+ const std::string& file,
+ const std::string& parsed_file_list,
+ const std::string& first_message_name);
};
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_COMPILER_MOCK_CODE_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
index 3e43f732..ac20cfdb 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
@@ -36,6 +36,8 @@
#include <string>
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -45,7 +47,7 @@ namespace objectivec {
// header. If you create your own protocol compiler binary and you want it to
// support ObjectiveC output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator {
+class PROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator {
public:
ObjectiveCGenerator();
~ObjectiveCGenerator();
@@ -69,4 +71,7 @@ class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator {
} // namespace compiler
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index df71c8bb..0afa6fb0 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -38,6 +38,7 @@
#include <iostream>
#include <sstream>
#include <stdlib.h>
+#include <unordered_set>
#include <vector>
#include <google/protobuf/stubs/hash.h>
@@ -79,8 +80,8 @@ Options::Options() {
namespace {
-hash_set<string> MakeWordsMap(const char* const words[], size_t num_words) {
- hash_set<string> result;
+std::unordered_set<string> MakeWordsMap(const char* const words[], size_t num_words) {
+ std::unordered_set<string> result;
for (int i = 0; i < num_words; i++) {
result.insert(words[i]);
}
@@ -89,7 +90,7 @@ hash_set<string> MakeWordsMap(const char* const words[], size_t num_words) {
const char* const kUpperSegmentsList[] = {"url", "http", "https"};
-hash_set<string> kUpperSegments =
+std::unordered_set<string> kUpperSegments =
MakeWordsMap(kUpperSegmentsList, GOOGLE_ARRAYSIZE(kUpperSegmentsList));
bool ascii_isnewline(char c) {
@@ -217,7 +218,7 @@ const char* const kReservedWordList[] = {
"StyleParameter", "StyleField", "TimeScale", "TimeBase", "TimeRecord",
};
-hash_set<string> kReservedWords =
+std::unordered_set<string> kReservedWords =
MakeWordsMap(kReservedWordList, GOOGLE_ARRAYSIZE(kReservedWordList));
string SanitizeNameForObjC(const string& input,
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index 8999aa59..e7f21f28 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -39,6 +39,8 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -53,66 +55,67 @@ struct Options {
};
// Escape C++ trigraphs by escaping question marks to "\?".
-string LIBPROTOC_EXPORT EscapeTrigraphs(const string& to_escape);
+string PROTOC_EXPORT EscapeTrigraphs(const string& to_escape);
// Strips ".proto" or ".protodevel" from the end of a filename.
-string LIBPROTOC_EXPORT StripProto(const string& filename);
+string PROTOC_EXPORT StripProto(const string& filename);
// Remove white space from either end of a StringPiece.
-void LIBPROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input);
+void PROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input);
// Returns true if the name requires a ns_returns_not_retained attribute applied
// to it.
-bool LIBPROTOC_EXPORT IsRetainedName(const string& name);
+bool PROTOC_EXPORT IsRetainedName(const string& name);
// Returns true if the name starts with "init" and will need to have special
// handling under ARC.
-bool LIBPROTOC_EXPORT IsInitName(const string& name);
+bool PROTOC_EXPORT IsInitName(const string& name);
// Gets the objc_class_prefix.
-string LIBPROTOC_EXPORT FileClassPrefix(const FileDescriptor* file);
+string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file);
// Gets the path of the file we're going to generate (sans the .pb.h
// extension). The path will be dependent on the objectivec package
// declared in the proto package.
-string LIBPROTOC_EXPORT FilePath(const FileDescriptor* file);
+string PROTOC_EXPORT FilePath(const FileDescriptor* file);
// Just like FilePath(), but without the directory part.
-string LIBPROTOC_EXPORT FilePathBasename(const FileDescriptor* file);
+string PROTOC_EXPORT FilePathBasename(const FileDescriptor* file);
// Gets the name of the root class we'll generate in the file. This class
// is not meant for external consumption, but instead contains helpers that
// the rest of the classes need
-string LIBPROTOC_EXPORT FileClassName(const FileDescriptor* file);
+string PROTOC_EXPORT FileClassName(const FileDescriptor* file);
// These return the fully-qualified class name corresponding to the given
// descriptor.
-string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor);
-string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor, string* out_suffix_added);
-string LIBPROTOC_EXPORT EnumName(const EnumDescriptor* descriptor);
+string PROTOC_EXPORT ClassName(const Descriptor* descriptor);
+string PROTOC_EXPORT ClassName(const Descriptor* descriptor,
+ string* out_suffix_added);
+string PROTOC_EXPORT EnumName(const EnumDescriptor* descriptor);
// Returns the fully-qualified name of the enum value corresponding to the
// the descriptor.
-string LIBPROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor);
+string PROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor);
// Returns the name of the enum value corresponding to the descriptor.
-string LIBPROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor);
+string PROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor);
// Reverse what an enum does.
-string LIBPROTOC_EXPORT UnCamelCaseEnumShortName(const string& name);
+string PROTOC_EXPORT UnCamelCaseEnumShortName(const string& name);
// Returns the name to use for the extension (used as the method off the file's
// Root class).
-string LIBPROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor);
+string PROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor);
// Returns the transformed field name.
-string LIBPROTOC_EXPORT FieldName(const FieldDescriptor* field);
-string LIBPROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field);
+string PROTOC_EXPORT FieldName(const FieldDescriptor* field);
+string PROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field);
// Returns the transformed oneof name.
-string LIBPROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor);
-string LIBPROTOC_EXPORT OneofName(const OneofDescriptor* descriptor);
-string LIBPROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor);
+string PROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor);
+string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor);
+string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor);
inline bool HasFieldPresence(const FileDescriptor* file) {
return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
@@ -127,7 +130,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) {
}
// Reverse of the above.
-string LIBPROTOC_EXPORT UnCamelCaseFieldName(const string& name, const FieldDescriptor* field);
+string PROTOC_EXPORT UnCamelCaseFieldName(const string& name,
+ const FieldDescriptor* field);
enum ObjectiveCType {
OBJECTIVECTYPE_INT32,
@@ -175,48 +179,52 @@ string GetOptionalDeprecatedAttribute(
}
}
-string LIBPROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field);
+string PROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field);
-ObjectiveCType LIBPROTOC_EXPORT GetObjectiveCType(FieldDescriptor::Type field_type);
+ObjectiveCType PROTOC_EXPORT
+GetObjectiveCType(FieldDescriptor::Type field_type);
inline ObjectiveCType GetObjectiveCType(const FieldDescriptor* field) {
return GetObjectiveCType(field->type());
}
-bool LIBPROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field);
-bool LIBPROTOC_EXPORT IsReferenceType(const FieldDescriptor* field);
+bool PROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field);
+bool PROTOC_EXPORT IsReferenceType(const FieldDescriptor* field);
-string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field);
-string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field);
-bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field);
+string PROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field);
+string PROTOC_EXPORT DefaultValue(const FieldDescriptor* field);
+bool PROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field);
-string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector<string>& strings);
+string PROTOC_EXPORT BuildFlagsString(const FlagType type,
+ const std::vector<string>& strings);
// Builds HeaderDoc/appledoc style comments out of the comments in the .proto
// file.
-string LIBPROTOC_EXPORT BuildCommentsString(const SourceLocation& location,
- bool prefer_single_line);
+string PROTOC_EXPORT BuildCommentsString(const SourceLocation& location,
+ bool prefer_single_line);
// The name the commonly used by the library when built as a framework.
// This lines up to the name used in the CocoaPod.
-extern LIBPROTOC_EXPORT const char* const ProtobufLibraryFrameworkName;
+extern PROTOC_EXPORT const char* const ProtobufLibraryFrameworkName;
// Returns the CPP symbol name to use as the gate for framework style imports
// for the given framework name to use.
-string LIBPROTOC_EXPORT ProtobufFrameworkImportSymbol(const string& framework_name);
+string PROTOC_EXPORT
+ProtobufFrameworkImportSymbol(const string& framework_name);
// Checks if the file is one of the proto's bundled with the library.
-bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* file);
+bool PROTOC_EXPORT
+IsProtobufLibraryBundledProtoFile(const FileDescriptor* file);
// Checks the prefix for the given files and outputs any warnings as needed. If
// there are flat out errors, then out_error is filled in with the first error
// and the result is false.
-bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files,
- const Options& generation_options,
- string* out_error);
+bool PROTOC_EXPORT
+ValidateObjCClassPrefixes(const std::vector<const FileDescriptor*>& files,
+ const Options& generation_options, string* out_error);
// Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform
// the input into the expected output.
-class LIBPROTOC_EXPORT TextFormatDecodeData {
+class PROTOC_EXPORT TextFormatDecodeData {
public:
TextFormatDecodeData();
~TextFormatDecodeData();
@@ -237,20 +245,20 @@ class LIBPROTOC_EXPORT TextFormatDecodeData {
};
// Helper for parsing simple files.
-class LIBPROTOC_EXPORT LineConsumer {
+class PROTOC_EXPORT LineConsumer {
public:
LineConsumer();
virtual ~LineConsumer();
virtual bool ConsumeLine(const StringPiece& line, string* out_error) = 0;
};
-bool LIBPROTOC_EXPORT ParseSimpleFile(
- const string& path, LineConsumer* line_consumer, string* out_error);
-
+bool PROTOC_EXPORT ParseSimpleFile(const string& path,
+ LineConsumer* line_consumer,
+ string* out_error);
// Helper class for parsing framework import mappings and generating
// import statements.
-class LIBPROTOC_EXPORT ImportWriter {
+class PROTOC_EXPORT ImportWriter {
public:
ImportWriter(const string& generate_for_named_framework,
const string& named_framework_to_proto_path_mappings_path,
@@ -290,4 +298,7 @@ class LIBPROTOC_EXPORT ImportWriter {
} // namespace compiler
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
diff --git a/src/google/protobuf/compiler/package_info.h b/src/google/protobuf/compiler/package_info.h
index fb6b473e..105ef601 100644
--- a/src/google/protobuf/compiler/package_info.h
+++ b/src/google/protobuf/compiler/package_info.h
@@ -37,7 +37,6 @@
// documentation generator.
namespace google {
-
namespace protobuf {
// Implementation of the Protocol Buffer compiler.
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc
index 5c7047a6..0cec2939 100644
--- a/src/google/protobuf/compiler/parser.cc
+++ b/src/google/protobuf/compiler/parser.cc
@@ -35,9 +35,10 @@
// Recursive descent FTW.
#include <float.h>
-#include <google/protobuf/stubs/hash.h>
#include <limits>
+#include <unordered_map>
+#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
@@ -58,7 +59,7 @@ using internal::WireFormat;
namespace {
-typedef hash_map<string, FieldDescriptorProto::Type> TypeNameMap;
+typedef std::unordered_map<string, FieldDescriptorProto::Type> TypeNameMap;
TypeNameMap MakeTypeNameTable() {
TypeNameMap result;
@@ -336,9 +337,9 @@ void Parser::AddError(const string& error) {
// -------------------------------------------------------------------
Parser::LocationRecorder::LocationRecorder(Parser* parser)
- : parser_(parser),
- source_code_info_(parser->source_code_info_),
- location_(parser_->source_code_info_->add_location()) {
+ : parser_(parser),
+ source_code_info_(parser->source_code_info_),
+ location_(parser_->source_code_info_->add_location()) {
location_->add_span(parser_->input_->current().line);
location_->add_span(parser_->input_->current().column);
}
@@ -1511,7 +1512,6 @@ bool Parser::ParseExtensions(DescriptorProto* message,
range->set_end(end);
} while (TryConsume(","));
-
if (LookingAt("[")) {
int range_number_index = extensions_location.CurrentPathSize();
SourceCodeInfo info;
@@ -1525,8 +1525,7 @@ bool Parser::ParseExtensions(DescriptorProto* message,
extensions_location, 0 /* we fill this in w/ actual index below */,
&info);
LocationRecorder location(
- index_location,
- DescriptorProto::ExtensionRange::kOptionsFieldNumber);
+ index_location, DescriptorProto::ExtensionRange::kOptionsFieldNumber);
DO(Consume("["));
do {
@@ -1546,12 +1545,12 @@ bool Parser::ParseExtensions(DescriptorProto* message,
for (int i = old_range_size; i < message->extension_range_size(); i++) {
for (int j = 0; j < info.location_size(); j++) {
if (info.location(j).path_size() == range_number_index + 1) {
- // this location's path is up to the extension range index, but doesn't
- // include options; so it's redundant with location above
+ // this location's path is up to the extension range index, but
+ // doesn't include options; so it's redundant with location above
continue;
}
SourceCodeInfo_Location* dest = source_code_info_->add_location();
- dest->CopyFrom(info.location(j));
+ *dest = info.location(j);
dest->set_path(range_number_index, i);
}
}
@@ -2277,5 +2276,4 @@ 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 5d98e5e1..9ae6c6da 100644
--- a/src/google/protobuf/compiler/parser.h
+++ b/src/google/protobuf/compiler/parser.h
@@ -45,10 +45,13 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/repeated_field.h>
-namespace google {
-namespace protobuf { class Message; }
+#include <google/protobuf/port_def.inc>
+namespace google {
namespace protobuf {
+
+class Message;
+
namespace compiler {
// Defined in this file.
@@ -62,7 +65,7 @@ class SourceLocationTable;
// to a FileDescriptorProto. It does not resolve import directives or perform
// many other kinds of validation needed to construct a complete
// FileDescriptor.
-class LIBPROTOBUF_EXPORT Parser {
+class PROTOBUF_EXPORT Parser {
public:
Parser();
~Parser();
@@ -92,7 +95,7 @@ class LIBPROTOBUF_EXPORT Parser {
// Returns the identifier used in the "syntax = " declaration, if one was
// seen during the last call to Parse(), or the empty string otherwise.
- const string& GetSyntaxIdentifier() { return syntax_identifier_; }
+ const std::string& GetSyntaxIdentifier() { return syntax_identifier_; }
// If set true, input files will be required to begin with a syntax
// identifier. Otherwise, files may omit this. If a syntax identifier
@@ -162,7 +165,7 @@ class LIBPROTOBUF_EXPORT Parser {
// where "text" is the expected token text.
bool Consume(const char* text);
// Consume a token of type IDENTIFIER and store its text in "output".
- bool ConsumeIdentifier(string* output, const char* error);
+ bool ConsumeIdentifier(std::string* output, const char* error);
// Consume an integer and store its value in "output".
bool ConsumeInteger(int* output, const char* error);
// Consume a signed integer and store its value in "output".
@@ -174,7 +177,7 @@ class LIBPROTOBUF_EXPORT Parser {
// tokens of either INTEGER or FLOAT type.
bool ConsumeNumber(double* output, const char* error);
// Consume a string literal and store its (unescaped) value in "output".
- bool ConsumeString(string* output, const char* error);
+ bool ConsumeString(std::string* output, const char* error);
// Consume a token representing the end of the statement. Comments between
// this token and the next will be harvested for documentation. The given
@@ -197,18 +200,18 @@ class LIBPROTOBUF_EXPORT Parser {
// Error logging helpers
// Invokes error_collector_->AddError(), if error_collector_ is not NULL.
- void AddError(int line, int column, const string& error);
+ void AddError(int line, int column, const std::string& error);
// Invokes error_collector_->AddError() with the line and column number
// of the current token.
- void AddError(const string& error);
+ void AddError(const std::string& error);
// Records a location in the SourceCodeInfo.location table (see
// descriptor.proto). We use RAII to ensure that the start and end locations
// are recorded -- the constructor records the start location and the
// destructor records the end location. Since the parser is
// recursive-descent, this works out beautifully.
- class LIBPROTOBUF_EXPORT LocationRecorder {
+ class PROTOBUF_EXPORT LocationRecorder {
public:
// Construct the file's "root" location.
LocationRecorder(Parser* parser);
@@ -226,7 +229,7 @@ class LIBPROTOBUF_EXPORT Parser {
// Creates a recorder that generates locations into given source code info.
LocationRecorder(const LocationRecorder& parent, int path1,
- SourceCodeInfo* source_code_info);
+ SourceCodeInfo* source_code_info);
~LocationRecorder();
@@ -263,8 +266,8 @@ class LIBPROTOBUF_EXPORT Parser {
//
// TODO(kenton): See comment on TryConsumeEndOfDeclaration(), above, for
// why this is const.
- void AttachComments(string* leading, string* trailing,
- std::vector<string>* detached_comments) const;
+ void AttachComments(std::string* leading, std::string* trailing,
+ std::vector<std::string>* detached_comments) const;
private:
// Indexes of parent and current location in the parent
@@ -312,7 +315,7 @@ class LIBPROTOBUF_EXPORT Parser {
bool ParsePackage(FileDescriptorProto* file,
const LocationRecorder& root_location,
const FileDescriptorProto* containing_file);
- bool ParseImport(RepeatedPtrField<string>* dependency,
+ bool ParseImport(RepeatedPtrField<std::string>* dependency,
RepeatedField<int32>* public_dependency,
RepeatedField<int32>* weak_dependency,
const LocationRecorder& root_location,
@@ -436,10 +439,10 @@ class LIBPROTOBUF_EXPORT Parser {
// Parse a type name and fill in "type" (if it is a primitive) or
// "type_name" (if it is not) with the type parsed.
bool ParseType(FieldDescriptorProto::Type* type,
- string* type_name);
+ std::string* type_name);
// Parse a user-defined type and fill in "type_name" with the name.
// If a primitive type is named, it is treated as an error.
- bool ParseUserDefinedType(string* type_name);
+ bool ParseUserDefinedType(std::string* type_name);
// Parses field options, i.e. the stuff in square brackets at the end
// of a field definition. Also parses default value.
@@ -488,7 +491,7 @@ class LIBPROTOBUF_EXPORT Parser {
// REQUIRES: LookingAt("{")
// When finished successfully, we are looking at the first token past
// the ending brace.
- bool ParseUninterpretedBlock(string* value);
+ bool ParseUninterpretedBlock(std::string* value);
struct MapField {
// Whether the field is a map field.
@@ -497,8 +500,8 @@ class LIBPROTOBUF_EXPORT Parser {
FieldDescriptorProto::Type key_type;
FieldDescriptorProto::Type value_type;
// Or the type names string if the types are customized types.
- string key_type_name;
- string value_type_name;
+ std::string key_type_name;
+ std::string value_type_name;
MapField() : is_map_field(false) {}
};
@@ -523,18 +526,18 @@ class LIBPROTOBUF_EXPORT Parser {
bool had_errors_;
bool require_syntax_identifier_;
bool stop_after_syntax_identifier_;
- string syntax_identifier_;
+ std::string syntax_identifier_;
// Leading doc comments for the next declaration. These are not complete
// yet; use ConsumeEndOfDeclaration() to get the complete comments.
- string upcoming_doc_comments_;
+ std::string upcoming_doc_comments_;
// Detached comments are not connected to any syntax entities. Elements in
// this vector are paragraphs of comments separated by empty lines. The
// detached comments will be put into the leading_detached_comments field for
// the next element (See SourceCodeInfo.Location in descriptor.proto), when
// ConsumeEndOfDeclaration() is called.
- std::vector<string> upcoming_detached_comments_;
+ std::vector<std::string> upcoming_detached_comments_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Parser);
};
@@ -547,7 +550,7 @@ class LIBPROTOBUF_EXPORT Parser {
// far more complete information about source locations. However, as of this
// writing you still need to use SourceLocationTable when integrating with
// DescriptorPool.
-class LIBPROTOBUF_EXPORT SourceLocationTable {
+class PROTOBUF_EXPORT SourceLocationTable {
public:
SourceLocationTable();
~SourceLocationTable();
@@ -578,6 +581,8 @@ class LIBPROTOBUF_EXPORT SourceLocationTable {
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_PARSER_H__
diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc
index 0725a682..008d97d5 100644
--- a/src/google/protobuf/compiler/parser_unittest.cc
+++ b/src/google/protobuf/compiler/parser_unittest.cc
@@ -39,6 +39,7 @@
#include <google/protobuf/compiler/parser.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_custom_options.pb.h>
#include <google/protobuf/io/tokenizer.h>
@@ -1746,7 +1747,8 @@ TEST_F(ParserValidationErrorTest, FieldDefaultValueError) {
TEST_F(ParserValidationErrorTest, FileOptionNameError) {
ExpectHasValidationErrors(
"option foo = 5;",
- "0:7: Option \"foo\" unknown.\n");
+ "0:7: Option \"foo\" unknown. Ensure that your proto definition file "
+ "imports the proto which defines the option.\n");
}
TEST_F(ParserValidationErrorTest, FileOptionValueError) {
@@ -1761,7 +1763,8 @@ TEST_F(ParserValidationErrorTest, FieldOptionNameError) {
"message Foo {\n"
" optional bool bar = 1 [foo=1];\n"
"}\n",
- "1:25: Option \"foo\" unknown.\n");
+ "1:25: Option \"foo\" unknown. Ensure that your proto definition file "
+ "imports the proto which defines the option.\n");
}
TEST_F(ParserValidationErrorTest, FieldOptionValueError) {
@@ -1866,7 +1869,7 @@ TEST_F(ParserValidationErrorTest, ResovledUndefinedOptionError) {
// base2.proto:
// package baz
- // import google/protobuf/descriptor.proto
+ // import net/proto2/proto/descriptor.proto
// message Bar { optional int32 foo = 1; }
// extend FileOptions { optional Bar bar = 7672757; }
FileDescriptorProto other_file;
@@ -1992,7 +1995,8 @@ TEST_F(ParseDescriptorDebugTest, TestAllDescriptorTypes) {
// We now have a FileDescriptorProto, but to compare with the expected we
// need to link to a FileDecriptor, then output back to a proto. We'll
// also need to give it the same name as the original.
- parsed.set_name("google/protobuf/unittest.proto");
+ parsed.set_name(
+ TestUtil::MaybeTranslatePath("net/proto2/internal/unittest.proto"));
// We need the imported dependency before we can build our parsed proto
const FileDescriptor* public_import =
protobuf_unittest_import::PublicImportMessage::descriptor()->file();
diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h
index b851d9b4..283767ec 100644
--- a/src/google/protobuf/compiler/php/php_generator.h
+++ b/src/google/protobuf/compiler/php/php_generator.h
@@ -36,12 +36,14 @@
#include <string>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
namespace php {
-class LIBPROTOC_EXPORT Generator
+class PROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
virtual bool Generate(
const FileDescriptor* file,
@@ -53,11 +55,11 @@ class LIBPROTOC_EXPORT Generator
// To skip reserved keywords in php, some generated classname are prefixed.
// Other code generators may need following API to figure out the actual
// classname.
-LIBPROTOC_EXPORT std::string GeneratedClassName(
+PROTOC_EXPORT std::string GeneratedClassName(
const google::protobuf::Descriptor* desc);
-LIBPROTOC_EXPORT std::string GeneratedClassName(
+PROTOC_EXPORT std::string GeneratedClassName(
const google::protobuf::EnumDescriptor* desc);
-LIBPROTOC_EXPORT std::string GeneratedClassName(
+PROTOC_EXPORT std::string GeneratedClassName(
const google::protobuf::ServiceDescriptor* desc);
} // namespace php
@@ -65,4 +67,6 @@ LIBPROTOC_EXPORT std::string GeneratedClassName(
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/plugin.h b/src/google/protobuf/compiler/plugin.h
index d2793a9f..48db3c1c 100644
--- a/src/google/protobuf/compiler/plugin.h
+++ b/src/google/protobuf/compiler/plugin.h
@@ -64,7 +64,8 @@
#include <string>
-#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -74,17 +75,20 @@ class CodeGeneratorRequest;
class CodeGeneratorResponse;
// Implements main() for a protoc plugin exposing the given code generator.
-LIBPROTOC_EXPORT int PluginMain(int argc, char* argv[], const CodeGenerator* generator);
+PROTOC_EXPORT int PluginMain(int argc, char* argv[],
+ const CodeGenerator* generator);
// Generates code using the given code generator. Returns true if the code
// generation is successful. If the code geneartion fails, error_msg may be
// populated to describe the failure cause.
bool GenerateCode(const CodeGeneratorRequest& request,
const CodeGenerator& generator, CodeGeneratorResponse* response,
- string* error_msg);
+ std::string* error_msg);
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_PLUGIN_H__
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc
index ef52def3..234be0dd 100644
--- a/src/google/protobuf/compiler/plugin.pb.cc
+++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -6,54 +6,42 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
-namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version;
-} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
-namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto;
-} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
namespace google {
namespace protobuf {
namespace compiler {
class VersionDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Version>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Version> _instance;
} _Version_default_instance_;
class CodeGeneratorRequestDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest> _instance;
} _CodeGeneratorRequest_default_instance_;
class CodeGeneratorResponse_FileDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File> _instance;
} _CodeGeneratorResponse_File_default_instance_;
class CodeGeneratorResponseDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse> _instance;
} _CodeGeneratorResponse_default_instance_;
} // namespace compiler
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
-static void InitDefaultsVersion() {
+static void InitDefaultsVersion_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -64,10 +52,10 @@ static void InitDefaultsVersion() {
::google::protobuf::compiler::Version::InitAsDefaultInstance();
}
-LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}};
+PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}};
-static void InitDefaultsCodeGeneratorRequest() {
+static void InitDefaultsCodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -78,12 +66,12 @@ static void InitDefaultsCodeGeneratorRequest() {
::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance();
}
-LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base,}};
+PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {
+ &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}};
-static void InitDefaultsCodeGeneratorResponse_File() {
+static void InitDefaultsCodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -94,10 +82,10 @@ static void InitDefaultsCodeGeneratorResponse_File() {
::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance();
}
-LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}};
+PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {}};
-static void InitDefaultsCodeGeneratorResponse() {
+static void InitDefaultsCodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -108,68 +96,70 @@ static void InitDefaultsCodeGeneratorResponse() {
::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance();
}
-LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse}, {
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base,}};
+PROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto}, {
+ &scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base,}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Version.base);
- ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest.base);
- ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File.base);
- ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse.base);
+void InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[4];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[4];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr;
-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_),
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, major_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_),
0,
~0u,
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_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)},
@@ -183,62 +173,44 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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);
-}
-
-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"
- "\001 \001(\005\022\r\n\005minor\030\002 \001(\005\022\r\n\005patch\030\003 \001(\005\022\016\n\006s"
- "uffix\030\004 \001(\t\"\272\001\n\024CodeGeneratorRequest\022\030\n\020"
- "file_to_generate\030\001 \003(\t\022\021\n\tparameter\030\002 \001("
- "\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf."
- "FileDescriptorProto\022;\n\020compiler_version\030"
- "\003 \001(\0132!.google.protobuf.compiler.Version"
- "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001("
- "\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(\tBg\n\034com.google.protobuf.com"
- "pilerB\014PluginProtosZ9github.com/golang/p"
- "rotobuf/protoc-gen-go/plugin;plugin_go"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto, "google/protobuf/compiler/plugin.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto, file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto,
+ "\n%google/protobuf/compiler/plugin.proto\022"
+ "\030google.protobuf.compiler\032 google/protob"
+ "uf/descriptor.proto\"F\n\007Version\022\r\n\005major\030"
+ "\001 \001(\005\022\r\n\005minor\030\002 \001(\005\022\r\n\005patch\030\003 \001(\005\022\016\n\006s"
+ "uffix\030\004 \001(\t\"\272\001\n\024CodeGeneratorRequest\022\030\n\020"
+ "file_to_generate\030\001 \003(\t\022\021\n\tparameter\030\002 \001("
+ "\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf."
+ "FileDescriptorProto\022;\n\020compiler_version\030"
+ "\003 \001(\0132!.google.protobuf.compiler.Version"
+ "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001("
+ "\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(\tBg\n\034com.google.protobuf.com"
+ "pilerB\014PluginProtosZ9github.com/golang/p"
+ "rotobuf/protoc-gen-go/plugin;plugin_go"
+,
+ "google/protobuf/compiler/plugin.proto", &assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto, 638,
+};
+
+void AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
+ ::AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto,
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 638);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/compiler/plugin.proto", &protobuf_RegisterTypes);
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::AddDescriptors();
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto, deps, 1);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fcompiler_2fplugin_2eproto = []() { AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto(); return true; }();
namespace google {
namespace protobuf {
namespace compiler {
@@ -247,6 +219,22 @@ namespace compiler {
void Version::InitAsDefaultInstance() {
}
+class Version::HasBitSetters {
+ public:
+ static void set_has_major(Version* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_minor(Version* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static void set_has_patch(Version* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_suffix(Version* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Version::kMajorFieldNumber;
const int Version::kMinorFieldNumber;
@@ -256,8 +244,6 @@ const int Version::kSuffixFieldNumber;
Version::Version()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.Version)
}
@@ -277,6 +263,8 @@ Version::Version(const Version& from)
}
void Version::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&major_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&patch_) -
@@ -295,13 +283,8 @@ void Version::SharedDtor() {
void Version::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Version::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Version_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
return *internal_default_instance();
}
@@ -316,7 +299,7 @@ void Version::Clear() {
if (cached_has_bits & 0x00000001u) {
suffix_.ClearNonDefaultToEmptyNoArena();
}
- if (cached_has_bits & 14u) {
+ if (cached_has_bits & 0x0000000eu) {
::memset(&major_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&patch_) -
reinterpret_cast<char*>(&major_)) + sizeof(patch_));
@@ -325,9 +308,92 @@ void Version::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Version::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Version*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional int32 major = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_major(value);
+ break;
+ }
+ // optional int32 minor = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_minor(value);
+ break;
+ }
+ // optional int32 patch = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_patch(value);
+ break;
+ }
+ // optional string suffix = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.Version.suffix");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_suffix();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Version::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version)
for (;;) {
@@ -337,9 +403,8 @@ bool Version::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 major = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- set_has_major();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_major(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &major_)));
@@ -351,9 +416,8 @@ bool Version::MergePartialFromCodedStream(
// optional int32 minor = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_minor();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_minor(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &minor_)));
@@ -365,9 +429,8 @@ bool Version::MergePartialFromCodedStream(
// optional int32 patch = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_patch();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_patch(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &patch_)));
@@ -379,8 +442,7 @@ bool Version::MergePartialFromCodedStream(
// optional string suffix = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_suffix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -412,6 +474,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Version::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -503,30 +566,35 @@ size_t Version::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 15u) {
+ ::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 & 0x0000000fu) {
// optional string suffix = 4;
- if (has_suffix()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->suffix());
}
// optional int32 major = 1;
- if (has_major()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->major());
}
// optional int32 minor = 2;
- if (has_minor()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->minor());
}
// optional int32 patch = 3;
- if (has_patch()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->patch());
@@ -542,7 +610,7 @@ void Version::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.Version)
GOOGLE_DCHECK_NE(&from, this);
const Version* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Version>(
+ ::google::protobuf::DynamicCastToGenerated<Version>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.Version)
@@ -561,9 +629,9 @@ void Version::MergeFrom(const Version& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x0000000fu) {
if (cached_has_bits & 0x00000001u) {
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_);
}
if (cached_has_bits & 0x00000002u) {
@@ -603,18 +671,18 @@ void Version::Swap(Version* other) {
}
void Version::InternalSwap(Version* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
suffix_.Swap(&other->suffix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
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_);
}
::google::protobuf::Metadata Version::GetMetadata() const {
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[kIndexInFileMessages];
}
@@ -624,6 +692,21 @@ 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());
}
+class CodeGeneratorRequest::HasBitSetters {
+ public:
+ static void set_has_parameter(CodeGeneratorRequest* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static const ::google::protobuf::compiler::Version& compiler_version(const CodeGeneratorRequest* msg);
+ static void set_has_compiler_version(CodeGeneratorRequest* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::compiler::Version&
+CodeGeneratorRequest::HasBitSetters::compiler_version(const CodeGeneratorRequest* msg) {
+ return *msg->compiler_version_;
+}
void CodeGeneratorRequest::clear_proto_file() {
proto_file_.Clear();
}
@@ -636,8 +719,6 @@ const int CodeGeneratorRequest::kCompilerVersionFieldNumber;
CodeGeneratorRequest::CodeGeneratorRequest()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest)
}
@@ -661,6 +742,8 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
}
void CodeGeneratorRequest::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
compiler_version_ = NULL;
}
@@ -678,13 +761,8 @@ void CodeGeneratorRequest::SharedDtor() {
void CodeGeneratorRequest::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* CodeGeneratorRequest::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_CodeGeneratorRequest_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
return *internal_default_instance();
}
@@ -698,7 +776,7 @@ void CodeGeneratorRequest::Clear() {
file_to_generate_.Clear();
proto_file_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
parameter_.ClearNonDefaultToEmptyNoArena();
}
@@ -711,9 +789,114 @@ void CodeGeneratorRequest::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* CodeGeneratorRequest::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<CodeGeneratorRequest*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated string file_to_generate = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorRequest.file_to_generate");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->add_file_to_generate();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ // optional string parameter = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorRequest.parameter");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_parameter();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional .google.protobuf.compiler.Version compiler_version = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::compiler::Version::_InternalParse;
+ object = msg->mutable_compiler_version();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // repeated .google.protobuf.FileDescriptorProto proto_file = 15;
+ case 15: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FileDescriptorProto::_InternalParse;
+ object = msg->add_proto_file();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 122 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CodeGeneratorRequest::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest)
for (;;) {
@@ -723,8 +906,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string file_to_generate = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_file_to_generate()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -740,8 +922,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// optional string parameter = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_parameter()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -756,8 +937,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// optional .google.protobuf.compiler.Version compiler_version = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_compiler_version()));
} else {
@@ -768,8 +948,7 @@ bool CodeGeneratorRequest::MergePartialFromCodedStream(
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
case 15: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (122 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_proto_file()));
} else {
@@ -797,6 +976,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CodeGeneratorRequest::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -828,7 +1008,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
// optional .google.protobuf.compiler.Version compiler_version = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->_internal_compiler_version(), output);
+ 3, HasBitSetters::compiler_version(this), output);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
@@ -880,7 +1060,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, this->_internal_compiler_version(), deterministic, target);
+ 3, HasBitSetters::compiler_version(this), deterministic, target);
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
@@ -908,6 +1088,10 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated string file_to_generate = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->file_to_generate_size());
@@ -927,16 +1111,17 @@ size_t CodeGeneratorRequest::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional string parameter = 2;
- if (has_parameter()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->parameter());
}
// optional .google.protobuf.compiler.Version compiler_version = 3;
- if (has_compiler_version()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*compiler_version_);
@@ -952,7 +1137,7 @@ void CodeGeneratorRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest)
GOOGLE_DCHECK_NE(&from, this);
const CodeGeneratorRequest* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorRequest>(
+ ::google::protobuf::DynamicCastToGenerated<CodeGeneratorRequest>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorRequest)
@@ -973,9 +1158,9 @@ void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) {
file_to_generate_.MergeFrom(from.file_to_generate_);
proto_file_.MergeFrom(from.proto_file_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_);
}
if (cached_has_bits & 0x00000002u) {
@@ -1009,18 +1194,18 @@ void CodeGeneratorRequest::Swap(CodeGeneratorRequest* other) {
}
void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_));
CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_));
parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(compiler_version_, other->compiler_version_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const {
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[kIndexInFileMessages];
}
@@ -1028,6 +1213,19 @@ void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) {
void CodeGeneratorResponse_File::InitAsDefaultInstance() {
}
+class CodeGeneratorResponse_File::HasBitSetters {
+ public:
+ static void set_has_name(CodeGeneratorResponse_File* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_insertion_point(CodeGeneratorResponse_File* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_content(CodeGeneratorResponse_File* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CodeGeneratorResponse_File::kNameFieldNumber;
const int CodeGeneratorResponse_File::kInsertionPointFieldNumber;
@@ -1036,8 +1234,6 @@ const int CodeGeneratorResponse_File::kContentFieldNumber;
CodeGeneratorResponse_File::CodeGeneratorResponse_File()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
}
@@ -1062,6 +1258,8 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon
}
void CodeGeneratorResponse_File::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1081,13 +1279,8 @@ void CodeGeneratorResponse_File::SharedDtor() {
void CodeGeneratorResponse_File::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_CodeGeneratorResponse_File_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
return *internal_default_instance();
}
@@ -1099,7 +1292,7 @@ void CodeGeneratorResponse_File::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmptyNoArena();
}
@@ -1114,9 +1307,94 @@ void CodeGeneratorResponse_File::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* CodeGeneratorResponse_File::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<CodeGeneratorResponse_File*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string insertion_point = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_insertion_point();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string content = 15;
+ case 15: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.File.content");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_content();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File)
for (;;) {
@@ -1126,8 +1404,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1142,8 +1419,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
// optional string insertion_point = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_insertion_point()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1158,8 +1434,7 @@ bool CodeGeneratorResponse_File::MergePartialFromCodedStream(
// optional string content = 15;
case 15: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (122 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_content()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1191,6 +1466,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CodeGeneratorResponse_File::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1294,23 +1570,28 @@ size_t CodeGeneratorResponse_File::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 7u) {
+ ::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 & 0x00000007u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional string insertion_point = 2;
- if (has_insertion_point()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->insertion_point());
}
// optional string content = 15;
- if (has_content()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->content());
@@ -1326,7 +1607,7 @@ void CodeGeneratorResponse_File::MergeFrom(const ::google::protobuf::Message& fr
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
GOOGLE_DCHECK_NE(&from, this);
const CodeGeneratorResponse_File* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorResponse_File>(
+ ::google::protobuf::DynamicCastToGenerated<CodeGeneratorResponse_File>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse.File)
@@ -1345,17 +1626,17 @@ void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& fro
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (cached_has_bits & 0x00000002u) {
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_);
}
if (cached_has_bits & 0x00000004u) {
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_);
}
}
@@ -1385,19 +1666,19 @@ void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) {
}
void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
insertion_point_.Swap(&other->insertion_point_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const {
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[kIndexInFileMessages];
}
@@ -1405,6 +1686,13 @@ void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other)
void CodeGeneratorResponse::InitAsDefaultInstance() {
}
+class CodeGeneratorResponse::HasBitSetters {
+ public:
+ static void set_has_error(CodeGeneratorResponse* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CodeGeneratorResponse::kErrorFieldNumber;
const int CodeGeneratorResponse::kFileFieldNumber;
@@ -1412,8 +1700,6 @@ const int CodeGeneratorResponse::kFileFieldNumber;
CodeGeneratorResponse::CodeGeneratorResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
@@ -1431,6 +1717,8 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
}
void CodeGeneratorResponse::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1446,13 +1734,8 @@ void CodeGeneratorResponse::SharedDtor() {
void CodeGeneratorResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* CodeGeneratorResponse::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_CodeGeneratorResponse_google_2fprotobuf_2fcompiler_2fplugin_2eproto.base);
return *internal_default_instance();
}
@@ -1472,9 +1755,80 @@ void CodeGeneratorResponse::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* CodeGeneratorResponse::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<CodeGeneratorResponse*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string error = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.compiler.CodeGeneratorResponse.error");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_error();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
+ case 15: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 122) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::compiler::CodeGeneratorResponse_File::_InternalParse;
+ object = msg->add_file();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 122 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool CodeGeneratorResponse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse)
for (;;) {
@@ -1484,8 +1838,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string error = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_error()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1500,8 +1853,7 @@ bool CodeGeneratorResponse::MergePartialFromCodedStream(
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
case 15: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (122 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_file()));
} else {
@@ -1529,6 +1881,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void CodeGeneratorResponse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1607,6 +1960,10 @@ size_t CodeGeneratorResponse::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
{
unsigned int count = static_cast<unsigned int>(this->file_size());
@@ -1619,7 +1976,8 @@ size_t CodeGeneratorResponse::ByteSizeLong() const {
}
// optional string error = 1;
- if (has_error()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->error());
@@ -1634,7 +1992,7 @@ void CodeGeneratorResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse)
GOOGLE_DCHECK_NE(&from, this);
const CodeGeneratorResponse* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorResponse>(
+ ::google::protobuf::DynamicCastToGenerated<CodeGeneratorResponse>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse)
@@ -1654,7 +2012,7 @@ void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) {
file_.MergeFrom(from.file_);
if (from.has_error()) {
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
error_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_);
}
}
@@ -1683,16 +2041,16 @@ void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) {
}
void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const {
- protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fcompiler_2fplugin_2eproto[kIndexInFileMessages];
}
@@ -1702,19 +2060,20 @@ void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index 78d3bba3..187587ca 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -32,7 +33,8 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto PROTOC_EXPORT
#ifdef major
#undef major
#endif
@@ -40,42 +42,39 @@
#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];
+struct PROTOC_EXPORT TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[4]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto
+void PROTOC_EXPORT AddDescriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
namespace google {
namespace protobuf {
namespace compiler {
class CodeGeneratorRequest;
class CodeGeneratorRequestDefaultTypeInternal;
-LIBPROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_;
+PROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_;
class CodeGeneratorResponse;
class CodeGeneratorResponseDefaultTypeInternal;
-LIBPROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_;
+PROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_;
class CodeGeneratorResponse_File;
class CodeGeneratorResponse_FileDefaultTypeInternal;
-LIBPROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_;
+PROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_;
class Version;
class VersionDefaultTypeInternal;
-LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_;
+PROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_;
} // namespace compiler
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*);
-template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*);
+template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*);
+template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*);
+template<> PROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*);
+template<> PROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -84,7 +83,7 @@ namespace compiler {
// ===================================================================
-class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ {
+class PROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ {
public:
Version();
virtual ~Version();
@@ -117,7 +116,9 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
return _internal_metadata_.mutable_unknown_fields();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Version& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -150,8 +151,13 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -216,14 +222,7 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.Version)
private:
- void set_has_major();
- void clear_has_major();
- void set_has_minor();
- void clear_has_minor();
- void set_has_patch();
- void clear_has_patch();
- void set_has_suffix();
- void clear_has_suffix();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
@@ -232,11 +231,11 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 major_;
::google::protobuf::int32 minor_;
::google::protobuf::int32 patch_;
- friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ {
+class PROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ {
public:
CodeGeneratorRequest();
virtual ~CodeGeneratorRequest();
@@ -269,7 +268,9 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
return _internal_metadata_.mutable_unknown_fields();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const CodeGeneratorRequest& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -302,8 +303,13 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -349,8 +355,8 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
#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();
+ const ::google::protobuf::RepeatedPtrField<::std::string>& file_to_generate() const;
+ ::google::protobuf::RepeatedPtrField<::std::string>* mutable_file_to_generate();
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
int proto_file_size() const;
@@ -383,9 +389,6 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
bool has_compiler_version() const;
void clear_compiler_version();
static const int kCompilerVersionFieldNumber = 3;
- private:
- const ::google::protobuf::compiler::Version& _internal_compiler_version() const;
- public:
const ::google::protobuf::compiler::Version& compiler_version() const;
::google::protobuf::compiler::Version* release_compiler_version();
::google::protobuf::compiler::Version* mutable_compiler_version();
@@ -393,23 +396,20 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest)
private:
- void set_has_parameter();
- void clear_has_parameter();
- void set_has_compiler_version();
- void clear_has_compiler_version();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- ::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_;
+ ::google::protobuf::RepeatedPtrField<::std::string> file_to_generate_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_;
::google::protobuf::internal::ArenaStringPtr parameter_;
::google::protobuf::compiler::Version* compiler_version_;
- friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ {
+class PROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ {
public:
CodeGeneratorResponse_File();
virtual ~CodeGeneratorResponse_File();
@@ -442,7 +442,9 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
return _internal_metadata_.mutable_unknown_fields();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const CodeGeneratorResponse_File& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -475,8 +477,13 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -550,12 +557,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse.File)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_insertion_point();
- void clear_has_insertion_point();
- void set_has_content();
- void clear_has_content();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
@@ -563,11 +565,11 @@ 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 struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ {
+class PROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ {
public:
CodeGeneratorResponse();
virtual ~CodeGeneratorResponse();
@@ -600,7 +602,9 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
return _internal_metadata_.mutable_unknown_fields();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const CodeGeneratorResponse& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -633,8 +637,13 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -692,15 +701,14 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
// @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse)
private:
- void set_has_error();
- void clear_has_error();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_;
::google::protobuf::internal::ArenaStringPtr error_;
- friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto;
};
// ===================================================================
@@ -717,22 +725,16 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
inline bool Version::has_major() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void Version::set_has_major() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void Version::clear_has_major() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void Version::clear_major() {
major_ = 0;
- clear_has_major();
+ _has_bits_[0] &= ~0x00000002u;
}
inline ::google::protobuf::int32 Version::major() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major)
return major_;
}
inline void Version::set_major(::google::protobuf::int32 value) {
- set_has_major();
+ _has_bits_[0] |= 0x00000002u;
major_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.major)
}
@@ -741,22 +743,16 @@ inline void Version::set_major(::google::protobuf::int32 value) {
inline bool Version::has_minor() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void Version::set_has_minor() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void Version::clear_has_minor() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void Version::clear_minor() {
minor_ = 0;
- clear_has_minor();
+ _has_bits_[0] &= ~0x00000004u;
}
inline ::google::protobuf::int32 Version::minor() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor)
return minor_;
}
inline void Version::set_minor(::google::protobuf::int32 value) {
- set_has_minor();
+ _has_bits_[0] |= 0x00000004u;
minor_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.minor)
}
@@ -765,22 +761,16 @@ inline void Version::set_minor(::google::protobuf::int32 value) {
inline bool Version::has_patch() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void Version::set_has_patch() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void Version::clear_has_patch() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void Version::clear_patch() {
patch_ = 0;
- clear_has_patch();
+ _has_bits_[0] &= ~0x00000008u;
}
inline ::google::protobuf::int32 Version::patch() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch)
return patch_;
}
inline void Version::set_patch(::google::protobuf::int32 value) {
- set_has_patch();
+ _has_bits_[0] |= 0x00000008u;
patch_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.patch)
}
@@ -789,28 +779,22 @@ inline void Version::set_patch(::google::protobuf::int32 value) {
inline bool Version::has_suffix() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void Version::set_has_suffix() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void Version::clear_has_suffix() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void Version::clear_suffix() {
suffix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_suffix();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& Version::suffix() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.suffix)
return suffix_.GetNoArena();
}
inline void Version::set_suffix(const ::std::string& value) {
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
suffix_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.Version.suffix)
@@ -818,18 +802,18 @@ inline void Version::set_suffix(::std::string&& value) {
#endif
inline void Version::set_suffix(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix)
}
inline void Version::set_suffix(const char* value, size_t size) {
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
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)
}
inline ::std::string* Version::mutable_suffix() {
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.Version.suffix)
return suffix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -838,14 +822,14 @@ inline ::std::string* Version::release_suffix() {
if (!has_suffix()) {
return NULL;
}
- clear_has_suffix();
+ _has_bits_[0] &= ~0x00000001u;
return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Version::set_allocated_suffix(::std::string* suffix) {
if (suffix != NULL) {
- set_has_suffix();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_suffix();
+ _has_bits_[0] &= ~0x00000001u;
}
suffix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), suffix);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix)
@@ -913,12 +897,12 @@ inline void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t
file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline 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_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::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_;
@@ -928,28 +912,22 @@ CodeGeneratorRequest::mutable_file_to_generate() {
inline bool CodeGeneratorRequest::has_parameter() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void CodeGeneratorRequest::set_has_parameter() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void CodeGeneratorRequest::clear_has_parameter() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void CodeGeneratorRequest::clear_parameter() {
parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_parameter();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& CodeGeneratorRequest::parameter() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter)
return parameter_.GetNoArena();
}
inline void CodeGeneratorRequest::set_parameter(const ::std::string& value) {
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
parameter_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorRequest.parameter)
@@ -957,18 +935,18 @@ inline void CodeGeneratorRequest::set_parameter(::std::string&& value) {
#endif
inline void CodeGeneratorRequest::set_parameter(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
inline void CodeGeneratorRequest::set_parameter(const char* value, size_t size) {
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
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)
}
inline ::std::string* CodeGeneratorRequest::mutable_parameter() {
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.parameter)
return parameter_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -977,14 +955,14 @@ inline ::std::string* CodeGeneratorRequest::release_parameter() {
if (!has_parameter()) {
return NULL;
}
- clear_has_parameter();
+ _has_bits_[0] &= ~0x00000001u;
return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) {
if (parameter != NULL) {
- set_has_parameter();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_parameter();
+ _has_bits_[0] &= ~0x00000001u;
}
parameter_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), parameter);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter)
@@ -1021,18 +999,9 @@ CodeGeneratorRequest::proto_file() const {
inline bool CodeGeneratorRequest::has_compiler_version() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void CodeGeneratorRequest::set_has_compiler_version() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void CodeGeneratorRequest::clear_has_compiler_version() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void CodeGeneratorRequest::clear_compiler_version() {
if (compiler_version_ != NULL) compiler_version_->Clear();
- clear_has_compiler_version();
-}
-inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const {
- return *compiler_version_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const {
const ::google::protobuf::compiler::Version* p = compiler_version_;
@@ -1042,13 +1011,13 @@ inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compil
}
inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
- clear_has_compiler_version();
+ _has_bits_[0] &= ~0x00000002u;
::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();
+ _has_bits_[0] |= 0x00000002u;
if (compiler_version_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual());
compiler_version_ = p;
@@ -1067,9 +1036,9 @@ inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::proto
compiler_version = ::google::protobuf::internal::GetOwnedMessage(
message_arena, compiler_version, submessage_arena);
}
- set_has_compiler_version();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_compiler_version();
+ _has_bits_[0] &= ~0x00000002u;
}
compiler_version_ = compiler_version;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version)
@@ -1083,28 +1052,22 @@ inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::proto
inline bool CodeGeneratorResponse_File::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void CodeGeneratorResponse_File::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void CodeGeneratorResponse_File::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void CodeGeneratorResponse_File::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& CodeGeneratorResponse_File::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name)
return name_.GetNoArena();
}
inline void CodeGeneratorResponse_File::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.name)
@@ -1112,18 +1075,18 @@ inline void CodeGeneratorResponse_File::set_name(::std::string&& value) {
#endif
inline void CodeGeneratorResponse_File::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
inline void CodeGeneratorResponse_File::set_name(const char* value, size_t size) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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)
}
inline ::std::string* CodeGeneratorResponse_File::mutable_name() {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1132,14 +1095,14 @@ inline ::std::string* CodeGeneratorResponse_File::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name)
@@ -1149,28 +1112,22 @@ inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name)
inline bool CodeGeneratorResponse_File::has_insertion_point() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void CodeGeneratorResponse_File::set_has_insertion_point() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void CodeGeneratorResponse_File::clear_has_insertion_point() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void CodeGeneratorResponse_File::clear_insertion_point() {
insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_insertion_point();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& CodeGeneratorResponse_File::insertion_point() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
return insertion_point_.GetNoArena();
}
inline void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) {
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
insertion_point_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
@@ -1178,18 +1135,18 @@ inline void CodeGeneratorResponse_File::set_insertion_point(::std::string&& valu
#endif
inline void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
inline void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) {
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
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)
}
inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() {
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
return insertion_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1198,14 +1155,14 @@ inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() {
if (!has_insertion_point()) {
return NULL;
}
- clear_has_insertion_point();
+ _has_bits_[0] &= ~0x00000002u;
return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) {
if (insertion_point != NULL) {
- set_has_insertion_point();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_insertion_point();
+ _has_bits_[0] &= ~0x00000002u;
}
insertion_point_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), insertion_point);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
@@ -1215,28 +1172,22 @@ inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::str
inline bool CodeGeneratorResponse_File::has_content() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void CodeGeneratorResponse_File::set_has_content() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void CodeGeneratorResponse_File::clear_has_content() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void CodeGeneratorResponse_File::clear_content() {
content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_content();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& CodeGeneratorResponse_File::content() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content)
return content_.GetNoArena();
}
inline void CodeGeneratorResponse_File::set_content(const ::std::string& value) {
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
content_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.content)
@@ -1244,18 +1195,18 @@ inline void CodeGeneratorResponse_File::set_content(::std::string&& value) {
#endif
inline void CodeGeneratorResponse_File::set_content(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
inline void CodeGeneratorResponse_File::set_content(const char* value, size_t size) {
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
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)
}
inline ::std::string* CodeGeneratorResponse_File::mutable_content() {
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.content)
return content_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1264,14 +1215,14 @@ inline ::std::string* CodeGeneratorResponse_File::release_content() {
if (!has_content()) {
return NULL;
}
- clear_has_content();
+ _has_bits_[0] &= ~0x00000004u;
return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) {
if (content != NULL) {
- set_has_content();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_content();
+ _has_bits_[0] &= ~0x00000004u;
}
content_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
@@ -1285,28 +1236,22 @@ inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* con
inline bool CodeGeneratorResponse::has_error() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void CodeGeneratorResponse::set_has_error() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void CodeGeneratorResponse::clear_has_error() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void CodeGeneratorResponse::clear_error() {
error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- clear_has_error();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& CodeGeneratorResponse::error() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error)
return error_.GetNoArena();
}
inline void CodeGeneratorResponse::set_error(const ::std::string& value) {
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
error_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.error)
@@ -1314,18 +1259,18 @@ inline void CodeGeneratorResponse::set_error(::std::string&& value) {
#endif
inline void CodeGeneratorResponse::set_error(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error)
}
inline void CodeGeneratorResponse::set_error(const char* value, size_t size) {
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
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)
}
inline ::std::string* CodeGeneratorResponse::mutable_error() {
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.error)
return error_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -1334,14 +1279,14 @@ inline ::std::string* CodeGeneratorResponse::release_error() {
if (!has_error()) {
return NULL;
}
- clear_has_error();
+ _has_bits_[0] &= ~0x00000001u;
return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) {
if (error != NULL) {
- set_has_error();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_error();
+ _has_bits_[0] &= ~0x00000001u;
}
error_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error)
@@ -1395,4 +1340,5 @@ CodeGeneratorResponse::file() const {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto
diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc
index 01f28b37..6dc61ec1 100644
--- a/src/google/protobuf/compiler/python/python_generator.cc
+++ b/src/google/protobuf/compiler/python/python_generator.cc
@@ -45,7 +45,6 @@
// directly.
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <limits>
#include <map>
#include <memory>
@@ -73,11 +72,6 @@ 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;
}
@@ -103,7 +97,7 @@ string ModuleName(const string& filename) {
// Returns the alias we assign to the module of the given .proto filename
// when importing. See testPackageInitializationImport in
-// google/protobuf/python/reflection_test.py
+// net/proto2/python/internal/reflection_test.py
// to see why we need the alias.
string ModuleAlias(const string& filename) {
string module_name = ModuleName(filename);
@@ -424,7 +418,7 @@ void Generator::PrintFileDescriptor() const {
printer_->Print(m, file_descriptor_template);
printer_->Indent();
printer_->Print(
-//##!PY25 "serialized_pb=b'$value$'\n",
+ //##!PY25 "serialized_pb=b'$value$'\n",
"serialized_pb=_b('$value$')\n", //##PY25
"value", strings::CHexEscape(file_descriptor_serialized_));
if (file_->dependency_count() != 0) {
@@ -476,9 +470,9 @@ void Generator::PrintTopLevelEnums() const {
}
for (int i = 0; i < top_level_enum_values.size(); ++i) {
- printer_->Print("$name$ = $value$\n",
- "name", top_level_enum_values[i].first,
- "value", SimpleItoa(top_level_enum_values[i].second));
+ printer_->Print("$name$ = $value$\n", "name",
+ top_level_enum_values[i].first, "value",
+ SimpleItoa(top_level_enum_values[i].second));
}
printer_->Print("\n");
}
@@ -550,9 +544,9 @@ void Generator::PrintTopLevelExtensions() const {
const FieldDescriptor& extension_field = *file_->extension(i);
string constant_name = extension_field.name() + "_FIELD_NUMBER";
UpperString(&constant_name);
- printer_->Print("$constant_name$ = $number$\n",
- "constant_name", constant_name,
- "number", SimpleItoa(extension_field.number()));
+ printer_->Print("$constant_name$ = $number$\n", "constant_name",
+ constant_name, "number",
+ SimpleItoa(extension_field.number()));
printer_->Print("$name$ = ", "name", extension_field.name());
PrintFieldDescriptor(extension_field, is_extension);
printer_->Print("\n");
@@ -745,9 +739,9 @@ void Generator::PrintDescriptor(const Descriptor& message_descriptor) const {
for (int i = 0; i < message_descriptor.extension_range_count(); ++i) {
const Descriptor::ExtensionRange* range =
message_descriptor.extension_range(i);
- printer_->Print("($start$, $end$), ",
- "start", SimpleItoa(range->start),
- "end", SimpleItoa(range->end));
+ printer_->Print("($start$, $end$), ", "start",
+ SimpleItoa(range->start), "end",
+ SimpleItoa(range->end));
}
printer_->Print("],\n");
printer_->Print("oneofs=[\n");
@@ -1184,7 +1178,8 @@ void Generator::PrintExtensionsInDescriptor(
}
bool Generator::GeneratingDescriptorProto() const {
- return file_->name() == "google/protobuf/descriptor.proto";
+ return file_->name() == "net/proto2/proto/descriptor.proto" ||
+ file_->name() == "google/protobuf/descriptor.proto";
}
// Returns the unique Python module-level identifier given to a descriptor.
@@ -1260,10 +1255,11 @@ void Generator::PrintSerializedPbInterval(
int offset = file_descriptor_serialized_.find(sp);
GOOGLE_CHECK_GE(offset, 0);
- printer_->Print("serialized_start=$serialized_start$,\n"
- "serialized_end=$serialized_end$,\n",
- "serialized_start", SimpleItoa(offset),
- "serialized_end", SimpleItoa(offset + sp.size()));
+ printer_->Print(
+ "serialized_start=$serialized_start$,\n"
+ "serialized_end=$serialized_end$,\n",
+ "serialized_start", SimpleItoa(offset), "serialized_end",
+ SimpleItoa(offset + sp.size()));
}
namespace {
diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/python_generator.h
index 8e4050de..c21c36da 100644
--- a/src/google/protobuf/compiler/python/python_generator.h
+++ b/src/google/protobuf/compiler/python/python_generator.h
@@ -38,8 +38,8 @@
#include <string>
#include <google/protobuf/compiler/code_generator.h>
-#include <google/protobuf/stubs/mutex.h>
-#include <google/protobuf/stubs/common.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -60,16 +60,16 @@ namespace python {
// If you create your own protocol compiler binary and you want it to support
// Python output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT Generator : public CodeGenerator {
+class PROTOC_EXPORT Generator : public CodeGenerator {
public:
Generator();
virtual ~Generator();
// CodeGenerator methods.
virtual bool Generate(const FileDescriptor* file,
- const string& parameter,
+ const std::string& parameter,
GeneratorContext* generator_context,
- string* error) const;
+ std::string* error) const;
private:
void PrintImports() const;
@@ -86,7 +86,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void PrintFieldDescriptorsInDescriptor(
const Descriptor& message_descriptor,
bool is_extension,
- const string& list_variable_name,
+ const std::string& list_variable_name,
int (Descriptor::*CountFn)() const,
const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const;
void PrintFieldsInDescriptor(const Descriptor& message_descriptor) const;
@@ -96,11 +96,11 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void PrintNestedDescriptors(const Descriptor& containing_descriptor) const;
void PrintMessages() const;
- void PrintMessage(const Descriptor& message_descriptor, const string& prefix,
- std::vector<string>* to_register) const;
+ void PrintMessage(const Descriptor& message_descriptor, const std::string& prefix,
+ std::vector<std::string>* to_register) const;
void PrintNestedMessages(const Descriptor& containing_descriptor,
- const string& prefix,
- std::vector<string>* to_register) const;
+ const std::string& prefix,
+ std::vector<std::string>* to_register) const;
void FixForeignFieldsInDescriptors() const;
void FixForeignFieldsInDescriptor(
@@ -108,14 +108,14 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
const Descriptor* containing_descriptor) const;
void FixForeignFieldsInField(const Descriptor* containing_type,
const FieldDescriptor& field,
- const string& python_dict_name) const;
+ const std::string& python_dict_name) const;
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,
+ std::string FieldReferencingExpression(const Descriptor* containing_type,
const FieldDescriptor& field,
- const string& python_dict_name) const;
+ const std::string& python_dict_name) const;
template <typename DescriptorT>
void FixContainingTypeInDescriptor(
const DescriptorT& descriptor,
@@ -135,13 +135,13 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
const ServiceDescriptor& descriptor) const;
void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const;
- string OptionsValue(const string& serialized_options) const;
+ std::string OptionsValue(const std::string& serialized_options) const;
bool GeneratingDescriptorProto() const;
template <typename DescriptorT>
- string ModuleLevelDescriptorName(const DescriptorT& descriptor) const;
- string ModuleLevelMessageName(const Descriptor& descriptor) const;
- string ModuleLevelServiceDescriptorName(
+ std::string ModuleLevelDescriptorName(const DescriptorT& descriptor) const;
+ std::string ModuleLevelMessageName(const Descriptor& descriptor) const;
+ std::string ModuleLevelServiceDescriptorName(
const ServiceDescriptor& descriptor) const;
template <typename DescriptorT, typename DescriptorProtoT>
@@ -155,13 +155,13 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
void FixOptionsForMessage(const Descriptor& descriptor) const;
void CopyPublicDependenciesAliases(
- const string& copy_from, const FileDescriptor* file) const;
+ const std::string& copy_from, const FileDescriptor* file) const;
// Very coarse-grained lock to ensure that Generate() is reentrant.
// Guards file_, printer_ and file_descriptor_serialized_.
mutable Mutex mutex_;
mutable const FileDescriptor* file_; // Set in Generate(). Under mutex_.
- mutable string file_descriptor_serialized_;
+ mutable std::string file_descriptor_serialized_;
mutable io::Printer* printer_; // Set in Generate(). Under mutex_.
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Generator);
@@ -170,6 +170,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
} // namespace python
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_PYTHON_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/src/google/protobuf/compiler/python/python_plugin_unittest.cc
index 2f096808..d19d11f0 100644
--- a/src/google/protobuf/compiler/python/python_plugin_unittest.cc
+++ b/src/google/protobuf/compiler/python/python_plugin_unittest.cc
@@ -90,7 +90,7 @@ TEST(PythonPluginTest, PluginTest) {
"}\n",
true));
- google::protobuf::compiler::CommandLineInterface cli;
+ compiler::CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
python::Generator python_generator;
@@ -133,7 +133,7 @@ TEST(PythonPluginTest, ImportTest) {
"message Message2 {}\n",
true));
- google::protobuf::compiler::CommandLineInterface cli;
+ compiler::CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
python::Generator python_generator;
cli.RegisterGenerator("--python_out", &python_generator, "");
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.h b/src/google/protobuf/compiler/ruby/ruby_generator.h
index 8c1dfa26..521697fb 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator.h
+++ b/src/google/protobuf/compiler/ruby/ruby_generator.h
@@ -37,6 +37,8 @@
#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace compiler {
@@ -46,7 +48,7 @@ namespace ruby {
// If you create your own protocol compiler binary and you want it to support
// Ruby output, you can do so by registering an instance of this
// CodeGenerator with the CommandLineInterface in your main() function.
-class LIBPROTOC_EXPORT Generator
+class PROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
virtual bool Generate(
const FileDescriptor* file,
@@ -60,5 +62,7 @@ class LIBPROTOC_EXPORT Generator
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc b/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc
index 1aabe8aa..8454a5c5 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc
+++ b/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc
@@ -90,12 +90,12 @@ TEST(RubyGeneratorTest, GeneratorTest) {
// Load the generated output and compare to the expected result.
string output;
- GOOGLE_CHECK_OK(File::GetContents(
+ GOOGLE_CHECK_OK(File::GetContentsAsText(
TestTempDir() + "/ruby_generated_code_pb.rb",
&output,
true));
string expected_output;
- GOOGLE_CHECK_OK(File::GetContents(
+ GOOGLE_CHECK_OK(File::GetContentsAsText(
ruby_tests + "/ruby_generated_code_pb.rb",
&expected_output,
true));
diff --git a/src/google/protobuf/compiler/scc.cc b/src/google/protobuf/compiler/scc.cc
new file mode 100644
index 00000000..bbdabbfc
--- /dev/null
+++ b/src/google/protobuf/compiler/scc.cc
@@ -0,0 +1,111 @@
+// 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/scc.h>
+
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/descriptor.h>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+
+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 == nullptr) {
+ // 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(),
+ [](const Descriptor* a, const Descriptor* b) {
+ return a->full_name() < b->full_name();
+ });
+ 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);
+ }
+ }
+ }
+ }
+}
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/scc.h b/src/google/protobuf/compiler/scc.h
new file mode 100644
index 00000000..c8cf77d6
--- /dev/null
+++ b/src/google/protobuf/compiler/scc.h
@@ -0,0 +1,99 @@
+// 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_SCC_H__
+#define GOOGLE_PROTOBUF_COMPILER_SCC_H__
+
+#include <map>
+
+#include <google/protobuf/descriptor.h>
+
+#include <google/protobuf/port_def.inc>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+
+// 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]; }
+};
+
+// This class is used for analyzing the SCC for each message, to ensure linear
+// instead of quadratic performance, if we do this per message we would get
+// O(V*(V+E)).
+class PROTOC_EXPORT SCCAnalyzer {
+ public:
+ explicit SCCAnalyzer() : index_(0) {}
+
+ const SCC* GetSCC(const Descriptor* descriptor) {
+ if (cache_.count(descriptor)) return cache_[descriptor].scc;
+ return DFS(descriptor).scc;
+ }
+
+ private:
+ struct NodeData {
+ const SCC* scc; // if null it means its still on the stack
+ int index;
+ int lowlink;
+ };
+
+ std::map<const Descriptor*, NodeData> cache_;
+ std::vector<const Descriptor*> stack_;
+ int index_;
+ std::vector<std::unique_ptr<SCC>> garbage_bin_;
+
+ SCC* CreateSCC() {
+ garbage_bin_.emplace_back(new SCC());
+ return garbage_bin_.back().get();
+ }
+
+ // 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);
+
+ // This is necessary for compiler bug in msvc2015.
+ GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SCCAnalyzer);
+};
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
+#endif // GOOGLE_PROTOBUF_COMPILER_SCC_H__
diff --git a/src/google/protobuf/compiler/subprocess.h b/src/google/protobuf/compiler/subprocess.h
index 9d980b06..977abff7 100644
--- a/src/google/protobuf/compiler/subprocess.h
+++ b/src/google/protobuf/compiler/subprocess.h
@@ -44,6 +44,8 @@
#include <string>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -52,7 +54,7 @@ class Message;
namespace compiler {
// Utility class for launching sub-processes.
-class LIBPROTOC_EXPORT Subprocess {
+class PROTOC_EXPORT Subprocess {
public:
Subprocess();
~Subprocess();
@@ -64,19 +66,19 @@ class LIBPROTOC_EXPORT Subprocess {
// Start the subprocess. Currently we don't provide a way to specify
// arguments as protoc plugins don't have any.
- void Start(const string& program, SearchMode search_mode);
+ void Start(const std::string& program, SearchMode search_mode);
// Serialize the input message and pipe it to the subprocess's stdin, then
// close the pipe. Meanwhile, read from the subprocess's stdout and parse
// the data into *output. All this is done carefully to avoid deadlocks.
// Returns true if successful. On any sort of error, returns false and sets
// *error to a description of the problem.
- bool Communicate(const Message& input, Message* output, string* error);
+ bool Communicate(const Message& input, Message* output, std::string* error);
#ifdef _WIN32
// Given an error code, returns a human-readable error message. This is
// defined here so that CommandLineInterface can share it.
- static string Win32ErrorMessage(DWORD error_code);
+ static std::string Win32ErrorMessage(DWORD error_code);
#endif
private:
@@ -102,6 +104,8 @@ class LIBPROTOC_EXPORT Subprocess {
} // namespace compiler
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__
diff --git a/src/google/protobuf/compiler/test_plugin.cc b/src/google/protobuf/compiler/test_plugin.cc
index c676ce8c..4b758764 100644
--- a/src/google/protobuf/compiler/test_plugin.cc
+++ b/src/google/protobuf/compiler/test_plugin.cc
@@ -38,13 +38,24 @@
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/compiler/mock_code_generator.h>
+namespace google {
+namespace protobuf {
+namespace compiler {
+
+int ProtobufMain(int argc, char* argv[]) {
+ MockCodeGenerator generator("test_plugin");
+ return PluginMain(argc, argv, &generator);
+}
+
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
int main(int argc, char* argv[]) {
#ifdef _MSC_VER
// Don't print a silly message or stick a modal dialog box in my face,
// please.
_set_abort_behavior(0, ~0);
#endif // !_MSC_VER
-
- google::protobuf::compiler::MockCodeGenerator generator("test_plugin");
- return google::protobuf::compiler::PluginMain(argc, argv, &generator);
+ return google::protobuf::compiler::ProtobufMain(argc, argv);
}
diff --git a/src/google/protobuf/compiler/zip_writer.h b/src/google/protobuf/compiler/zip_writer.h
index 03db4d57..a99bb78c 100644
--- a/src/google/protobuf/compiler/zip_writer.h
+++ b/src/google/protobuf/compiler/zip_writer.h
@@ -73,12 +73,12 @@ class ZipWriter {
ZipWriter(io::ZeroCopyOutputStream* raw_output);
~ZipWriter();
- bool Write(const string& filename, const string& contents);
+ bool Write(const std::string& filename, const std::string& contents);
bool WriteDirectory();
private:
struct FileInfo {
- string name;
+ std::string name;
uint32 offset;
uint32 size;
uint32 crc32;
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc
index fc3a9c77..26f2b8c8 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -34,19 +34,17 @@
#include <algorithm>
#include <functional>
-#include <google/protobuf/stubs/hash.h>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
+#include <unordered_map>
+#include <unordered_set>
#include <vector>
-#include <google/protobuf/stubs/casts.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/descriptor.pb.h>
@@ -62,15 +60,19 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/hash.h>
#undef PACKAGE // autoheader #defines this. :(
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+namespace google {
namespace protobuf {
struct Symbol {
@@ -399,16 +401,17 @@ struct PointerStringPairEqual {
typedef std::pair<const Descriptor*, int> DescriptorIntPair;
typedef std::pair<const EnumDescriptor*, int> EnumIntPair;
-#define HASH_MAP hash_map
-#define HASH_SET hash_set
+#define HASH_MAP std::unordered_map
+#define HASH_SET std::unordered_set
#define HASH_FXN hash
template<typename PairType>
struct PointerIntegerPairHash {
size_t operator()(const PairType& p) const {
- // FIXME(kenton): What is the best way to compute this hash? I have
- // no idea! This seems a bit better than an XOR.
- return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + p.second;
+ static const size_t prime1 = 16777499;
+ static const size_t prime2 = 16777619;
+ return reinterpret_cast<size_t>(p.first) * prime1 ^
+ static_cast<size_t>(p.second) * prime2;
}
#ifdef _MSC_VER
@@ -424,11 +427,10 @@ struct PointerIntegerPairHash {
struct PointerStringPairHash {
size_t operator()(const PointerStringPair& p) const {
- // FIXME(kenton): What is the best way to compute this hash? I have
- // no idea! This seems a bit better than an XOR.
+ static const size_t prime = 16777619;
hash<const char*> cstring_hash;
- return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) +
- cstring_hash(p.second);
+ return reinterpret_cast<size_t>(p.first) * prime ^
+ static_cast<size_t>(cstring_hash(p.second));
}
#ifdef _MSC_VER
@@ -489,7 +491,7 @@ std::set<string>* NewAllowedProto3Extendee() {
// both so the opensource protocol compiler can also compile internal
// proto3 files with custom options. See: b/27567912
allowed_proto3_extendees->insert(string("google.protobuf.") +
- kOptionNames[i]);
+ kOptionNames[i]);
// Split the word to trick the opensource processing scripts so they
// will keep the origial package name.
allowed_proto3_extendees->insert(string("proto") + "2." + kOptionNames[i]);
@@ -626,9 +628,9 @@ 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
+ // Allocate a internal::call_once which will be destroyed when the pool is
// destroyed.
- GoogleOnceDynamic* AllocateOnceDynamic();
+ internal::once_flag* AllocateOnceDynamic();
// Allocate a protocol message object. Some older versions of GCC have
// trouble understanding explicit template instantiations in some cases, so
@@ -642,8 +644,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<internal::once_flag*>
+ once_dynamics_; // All internal::call_onces 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.
@@ -742,7 +744,7 @@ class FileDescriptorTables {
void AddFieldByStylizedNames(const FieldDescriptor* field);
// Populates p->first->locations_by_path_ from p->second.
- // Unusual signature dictated by GoogleOnceDynamic.
+ // Unusual signature dictated by internal::call_once.
static void BuildLocationsByPath(
std::pair<const FileDescriptorTables*, const SourceCodeInfo*>* p);
@@ -769,22 +771,22 @@ class FileDescriptorTables {
SymbolsByParentMap symbols_by_parent_;
mutable FieldsByNameMap fields_by_lowercase_name_;
std::unique_ptr<FieldsByNameMap> fields_by_lowercase_name_tmp_;
- mutable GoogleOnceDynamic fields_by_lowercase_name_once_;
+ mutable internal::once_flag fields_by_lowercase_name_once_;
mutable FieldsByNameMap fields_by_camelcase_name_;
std::unique_ptr<FieldsByNameMap> fields_by_camelcase_name_tmp_;
- mutable GoogleOnceDynamic fields_by_camelcase_name_once_;
+ mutable internal::once_flag 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_);
+ PROTOBUF_GUARDED_BY(unknown_enum_values_mu_);
// Populated on first request to save space, hence constness games.
- mutable GoogleOnceDynamic locations_by_path_once_;
+ mutable internal::once_flag locations_by_path_once_;
mutable LocationsByPathMap locations_by_path_;
// Mutex to protect the unknown-enum-value map due to dynamic
// EnumValueDescriptor creation on unknown values.
- mutable Mutex unknown_enum_values_mu_;
+ mutable internal::WrappedMutex unknown_enum_values_mu_;
};
DescriptorPool::Tables::Tables()
@@ -908,8 +910,8 @@ inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const {
inline Symbol FileDescriptorTables::FindNestedSymbol(
const void* parent, const string& name) const {
- const Symbol* result =
- FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str()));
+ const Symbol* result = FindOrNull(
+ symbols_by_parent_, PointerStringPair(parent, name.c_str()));
if (result == NULL) {
return kNullSymbol;
} else {
@@ -982,16 +984,18 @@ void FileDescriptorTables::FieldsByLowercaseNamesLazyInitInternal() const {
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);
+ 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(
+ internal::call_once(
+ fields_by_lowercase_name_once_,
&FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic, this);
return FindPtrOrNull(fields_by_lowercase_name_,
- PointerStringPair(parent, lowercase_name.c_str()));
+ PointerStringPair(parent, lowercase_name.c_str()));
}
void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic(
@@ -1004,21 +1008,24 @@ void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitInternal() const {
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);
+ 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);
+ internal::call_once(
+ fields_by_camelcase_name_once_,
+ FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic, this);
return FindPtrOrNull(fields_by_camelcase_name_,
- PointerStringPair(parent, camelcase_name.c_str()));
+ PointerStringPair(parent, camelcase_name.c_str()));
}
inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber(
const EnumDescriptor* parent, int number) const {
- return FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number));
+ return FindPtrOrNull(enum_values_by_number_,
+ std::make_pair(parent, number));
}
inline const EnumValueDescriptor*
@@ -1026,8 +1033,8 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown(
const EnumDescriptor* parent, int number) const {
// First try, with map of compiled-in values.
{
- const EnumValueDescriptor* desc =
- FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number));
+ const EnumValueDescriptor* desc = FindPtrOrNull(
+ enum_values_by_number_, std::make_pair(parent, number));
if (desc != NULL) {
return desc;
}
@@ -1068,7 +1075,7 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown(
result->type_ = parent;
result->options_ = &EnumValueOptions::default_instance();
InsertIfNotPresent(&unknown_enum_values_by_number_,
- std::make_pair(parent, number), result);
+ std::make_pair(parent, number), result);
return result;
}
}
@@ -1134,16 +1141,16 @@ void FileDescriptorTables::AddFieldByStylizedNames(
// entries from fields_by_number_.
PointerStringPair lowercase_key(parent, field->lowercase_name().c_str());
- if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(), lowercase_key,
- field)) {
+ if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(),
+ 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());
- if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(), camelcase_key,
- field)) {
+ if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(),
+ camelcase_key, field)) {
InsertIfNotPresent(
&fields_by_camelcase_name_, camelcase_key,
FindPtrOrNull(*fields_by_camelcase_name_tmp_, camelcase_key));
@@ -1189,8 +1196,8 @@ string* DescriptorPool::Tables::AllocateString(const string& value) {
return result;
}
-GoogleOnceDynamic* DescriptorPool::Tables::AllocateOnceDynamic() {
- GoogleOnceDynamic* result = new GoogleOnceDynamic();
+internal::once_flag* DescriptorPool::Tables::AllocateOnceDynamic() {
+ internal::once_flag* result = new internal::once_flag();
once_dynamics_.push_back(result);
return result;
}
@@ -1232,7 +1239,8 @@ const SourceCodeInfo_Location* FileDescriptorTables::GetSourceLocation(
const std::vector<int>& path, const SourceCodeInfo* info) const {
std::pair<const FileDescriptorTables*, const SourceCodeInfo*> p(
std::make_pair(this, info));
- locations_by_path_once_.Init(&FileDescriptorTables::BuildLocationsByPath, &p);
+ internal::call_once(locations_by_path_once_,
+ FileDescriptorTables::BuildLocationsByPath, &p);
return FindPtrOrNull(locations_by_path_, Join(path, ","));
}
@@ -1255,7 +1263,7 @@ DescriptorPool::DescriptorPool()
DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database,
ErrorCollector* error_collector)
- : mutex_(new Mutex),
+ : mutex_(new internal::WrappedMutex),
fallback_database_(fallback_database),
default_error_collector_(error_collector),
underlay_(NULL),
@@ -1307,6 +1315,7 @@ bool DescriptorPool::InternalIsFileLoaded(const string& filename) const {
namespace {
+
EncodedDescriptorDatabase* GeneratedDatabase() {
static auto generated_database =
internal::OnShutdownDelete(new EncodedDescriptorDatabase());
@@ -1331,6 +1340,8 @@ const DescriptorPool* DescriptorPool::generated_pool() {
return internal_generated_pool();
}
+
+
void DescriptorPool::InternalAddGeneratedFile(
const void* encoded_file_descriptor, int size) {
// So, this function is called in the process of initializing the
@@ -1760,7 +1771,7 @@ void Descriptor::ExtensionRange::CopyTo(
DescriptorProto_ExtensionRange* proto) const {
proto->set_start(this->start);
proto->set_end(this->end);
- if (options_ != &google::protobuf::ExtensionRangeOptions::default_instance()) {
+ if (options_ != &ExtensionRangeOptions::default_instance()) {
*proto->mutable_options() = *options_;
}
}
@@ -2079,9 +2090,9 @@ void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const {
// Some compilers do not allow static_cast directly between two enum types,
// so we must cast to int first.
proto->set_label(static_cast<FieldDescriptorProto::Label>(
- implicit_cast<int>(label())));
+ ::google::protobuf::implicit_cast<int>(label())));
proto->set_type(static_cast<FieldDescriptorProto::Type>(
- implicit_cast<int>(type())));
+ ::google::protobuf::implicit_cast<int>(type())));
if (is_extension()) {
if (!containing_type()->is_unqualified_placeholder_) {
@@ -2257,9 +2268,8 @@ bool RetrieveOptions(int depth, const Message& options,
const Descriptor* option_descriptor =
pool->FindMessageTypeByName(options.GetDescriptor()->full_name());
if (option_descriptor == NULL) {
- // google/protobuf/descriptor.proto is not in the pool. This means no
- // custom options are used so we are safe to proceed with the compiled
- // options message type.
+ // descriptor.proto is not in the pool. This means no custom options are
+ // used so we are safe to proceed with the compiled options message type.
return RetrieveOptionsAssumingRightPool(depth, options, option_entries);
}
DynamicMessageFactory factory;
@@ -2919,7 +2929,7 @@ void MethodDescriptor::DebugString(int depth, string *contents,
bool FileDescriptor::GetSourceLocation(const std::vector<int>& path,
SourceLocation* out_location) const {
- GOOGLE_CHECK_NOTNULL(out_location);
+ GOOGLE_CHECK(out_location != nullptr);
if (source_code_info_) {
if (const SourceCodeInfo_Location* loc =
tables_->GetSourceLocation(path, source_code_info_)) {
@@ -3071,17 +3081,14 @@ namespace {
// pointers in the original options, not the mutable copy). The Message must be
// one of the Options messages in descriptor.proto.
struct OptionsToInterpret {
- OptionsToInterpret(const string& ns,
- const string& el,
- std::vector<int>& path,
- const Message* orig_opt,
+ OptionsToInterpret(const string& ns, const string& el,
+ const std::vector<int>& path, const Message* orig_opt,
Message* opt)
: name_scope(ns),
element_name(el),
element_path(path),
original_options(orig_opt),
- options(opt) {
- }
+ options(opt) {}
string name_scope;
string element_name;
std::vector<int> element_path;
@@ -3249,20 +3256,19 @@ class DescriptorBuilder {
// descriptor. Remembers its uninterpreted options, to be interpreted
// later. DescriptorT must be one of the Descriptor messages from
// descriptor.proto.
- template<class DescriptorT> void AllocateOptions(
- const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor, int options_field_tag);
+ template <class DescriptorT>
+ void AllocateOptions(const typename DescriptorT::OptionsType& orig_options,
+ DescriptorT* descriptor, int options_field_tag);
// Specialization for FileOptions.
void AllocateOptions(const FileOptions& orig_options,
FileDescriptor* descriptor);
// Implementation for AllocateOptions(). Don't call this directly.
- template<class DescriptorT> void AllocateOptionsImpl(
- const string& name_scope,
- const string& element_name,
+ template <class DescriptorT>
+ void AllocateOptionsImpl(
+ const string& name_scope, const string& element_name,
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor,
- std::vector<int>& options_path);
+ DescriptorT* descriptor, const std::vector<int>& options_path);
// These methods all have the same signature for the sake of the BUILD_ARRAY
// macro, below.
@@ -3364,8 +3370,9 @@ class DescriptorBuilder {
// location path to the uninterpreted option, and options_path is the
// source location path to the options message. The location paths are
// recorded and then used in UpdateSourceCodeInfo.
- bool InterpretSingleOption(Message* options, std::vector<int>& src_path,
- std::vector<int>& options_path);
+ bool InterpretSingleOption(Message* options,
+ const std::vector<int>& src_path,
+ const std::vector<int>& options_path);
// Adds the uninterpreted_option to the given options message verbatim.
// Used when AllowUnknownDependencies() is in effect and we can't find
@@ -4065,7 +4072,8 @@ void DescriptorBuilder::ValidateSymbolName(
// This generic implementation is good for all descriptors except
// FileDescriptor.
-template<class DescriptorT> void DescriptorBuilder::AllocateOptions(
+template <class DescriptorT>
+void DescriptorBuilder::AllocateOptions(
const typename DescriptorT::OptionsType& orig_options,
DescriptorT* descriptor, int options_field_tag) {
std::vector<int> options_path;
@@ -4085,18 +4093,25 @@ void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options,
orig_options, descriptor, options_path);
}
-template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl(
- const string& name_scope,
- const string& element_name,
+template <class DescriptorT>
+void DescriptorBuilder::AllocateOptionsImpl(
+ const string& name_scope, const string& element_name,
const typename DescriptorT::OptionsType& orig_options,
- DescriptorT* descriptor,
- std::vector<int>& options_path) {
+ DescriptorT* descriptor, const std::vector<int>& options_path) {
// We need to use a dummy pointer to work around a bug in older versions of
// GCC. Otherwise, the following two lines could be replaced with:
// typename DescriptorT::OptionsType* options =
// tables_->AllocateMessage<typename DescriptorT::OptionsType>();
typename DescriptorT::OptionsType* const dummy = NULL;
typename DescriptorT::OptionsType* options = tables_->AllocateMessage(dummy);
+
+ if (!orig_options.IsInitialized()) {
+ AddError(name_scope + "." + element_name, orig_options,
+ DescriptorPool::ErrorCollector::OPTION_NAME,
+ "Uninterpreted option is missing name or value.");
+ return;
+ }
+
// Avoid using MergeFrom()/CopyFrom() in this class to make it -fno-rtti
// friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback to the
// reflection based method, which requires the Descriptor. However, we are in
@@ -4112,13 +4127,11 @@ template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl(
// OptionsType::GetDescriptor() to be called which may then deadlock since
// we're still trying to build it.
if (options->uninterpreted_option_size() > 0) {
- options_to_interpret_.push_back(
- OptionsToInterpret(name_scope, element_name, options_path,
- &orig_options, options));
+ options_to_interpret_.push_back(OptionsToInterpret(
+ name_scope, element_name, options_path, &orig_options, options));
}
}
-
// A common pattern: We want to convert a repeated field in the descriptor
// to an array of values, calling some method to build each value.
#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \
@@ -4252,7 +4265,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl(
result->is_placeholder_ = false;
result->finished_building_ = false;
- SourceCodeInfo *info = NULL;
+ SourceCodeInfo* info = nullptr;
if (proto.has_source_code_info()) {
info = tables_->AllocateMessage<SourceCodeInfo>();
info->CopyFrom(proto.source_code_info());
@@ -4452,8 +4465,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl(
option_interpreter.InterpretOptions(&(*iter));
}
options_to_interpret_.clear();
-
- if (info != NULL) {
+ if (info != nullptr) {
option_interpreter.UpdateSourceCodeInfo(info);
}
}
@@ -4528,7 +4540,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- DescriptorProto::kOptionsFieldNumber);
+ DescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -4669,10 +4681,10 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
// Some compilers do not allow static_cast directly between two enum types,
// so we must cast to int first.
- result->type_ = static_cast<FieldDescriptor::Type>(
- implicit_cast<int>(proto.type()));
+ result->type_ = static_cast<FieldDescriptor::Type>(
+ ::google::protobuf::implicit_cast<int>(proto.type()));
result->label_ = static_cast<FieldDescriptor::Label>(
- implicit_cast<int>(proto.label()));
+ ::google::protobuf::implicit_cast<int>(proto.label()));
// An extension cannot have a required field (b/13365836).
if (result->is_extension_ &&
@@ -4909,7 +4921,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- FieldDescriptorProto::kOptionsFieldNumber);
+ FieldDescriptorProto::kOptionsFieldNumber);
}
@@ -4948,7 +4960,8 @@ void DescriptorBuilder::BuildExtensionRange(
options_path.push_back(DescriptorProto::kExtensionRangeFieldNumber);
// find index of this extension range in order to compute path
int index;
- for (index = 0; parent->extension_ranges_ + index != result; index++);
+ for (index = 0; parent->extension_ranges_ + index != result; index++) {
+ }
options_path.push_back(index);
options_path.push_back(DescriptorProto_ExtensionRange::kOptionsFieldNumber);
AllocateOptionsImpl(parent->full_name(), parent->full_name(),
@@ -5005,7 +5018,7 @@ void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- OneofDescriptorProto::kOptionsFieldNumber);
+ OneofDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -5041,13 +5054,12 @@ void DescriptorBuilder::CheckEnumValueUniqueness(
// NAME_TYPE_LAST_NAME = 2,
// }
PrefixRemover remover(result->name());
- std::map<string, const google::protobuf::EnumValueDescriptor*> values;
+ std::map<string, const EnumValueDescriptor*> values;
for (int i = 0; i < result->value_count(); i++) {
- const google::protobuf::EnumValueDescriptor* value = result->value(i);
+ const EnumValueDescriptor* value = result->value(i);
string stripped =
EnumValueToPascalCase(remover.MaybeRemove(value->name()));
- std::pair<std::map<string, const google::protobuf::EnumValueDescriptor*>::iterator,
- bool>
+ std::pair<std::map<string, const EnumValueDescriptor*>::iterator, bool>
insert_result = values.insert(std::make_pair(stripped, value));
bool inserted = insert_result.second;
@@ -5123,7 +5135,7 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- EnumDescriptorProto::kOptionsFieldNumber);
+ EnumDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), parent, result->name(),
@@ -5201,7 +5213,7 @@ void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- EnumValueDescriptorProto::kOptionsFieldNumber);
+ EnumValueDescriptorProto::kOptionsFieldNumber);
}
// Again, enum values are weird because we makes them appear as siblings
@@ -5269,7 +5281,7 @@ void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- ServiceDescriptorProto::kOptionsFieldNumber);
+ ServiceDescriptorProto::kOptionsFieldNumber);
}
AddSymbol(result->full_name(), NULL, result->name(),
@@ -5298,7 +5310,7 @@ void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto,
result->options_ = NULL; // Will set to default_instance later.
} else {
AllocateOptions(proto.options(), result,
- MethodDescriptorProto::kOptionsFieldNumber);
+ MethodDescriptorProto::kOptionsFieldNumber);
}
result->client_streaming_ = proto.client_streaming();
@@ -6017,6 +6029,23 @@ void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field,
ValidateJSType(field, proto);
+ // json_name option is not allowed on extension fields. Note that the
+ // json_name field in FieldDescriptorProto is always populated by protoc
+ // when it sends descriptor data to plugins (caculated from field name if
+ // the option is not explicitly set) so we can't rely on its presence to
+ // determine whether the json_name option is set on the field. Here we
+ // compare it against the default calculated json_name value and consider
+ // the option set if they are different. This won't catch the case when
+ // an user explicitly sets json_name to the default value, but should be
+ // good enough to catch common misuses.
+ if (field->is_extension() &&
+ (field->has_json_name() &&
+ field->json_name() != ToJsonName(field->name()))) {
+ AddError(field->full_name(), proto,
+ DescriptorPool::ErrorCollector::OPTION_NAME,
+ "option json_name is not allowed on extension fields.");
+ }
+
}
void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm,
@@ -6308,25 +6337,31 @@ bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
// If they are not known, that's OK too. They will get reparsed into the
// UnknownFieldSet and wait there until the message is parsed by something
// that does know about the options.
+
+ // Keep the unparsed options around in case the reparsing fails.
+ std::unique_ptr<Message> unparsed_options(options->New());
+ options->GetReflection()->Swap(unparsed_options.get(), options);
+
string buf;
- GOOGLE_CHECK(options->AppendPartialToString(&buf))
- << "Protocol message could not be serialized.";
- GOOGLE_CHECK(options->ParsePartialFromString(buf))
- << "Protocol message serialized itself in invalid fashion.";
- if (!options->IsInitialized()) {
- builder_->AddWarning(
+ if (!unparsed_options->AppendToString(&buf) ||
+ !options->ParseFromString(buf)) {
+ builder_->AddError(
options_to_interpret->element_name, *original_options,
DescriptorPool::ErrorCollector::OTHER,
- "Options could not be fully parsed using the proto descriptors "
- "compiled into this binary. Missing required fields: " +
- options->InitializationErrorString());
+ "Some options could not be correctly parsed using the proto "
+ "descriptors compiled into this binary.\n"
+ "Unparsed options: " + unparsed_options->ShortDebugString() + "\n"
+ "Parsing attempt: " + options->ShortDebugString());
+ // Restore the unparsed options.
+ options->GetReflection()->Swap(unparsed_options.get(), options);
}
}
return !failed;
}
bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
- Message* options, std::vector<int>& src_path, std::vector<int>& opts_path) {
+ Message* options, const std::vector<int>& src_path,
+ const std::vector<int>& options_path) {
// First do some basic validation.
if (uninterpreted_option_->name_size() == 0) {
// This should never happen unless the parser has gone seriously awry or
@@ -6340,9 +6375,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
const Descriptor* options_descriptor = NULL;
// Get the options message's descriptor from the builder's pool, so that we
- // get the version that knows about any extension options declared in the
- // file we're currently building. The descriptor should be there as long as
- // the file we're building imported "google/protobuf/descriptors.proto".
+ // get the version that knows about any extension options declared in the file
+ // we're currently building. The descriptor should be there as long as the
+ // file we're building imported descriptor.proto.
// Note that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not
// DescriptorPool::FindMessageTypeByName() because we're already holding the
@@ -6372,7 +6407,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
std::vector<const FieldDescriptor*> intermediate_fields;
string debug_msg_name = "";
- std::vector<int> dest_path = opts_path;
+ std::vector<int> dest_path = options_path;
for (int i = 0; i < uninterpreted_option_->name_size(); ++i) {
const string& name_part = uninterpreted_option_->name(i).name_part();
@@ -6417,7 +6452,9 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
debug_msg_name.substr(1) +
"\") to start from the outermost scope.");
} else {
- return AddNameError("Option \"" + debug_msg_name + "\" unknown.");
+ return AddNameError(
+ "Option \"" + debug_msg_name + "\" unknown. Ensure that your proto" +
+ " definition file imports the proto which defines the option.");
}
} else if (field->containing_type() != descriptor) {
if (get_is_placeholder(field->containing_type())) {
@@ -6442,7 +6479,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
if (i < uninterpreted_option_->name_size() - 1) {
if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
- return AddNameError("Option \"" + debug_msg_name +
+ return AddNameError("Option \"" + debug_msg_name +
"\" is an atomic type, not a message.");
} else if (field->is_repeated()) {
return AddNameError("Option field \"" + debug_msg_name +
@@ -6531,7 +6568,6 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
SourceCodeInfo* info) {
-
if (interpreted_paths_.empty()) {
// nothing to do!
return;
@@ -6556,7 +6592,6 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
for (RepeatedPtrField<SourceCodeInfo_Location>::iterator loc = locs->begin();
loc != locs->end(); loc++) {
-
if (matched) {
// see if this location is in the range to remove
bool loc_matches = true;
@@ -6590,7 +6625,7 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
if (entry == interpreted_paths_.end()) {
// not a match
if (copying) {
- new_locs.Add()->CopyFrom(*loc);
+ *new_locs.Add() = *loc;
}
continue;
}
@@ -6602,14 +6637,15 @@ void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
copying = true;
new_locs.Reserve(locs->size());
for (RepeatedPtrField<SourceCodeInfo_Location>::iterator it =
- locs->begin(); it != loc; it++) {
- new_locs.Add()->CopyFrom(*it);
+ locs->begin();
+ it != loc; it++) {
+ *new_locs.Add() = *it;
}
}
// add replacement and update its path
SourceCodeInfo_Location* replacement = new_locs.Add();
- replacement->CopyFrom(*loc);
+ *replacement = *loc;
replacement->clear_path();
for (std::vector<int>::iterator rit = entry->second.begin();
rit != entry->second.end(); rit++) {
@@ -6789,7 +6825,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
option_field->full_name() + "\".");
}
unknown_fields->AddFixed32(option_field->number(),
- google::protobuf::internal::WireFormatLite::EncodeFloat(value));
+ internal::WireFormatLite::EncodeFloat(value));
break;
}
@@ -6806,7 +6842,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
option_field->full_name() + "\".");
}
unknown_fields->AddFixed64(option_field->number(),
- google::protobuf::internal::WireFormatLite::EncodeDouble(value));
+ internal::WireFormatLite::EncodeDouble(value));
break;
}
@@ -6905,8 +6941,8 @@ class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder
public:
DescriptorBuilder* builder_;
- virtual const FieldDescriptor* FindExtension(
- Message* message, const string& name) const {
+ const FieldDescriptor* FindExtension(Message* message,
+ const string& name) const override {
assert_mutex_held(builder_->pool_);
const Descriptor* descriptor = message->GetDescriptor();
Symbol result = builder_->LookupSymbolNoPlaceholder(
@@ -6943,20 +6979,20 @@ class AggregateErrorCollector : public io::ErrorCollector {
public:
string error_;
- virtual void AddError(int /* line */, int /* column */,
- const string& message) {
+ void AddError(int /* line */, int /* column */,
+ const string& message) override {
if (!error_.empty()) {
error_ += "; ";
}
error_ += message;
}
- virtual void AddWarning(int /* line */, int /* column */,
- const string& /* message */) {
+ void AddWarning(int /* line */, int /* column */,
+ const string& /* message */) override {
// Ignore warnings
}
};
-}
+} // namespace
// We construct a dynamic message of the type corresponding to
// option_field, parse the supplied text-format string into this
@@ -7017,8 +7053,8 @@ void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value,
break;
case FieldDescriptor::TYPE_SINT32:
- unknown_fields->AddVarint(number,
- google::protobuf::internal::WireFormatLite::ZigZagEncode32(value));
+ unknown_fields->AddVarint(
+ number, internal::WireFormatLite::ZigZagEncode32(value));
break;
default:
@@ -7039,8 +7075,8 @@ void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value,
break;
case FieldDescriptor::TYPE_SINT64:
- unknown_fields->AddVarint(number,
- google::protobuf::internal::WireFormatLite::ZigZagEncode64(value));
+ unknown_fields->AddVarint(
+ number, internal::WireFormatLite::ZigZagEncode64(value));
break;
default:
@@ -7177,25 +7213,25 @@ void FieldDescriptor::TypeOnceInit(const FieldDescriptor* to_init) {
}
// message_type(), enum_type(), default_value_enum(), and type()
-// all share the same GoogleOnceDynamic init path to do lazy
+// all share the same internal::call_once 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);
+ internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return message_type_;
}
const EnumDescriptor* FieldDescriptor::enum_type() const {
if (type_once_) {
- type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return enum_type_;
}
const EnumValueDescriptor* FieldDescriptor::default_value_enum() const {
if (type_once_) {
- type_once_->Init(&FieldDescriptor::TypeOnceInit, this);
+ internal::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return default_value_enum_;
}
@@ -7216,8 +7252,9 @@ void FileDescriptor::DependenciesOnceInit(const FileDescriptor* to_init) {
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);
+ // be called, and saves on internal::call_once allocations.
+ internal::call_once(*dependencies_once_,
+ FileDescriptor::DependenciesOnceInit, this);
}
return dependencies_[index];
}
@@ -7255,7 +7292,7 @@ void LazyDescriptor::SetLazy(const string& name, const FileDescriptor* file) {
void LazyDescriptor::Once() {
if (once_) {
- once_->Init(&LazyDescriptor::OnceStatic, this);
+ internal::call_once(*once_, LazyDescriptor::OnceStatic, this);
}
}
diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h
index 115d4ddc..cf0a52bb 100644
--- a/src/google/protobuf/descriptor.h
+++ b/src/google/protobuf/descriptor.h
@@ -62,11 +62,17 @@
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/port_def.inc>
+
// TYPE_BOOL is defined in the MacOS's ConditionalMacros.h.
#ifdef TYPE_BOOL
#undef TYPE_BOOL
#endif // TYPE_BOOL
+#ifdef SWIG
+#define PROTOBUF_EXPORT
+#endif
+
namespace google {
namespace protobuf {
@@ -123,6 +129,10 @@ class GeneratedMessageReflection;
// Defined in command_line_interface.cc
namespace compiler {
class CommandLineInterface;
+namespace cpp {
+// Defined in helpers.h
+class Formatter;
+} // namespace cpp
} // namespace compiler
namespace descriptor_unittest {
@@ -143,9 +153,9 @@ struct SourceLocation {
// Doc comments found at the source location.
// See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
- string leading_comments;
- string trailing_comments;
- std::vector<string> leading_detached_comments;
+ std::string leading_comments;
+ std::string trailing_comments;
+ std::vector<std::string> leading_detached_comments;
};
// Options when generating machine-parsable output from a descriptor with
@@ -171,7 +181,7 @@ struct DebugStringOptions {
// 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 {
+class PROTOBUF_EXPORT LazyDescriptor {
public:
// Init function to be called at init time of a descriptor containing
// a LazyDescriptor.
@@ -193,7 +203,7 @@ class LIBPROTOBUF_EXPORT LazyDescriptor {
// 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);
+ void SetLazy(const std::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,
@@ -209,8 +219,8 @@ class LIBPROTOBUF_EXPORT LazyDescriptor {
void Once();
const Descriptor* descriptor_;
- const string* name_;
- GoogleOnceDynamic* once_;
+ const std::string* name_;
+ internal::once_flag* once_;
const FileDescriptor* file_;
};
} // namespace internal
@@ -220,17 +230,17 @@ class LIBPROTOBUF_EXPORT LazyDescriptor {
// Message::GetDescriptor(). Generated message classes also have a
// static method called descriptor() which returns the type's descriptor.
// Use DescriptorPool to construct your own descriptors.
-class LIBPROTOBUF_EXPORT Descriptor {
+class PROTOBUF_EXPORT Descriptor {
public:
// The name of the message type, not including its scope.
- const string& name() const;
+ const std::string& name() const;
// The fully-qualified name of the message type, scope delimited by
// periods. For example, message type "Foo" which is declared in package
// "bar" has full name "bar.Foo". If a type "Baz" is nested within
// Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that
// comes after the last '.', use name().
- const string& full_name() const;
+ const std::string& full_name() const;
// Index of this descriptor within the file or containing type's message
// type array.
@@ -245,9 +255,8 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Get options for this message type. These are specified in the .proto file
// by placing lines like "option foo = 1234;" in the message definition.
- // Allowed options are defined by MessageOptions in
- // google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // Allowed options are defined by MessageOptions in descriptor.proto, and any
+ // available extensions of that message.
const MessageOptions& options() const;
// Write the contents of this Descriptor into the given DescriptorProto.
@@ -257,11 +266,11 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Write the contents of this decriptor in a human-readable form. Output
// will be suitable for re-parsing.
- string DebugString() const;
+ std::string DebugString() const;
// Similar to DebugString(), but additionally takes options (e.g.,
// include original user comments in output).
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Returns true if this is a placeholder for an unknown type. This will
// only be the case if this descriptor comes from a DescriptorPool
@@ -280,20 +289,20 @@ class LIBPROTOBUF_EXPORT Descriptor {
// exists.
const FieldDescriptor* FindFieldByNumber(int number) const;
// Looks up a field by name. Returns NULL if no such field exists.
- const FieldDescriptor* FindFieldByName(const string& name) const;
+ const FieldDescriptor* FindFieldByName(const std::string& name) const;
// Looks up a field by lowercased name (as returned by lowercase_name()).
// This lookup may be ambiguous if multiple field names differ only by case,
// in which case the field returned is chosen arbitrarily from the matches.
const FieldDescriptor* FindFieldByLowercaseName(
- const string& lowercase_name) const;
+ const std::string& lowercase_name) const;
// Looks up a field by camel-case name (as returned by camelcase_name()).
// This lookup may be ambiguous if multiple field names differ in a way that
// leads them to have identical camel-case names, in which case the field
// returned is chosen arbitrarily from the matches.
const FieldDescriptor* FindFieldByCamelcaseName(
- const string& camelcase_name) const;
+ const std::string& camelcase_name) const;
// The number of oneofs in this message type.
int oneof_decl_count() const;
@@ -302,7 +311,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
const OneofDescriptor* oneof_decl(int index) const;
// Looks up a oneof by name. Returns NULL if no such oneof exists.
- const OneofDescriptor* FindOneofByName(const string& name) const;
+ const OneofDescriptor* FindOneofByName(const std::string& name) const;
// Nested type stuff -----------------------------------------------
@@ -314,7 +323,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Looks up a nested type by name. Returns NULL if no such nested type
// exists.
- const Descriptor* FindNestedTypeByName(const string& name) const;
+ const Descriptor* FindNestedTypeByName(const std::string& name) const;
// Enum stuff ------------------------------------------------------
@@ -325,11 +334,11 @@ class LIBPROTOBUF_EXPORT Descriptor {
const EnumDescriptor* enum_type(int index) const;
// Looks up an enum type by name. Returns NULL if no such enum type exists.
- const EnumDescriptor* FindEnumTypeByName(const string& name) const;
+ const EnumDescriptor* FindEnumTypeByName(const std::string& name) const;
// Looks up an enum value by name, among all enum types in this message.
// Returns NULL if no such value exists.
- const EnumValueDescriptor* FindEnumValueByName(const string& name) const;
+ const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const;
// Extensions ------------------------------------------------------
@@ -369,15 +378,15 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Looks up a named extension (which extends some *other* message type)
// defined within this message type's scope.
- const FieldDescriptor* FindExtensionByName(const string& name) const;
+ const FieldDescriptor* FindExtensionByName(const std::string& name) const;
// Similar to FindFieldByLowercaseName(), but finds extensions defined within
// this message type's scope.
- const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const;
+ const FieldDescriptor* FindExtensionByLowercaseName(const std::string& name) const;
// Similar to FindFieldByCamelcaseName(), but finds extensions defined within
// this message type's scope.
- const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const;
+ const FieldDescriptor* FindExtensionByCamelcaseName(const std::string& name) const;
// Reserved fields -------------------------------------------------
@@ -404,10 +413,10 @@ class LIBPROTOBUF_EXPORT Descriptor {
int reserved_name_count() const;
// Gets a reserved name by index, where 0 <= index < reserved_name_count().
- const string& reserved_name(int index) const;
+ const std::string& reserved_name(int index) const;
// Returns true if the field name is reserved.
- bool IsReservedName(const string& name) const;
+ bool IsReservedName(const std::string& name) const;
// Source Location ---------------------------------------------------
@@ -420,10 +429,11 @@ class LIBPROTOBUF_EXPORT Descriptor {
typedef MessageOptions OptionsType;
// Allows tests to test CopyTo(proto, true).
- friend class ::google::protobuf::descriptor_unittest::DescriptorTest;
+ friend class descriptor_unittest::DescriptorTest;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// Fill the json_name field of FieldDescriptorProto.
void CopyJsonNameTo(DescriptorProto* proto) const;
@@ -432,7 +442,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
// correct depth. Takes |options| to control debug-string options, and
// |include_opening_clause| to indicate whether the "message ... " part of the
// clause has already been generated (this varies depending on context).
- void DebugString(int depth, string *contents,
+ void DebugString(int depth, std::string *contents,
const DebugStringOptions& options,
bool include_opening_clause) const;
@@ -440,8 +450,8 @@ class LIBPROTOBUF_EXPORT Descriptor {
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
const FileDescriptor* file_;
const Descriptor* containing_type_;
const MessageOptions* options_;
@@ -454,7 +464,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
ExtensionRange* extension_ranges_;
FieldDescriptor* extensions_;
ReservedRange* reserved_ranges_;
- const string** reserved_names_;
+ const std::string** reserved_names_;
int field_count_;
int oneof_decl_count_;
@@ -499,7 +509,7 @@ class LIBPROTOBUF_EXPORT Descriptor {
// Reflection::FindKnownExtensionByName() or
// Reflection::FindKnownExtensionByNumber().
// Use DescriptorPool to construct your own descriptors.
-class LIBPROTOBUF_EXPORT FieldDescriptor {
+class PROTOBUF_EXPORT FieldDescriptor {
public:
// Identifies a field type. 0 is reserved for errors. The order is weird
// for historical reasons. Types 12 and up are new in proto2.
@@ -572,9 +582,9 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// Users may not declare fields that use reserved numbers.
static const int kLastReservedNumber = 19999;
- const string& name() const; // Name of this field within the message.
- const string& full_name() const; // Fully-qualified name of the field.
- const string& json_name() const; // JSON name of this field.
+ const std::string& name() const; // Name of this field within the message.
+ const std::string& full_name() const; // Fully-qualified name of the field.
+ const std::string& json_name() const; // JSON name of this field.
const FileDescriptor* file() const;// File in which this field was defined.
bool is_extension() const; // Is this an extension field?
int number() const; // Declared tag number.
@@ -585,7 +595,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// field names should be lowercased anyway according to the protobuf style
// guide, so this only makes a difference when dealing with old .proto files
// which do not follow the guide.)
- const string& lowercase_name() const;
+ const std::string& lowercase_name() const;
// Same as name() except converted to camel-case. In this conversion, any
// time an underscore appears in the name, it is removed and the next
@@ -596,7 +606,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// fooBar -> fooBar
// This (and especially the FindFieldByCamelcaseName() method) can be useful
// when parsing formats which prefer to use camel-case naming style.
- const string& camelcase_name() const;
+ const std::string& camelcase_name() const;
Type type() const; // Declared type of this field.
const char* type_name() const; // Name of the declared type.
@@ -653,7 +663,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
const EnumValueDescriptor* default_value_enum() const;
// Get the field default value if cpp_type() == CPPTYPE_STRING. If no
// explicit default was defined, the default is the empty string.
- const string& default_value_string() const;
+ const std::string& default_value_string() const;
// The Descriptor for the message of which this is a field. For extensions,
// this is the extended type. Never NULL.
@@ -683,19 +693,18 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// Get the FieldOptions for this field. This includes things listed in
// square brackets after the field definition. E.g., the field:
// optional string text = 1 [ctype=CORD];
- // has the "ctype" option set. Allowed options are defined by FieldOptions
- // in google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // has the "ctype" option set. Allowed options are defined by FieldOptions in
+ // descriptor.proto, and any available extensions of that message.
const FieldOptions& options() const;
// See Descriptor::CopyTo().
void CopyTo(FieldDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Helper method to get the CppType for a particular Type.
static CppType TypeToCppType(Type type);
@@ -720,7 +729,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
typedef FieldOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// Fill the json_name field of FieldDescriptorProto.
void CopyJsonNameTo(FieldDescriptorProto* proto) const;
@@ -728,15 +738,15 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// See Descriptor::DebugString().
enum PrintLabelFlag { PRINT_LABEL, OMIT_LABEL };
void DebugString(int depth, PrintLabelFlag print_label_flag,
- string* contents, const DebugStringOptions& options) const;
+ std::string* contents, const DebugStringOptions& options) const;
// formats the default value appropriately and returns it as a string.
// Must have a default value to call this. If quote_string_type is true, then
// types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped.
- string DefaultValueAsString(bool quote_string_type) const;
+ std::string DefaultValueAsString(bool quote_string_type) const;
// Helper function that returns the field type name for DebugString.
- string FieldTypeNameDebugString() const;
+ std::string FieldTypeNameDebugString() const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
@@ -745,15 +755,15 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// 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_;
+ const std::string* name_;
+ const std::string* full_name_;
+ const std::string* lowercase_name_;
+ const std::string* camelcase_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 std::string* json_name_;
const FileDescriptor* file_;
- GoogleOnceDynamic* type_once_;
+ internal::once_flag* type_once_;
static void TypeOnceInit(const FieldDescriptor* to_init);
void InternalTypeOnceInit() const;
mutable Type type_;
@@ -771,8 +781,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
mutable const Descriptor* message_type_;
mutable const EnumDescriptor* enum_type_;
const FieldOptions* options_;
- const string* type_name_;
- const string* default_value_enum_name_;
+ const std::string* type_name_;
+ const std::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.
@@ -787,7 +797,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
bool default_value_bool_;
mutable const EnumValueDescriptor* default_value_enum_;
- const string* default_value_string_;
+ const std::string* default_value_string_;
};
static const CppType kTypeToCppTypeMap[MAX_TYPE + 1];
@@ -809,10 +819,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// Describes a oneof defined in a message type.
-class LIBPROTOBUF_EXPORT OneofDescriptor {
+class PROTOBUF_EXPORT OneofDescriptor {
public:
- const string& name() const; // Name of this oneof.
- const string& full_name() const; // Fully-qualified name of the oneof.
+ const std::string& name() const; // Name of this oneof.
+ const std::string& full_name() const; // Fully-qualified name of the oneof.
// Index of this oneof within the message's oneof array.
int index() const;
@@ -834,10 +844,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptor {
void CopyTo(OneofDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Source Location ---------------------------------------------------
@@ -850,18 +860,19 @@ class LIBPROTOBUF_EXPORT OneofDescriptor {
typedef OneofOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// See Descriptor::DebugString().
- void DebugString(int depth, string* contents,
+ void DebugString(int depth, std::string* contents,
const DebugStringOptions& options) const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
const Descriptor* containing_type_;
bool is_extendable_;
int field_count_;
@@ -882,13 +893,13 @@ class LIBPROTOBUF_EXPORT OneofDescriptor {
// Describes an enum type defined in a .proto file. To get the EnumDescriptor
// for a generated enum type, call TypeName_descriptor(). Use DescriptorPool
// to construct your own descriptors.
-class LIBPROTOBUF_EXPORT EnumDescriptor {
+class PROTOBUF_EXPORT EnumDescriptor {
public:
// The name of this enum type in the containing scope.
- const string& name() const;
+ const std::string& name() const;
// The fully-qualified name of the enum type, scope delimited by periods.
- const string& full_name() const;
+ const std::string& full_name() const;
// Index of this enum within the file or containing message's enum array.
int index() const;
@@ -904,7 +915,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
const EnumValueDescriptor* value(int index) const;
// Looks up a value by name. Returns NULL if no such value exists.
- const EnumValueDescriptor* FindValueByName(const string& name) const;
+ const EnumValueDescriptor* FindValueByName(const std::string& name) const;
// Looks up a value by number. Returns NULL if no such value exists. If
// multiple values have this number, the first one defined is returned.
const EnumValueDescriptor* FindValueByNumber(int number) const;
@@ -915,18 +926,18 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
// Get options for this enum type. These are specified in the .proto file by
// placing lines like "option foo = 1234;" in the enum definition. Allowed
- // options are defined by EnumOptions in google/protobuf/descriptor.proto,
- // and any available extensions of that message.
+ // options are defined by EnumOptions in descriptor.proto, and any available
+ // extensions of that message.
const EnumOptions& options() const;
// See Descriptor::CopyTo().
void CopyTo(EnumDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::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
@@ -959,10 +970,10 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
int reserved_name_count() const;
// Gets a reserved name by index, where 0 <= index < reserved_name_count().
- const string& reserved_name(int index) const;
+ const std::string& reserved_name(int index) const;
// Returns true if the field name is reserved.
- bool IsReservedName(const string& name) const;
+ bool IsReservedName(const std::string& name) const;
// Source Location ---------------------------------------------------
@@ -975,7 +986,8 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
typedef EnumOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// Looks up a value by number. If the value does not exist, dynamically
// creates a new EnumValueDescriptor for that value, assuming that it was
@@ -990,15 +1002,15 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
// See Descriptor::DebugString().
- void DebugString(int depth, string *contents,
+ void DebugString(int depth, std::string *contents,
const DebugStringOptions& options) const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
const FileDescriptor* file_;
const Descriptor* containing_type_;
const EnumOptions* options_;
@@ -1014,7 +1026,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
int reserved_range_count_;
int reserved_name_count_;
EnumDescriptor::ReservedRange* reserved_ranges_;
- const string** reserved_names_;
+ const std::string** reserved_names_;
// IMPORTANT: If you add a new field, make sure to search for all instances
// of Allocate<EnumDescriptor>() and AllocateArray<EnumDescriptor>() in
@@ -1037,9 +1049,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptor {
// for its type, then use EnumDescriptor::FindValueByName() or
// EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct
// your own descriptors.
-class LIBPROTOBUF_EXPORT EnumValueDescriptor {
+class PROTOBUF_EXPORT EnumValueDescriptor {
public:
- const string& name() const; // Name of this enum constant.
+ const std::string& name() const; // Name of this enum constant.
int index() const; // Index within the enums's Descriptor.
int number() const; // Numeric value of this enum constant.
@@ -1048,28 +1060,27 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor {
// "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT
// "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform
// with C++ scoping rules for enums.
- const string& full_name() const;
+ const std::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;
- // Get options for this enum value. These are specified in the .proto file
- // by adding text like "[foo = 1234]" after an enum value definition.
- // Allowed options are defined by EnumValueOptions in
- // google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // Get options for this enum value. These are specified in the .proto file by
+ // adding text like "[foo = 1234]" after an enum value definition. Allowed
+ // options are defined by EnumValueOptions in descriptor.proto, and any
+ // available extensions of that message.
const EnumValueOptions& options() const;
// See Descriptor::CopyTo().
void CopyTo(EnumValueDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Source Location ---------------------------------------------------
@@ -1083,18 +1094,19 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor {
typedef EnumValueOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// See Descriptor::DebugString().
- void DebugString(int depth, string *contents,
+ void DebugString(int depth, std::string *contents,
const DebugStringOptions& options) const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
int number_;
const EnumDescriptor* type_;
const EnumValueOptions* options_;
@@ -1115,12 +1127,12 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor {
// call Service::GetDescriptor(). Generated service classes also have a
// static method called descriptor() which returns the type's
// ServiceDescriptor. Use DescriptorPool to construct your own descriptors.
-class LIBPROTOBUF_EXPORT ServiceDescriptor {
+class PROTOBUF_EXPORT ServiceDescriptor {
public:
// The name of the service, not including its containing scope.
- const string& name() const;
+ const std::string& name() const;
// The fully-qualified name of the service, scope delimited by periods.
- const string& full_name() const;
+ const std::string& full_name() const;
// Index of this service within the file's services array.
int index() const;
@@ -1129,9 +1141,8 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
// Get options for this service type. These are specified in the .proto file
// by placing lines like "option foo = 1234;" in the service definition.
- // Allowed options are defined by ServiceOptions in
- // google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // Allowed options are defined by ServiceOptions in descriptor.proto, and any
+ // available extensions of that message.
const ServiceOptions& options() const;
// The number of methods this service defines.
@@ -1141,15 +1152,15 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
const MethodDescriptor* method(int index) const;
// Look up a MethodDescriptor by name.
- const MethodDescriptor* FindMethodByName(const string& name) const;
+ const MethodDescriptor* FindMethodByName(const std::string& name) const;
// See Descriptor::CopyTo().
void CopyTo(ServiceDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Source Location ---------------------------------------------------
@@ -1163,17 +1174,18 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
typedef ServiceOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// See Descriptor::DebugString().
- void DebugString(string *contents, const DebugStringOptions& options) const;
+ void DebugString(std::string *contents, const DebugStringOptions& options) const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
const FileDescriptor* file_;
const ServiceOptions* options_;
MethodDescriptor* methods_;
@@ -1195,12 +1207,12 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor {
// a service, first get its ServiceDescriptor, then call
// ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your
// own descriptors.
-class LIBPROTOBUF_EXPORT MethodDescriptor {
+class PROTOBUF_EXPORT MethodDescriptor {
public:
// Name of this method, not including containing scope.
- const string& name() const;
+ const std::string& name() const;
// The fully-qualified name of the method, scope delimited by periods.
- const string& full_name() const;
+ const std::string& full_name() const;
// Index within the service's Descriptor.
int index() const;
@@ -1222,18 +1234,17 @@ class LIBPROTOBUF_EXPORT MethodDescriptor {
// Get options for this method. These are specified in the .proto file by
// placing lines like "option foo = 1234;" in curly-braces after a method
// declaration. Allowed options are defined by MethodOptions in
- // google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // descriptor.proto, and any available extensions of that message.
const MethodOptions& options() const;
// See Descriptor::CopyTo().
void CopyTo(MethodDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Source Location ---------------------------------------------------
@@ -1247,18 +1258,19 @@ class LIBPROTOBUF_EXPORT MethodDescriptor {
typedef MethodOptions OptionsType;
// Allows access to GetLocationPath for annotations.
- friend class ::google::protobuf::io::Printer;
+ friend class io::Printer;
+ friend class compiler::cpp::Formatter;
// See Descriptor::DebugString().
- void DebugString(int depth, string *contents,
+ void DebugString(int depth, std::string *contents,
const DebugStringOptions& options) const;
// Walks up the descriptor tree to generate the source location path
// to this descriptor from the file root.
void GetLocationPath(std::vector<int>* output) const;
- const string* name_;
- const string* full_name_;
+ const std::string* name_;
+ const std::string* full_name_;
const ServiceDescriptor* service_;
mutable internal::LazyDescriptor input_type_;
mutable internal::LazyDescriptor output_type_;
@@ -1280,14 +1292,14 @@ class LIBPROTOBUF_EXPORT MethodDescriptor {
// Describes a whole .proto file. To get the FileDescriptor for a compiled-in
// file, get the descriptor for something defined in that file and call
// descriptor->file(). Use DescriptorPool to construct your own descriptors.
-class LIBPROTOBUF_EXPORT FileDescriptor {
+class PROTOBUF_EXPORT FileDescriptor {
public:
// The filename, relative to the source tree.
- // e.g. "google/protobuf/descriptor.proto"
- const string& name() const;
+ // e.g. "foo/bar/baz.proto"
+ const std::string& name() const;
// The package, e.g. "google.protobuf.compiler".
- const string& package() const;
+ const std::string& package() const;
// The DescriptorPool in which this FileDescriptor and all its contents were
// allocated. Never NULL.
@@ -1345,8 +1357,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
// Get options for this file. These are specified in the .proto file by
// placing lines like "option foo = 1234;" at the top level, outside of any
// other definitions. Allowed options are defined by FileOptions in
- // google/protobuf/descriptor.proto, and any available extensions of that
- // message.
+ // descriptor.proto, and any available extensions of that message.
const FileOptions& options() const;
// Syntax of this file.
@@ -1359,22 +1370,22 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
static const char* SyntaxName(Syntax syntax);
// Find a top-level message type by name. Returns NULL if not found.
- const Descriptor* FindMessageTypeByName(const string& name) const;
+ const Descriptor* FindMessageTypeByName(const std::string& name) const;
// Find a top-level enum type by name. Returns NULL if not found.
- const EnumDescriptor* FindEnumTypeByName(const string& name) const;
+ const EnumDescriptor* FindEnumTypeByName(const std::string& name) const;
// Find an enum value defined in any top-level enum by name. Returns NULL if
// not found.
- const EnumValueDescriptor* FindEnumValueByName(const string& name) const;
+ const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const;
// Find a service definition by name. Returns NULL if not found.
- const ServiceDescriptor* FindServiceByName(const string& name) const;
+ const ServiceDescriptor* FindServiceByName(const std::string& name) const;
// Find a top-level extension definition by name. Returns NULL if not found.
- const FieldDescriptor* FindExtensionByName(const string& name) const;
+ const FieldDescriptor* FindExtensionByName(const std::string& name) const;
// Similar to FindExtensionByName(), but searches by lowercased-name. See
// Descriptor::FindFieldByLowercaseName().
- const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const;
+ const FieldDescriptor* FindExtensionByLowercaseName(const std::string& name) const;
// Similar to FindExtensionByName(), but searches by camelcased-name. See
// Descriptor::FindFieldByCamelcaseName().
- const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const;
+ const FieldDescriptor* FindExtensionByCamelcaseName(const std::string& name) const;
// See Descriptor::CopyTo().
// Notes:
@@ -1389,10 +1400,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
void CopyJsonNameTo(FileDescriptorProto* proto) const;
// See Descriptor::DebugString().
- string DebugString() const;
+ std::string DebugString() const;
// See Descriptor::DebugStringWithOptions().
- string DebugStringWithOptions(const DebugStringOptions& options) const;
+ std::string DebugStringWithOptions(const DebugStringOptions& options) const;
// Returns true if this is a placeholder for an unknown file. This will
// only be the case if this descriptor comes from a DescriptorPool
@@ -1414,10 +1425,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
private:
typedef FileOptions OptionsType;
- const string* name_;
- const string* package_;
+ const std::string* name_;
+ const std::string* package_;
const DescriptorPool* pool_;
- GoogleOnceDynamic* dependencies_once_;
+ internal::once_flag* dependencies_once_;
static void DependenciesOnceInit(const FileDescriptor* to_init);
void InternalDependenciesOnceInit() const;
@@ -1438,7 +1449,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
bool finished_building_;
mutable const FileDescriptor** dependencies_;
- const string** dependencies_names_;
+ const std::string** dependencies_names_;
int* public_dependencies_;
int* weak_dependencies_;
Descriptor* message_types_;
@@ -1495,7 +1506,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor {
//
// You can also search for descriptors within a DescriptorPool by name, and
// extensions by number.
-class LIBPROTOBUF_EXPORT DescriptorPool {
+class PROTOBUF_EXPORT DescriptorPool {
public:
// Create a normal, empty DescriptorPool.
DescriptorPool();
@@ -1537,28 +1548,28 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// Find a FileDescriptor in the pool by file name. Returns NULL if not
// found.
- const FileDescriptor* FindFileByName(const string& name) const;
+ const FileDescriptor* FindFileByName(const std::string& name) const;
// Find the FileDescriptor in the pool which defines the given symbol.
// If any of the Find*ByName() methods below would succeed, then this is
// equivalent to calling that method and calling the result's file() method.
// Otherwise this returns NULL.
const FileDescriptor* FindFileContainingSymbol(
- const string& symbol_name) const;
+ const std::string& symbol_name) const;
// Looking up descriptors ------------------------------------------
// These find descriptors by fully-qualified name. These will find both
// top-level descriptors and nested descriptors. They return NULL if not
// found.
- const Descriptor* FindMessageTypeByName(const string& name) const;
- const FieldDescriptor* FindFieldByName(const string& name) const;
- const FieldDescriptor* FindExtensionByName(const string& name) const;
- const OneofDescriptor* FindOneofByName(const string& name) const;
- const EnumDescriptor* FindEnumTypeByName(const string& name) const;
- const EnumValueDescriptor* FindEnumValueByName(const string& name) const;
- const ServiceDescriptor* FindServiceByName(const string& name) const;
- const MethodDescriptor* FindMethodByName(const string& name) const;
+ const Descriptor* FindMessageTypeByName(const std::string& name) const;
+ const FieldDescriptor* FindFieldByName(const std::string& name) const;
+ const FieldDescriptor* FindExtensionByName(const std::string& name) const;
+ const OneofDescriptor* FindOneofByName(const std::string& name) const;
+ const EnumDescriptor* FindEnumTypeByName(const std::string& name) const;
+ const EnumValueDescriptor* FindEnumValueByName(const std::string& name) const;
+ const ServiceDescriptor* FindServiceByName(const std::string& name) const;
+ const MethodDescriptor* FindMethodByName(const std::string& name) const;
// Finds an extension of the given type by number. The extendee must be
// a member of this DescriptorPool or one of its underlays.
@@ -1578,7 +1589,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// When converting a FileDescriptorProto to a FileDescriptor, various
// errors might be detected in the input. The caller may handle these
// programmatically by implementing an ErrorCollector.
- class LIBPROTOBUF_EXPORT ErrorCollector {
+ class PROTOBUF_EXPORT ErrorCollector {
public:
inline ErrorCollector() {}
virtual ~ErrorCollector();
@@ -1602,21 +1613,21 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// Reports an error in the FileDescriptorProto. Use this function if the
// problem occurred should interrupt building the FileDescriptorProto.
virtual void AddError(
- const string& filename, // File name in which the error occurred.
- const string& element_name, // Full name of the erroneous element.
+ const std::string& filename, // File name in which the error occurred.
+ const std::string& element_name, // Full name of the erroneous element.
const Message* descriptor, // Descriptor of the erroneous element.
ErrorLocation location, // One of the location constants, above.
- const string& message // Human-readable error message.
+ const std::string& message // Human-readable error message.
) = 0;
// Reports a warning in the FileDescriptorProto. Use this function if the
// problem occurred should NOT interrupt building the FileDescriptorProto.
virtual void AddWarning(
- const string& /*filename*/, // File name in which the error occurred.
- const string& /*element_name*/, // Full name of the erroneous element.
+ const std::string& /*filename*/, // File name in which the error occurred.
+ const std::string& /*element_name*/, // Full name of the erroneous element.
const Message* /*descriptor*/, // Descriptor of the erroneous element.
ErrorLocation /*location*/, // One of the location constants, above.
- const string& /*message*/ // Human-readable error message.
+ const std::string& /*message*/ // Human-readable error message.
) {}
private:
@@ -1729,12 +1740,12 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// For internal (unit test) use only: Returns true if a FileDescriptor has
// been constructed for the given file, false otherwise. Useful for testing
// lazy descriptor initialization behavior.
- bool InternalIsFileLoaded(const string& filename) const;
+ bool InternalIsFileLoaded(const std::string& filename) const;
// Add a file to unused_import_track_files_. DescriptorBuilder will log
// warnings for those files if there is any unused import.
- void AddUnusedImportTrackFile(const string& file_name);
+ void AddUnusedImportTrackFile(const std::string& file_name);
void ClearUnusedImportTrackFiles();
private:
@@ -1752,14 +1763,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// Return true if the given name is a sub-symbol of any non-package
// descriptor that already exists in the descriptor pool. (The full
// definition of such types is already known.)
- bool IsSubSymbolOfBuiltType(const string& name) const;
+ bool IsSubSymbolOfBuiltType(const std::string& name) const;
// Tries to find something in the fallback database and link in the
// corresponding proto file. Returns true if successful, in which case
// the caller should search for the thing again. These are declared
// const because they are called by (semantically) const methods.
- bool TryFindFileInFallbackDatabase(const string& name) const;
- bool TryFindSymbolInFallbackDatabase(const string& name) const;
+ bool TryFindFileInFallbackDatabase(const std::string& name) const;
+ bool TryFindSymbolInFallbackDatabase(const std::string& name) const;
bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type,
int field_number) const;
@@ -1774,11 +1785,11 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// 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;
+ Symbol CrossLinkOnDemandHelper(const std::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;
+ FileDescriptor* NewPlaceholderFile(const std::string& name) const;
+ FileDescriptor* NewPlaceholderFileWithMutexHeld(const std::string& name) const;
enum PlaceholderType {
PLACEHOLDER_MESSAGE,
@@ -1786,14 +1797,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
PLACEHOLDER_EXTENDABLE_MESSAGE
};
// Create a placeholder Descriptor of the specified name
- Symbol NewPlaceholder(const string& name,
+ Symbol NewPlaceholder(const std::string& name,
PlaceholderType placeholder_type) const;
- Symbol NewPlaceholderWithMutexHeld(const string& name,
+ Symbol NewPlaceholderWithMutexHeld(const std::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_;
+ internal::WrappedMutex* mutex_;
// See constructor.
DescriptorDatabase* fallback_database_;
@@ -1810,7 +1821,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
bool allow_unknown_;
bool enforce_weak_;
bool disallow_enforce_utf8_;
- std::set<string> unused_import_track_files_;
+ std::set<std::string> unused_import_track_files_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool);
};
@@ -1824,7 +1835,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool {
// Strings fields are stored as pointers but returned as const references.
#define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \
- inline const string& CLASS::FIELD() const { return *FIELD##_; }
+ inline const std::string& CLASS::FIELD() const { return *FIELD##_; }
// Arrays take an index parameter, obviously.
#define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \
@@ -1964,7 +1975,7 @@ inline bool Descriptor::IsReservedNumber(int number) const {
return FindReservedRangeContainingNumber(number) != NULL;
}
-inline bool Descriptor::IsReservedName(const string& name) const {
+inline bool Descriptor::IsReservedName(const std::string& name) const {
for (int i = 0; i < reserved_name_count(); i++) {
if (name == reserved_name(i)) {
return true;
@@ -1975,7 +1986,7 @@ inline bool Descriptor::IsReservedName(const string& name) const {
// 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& Descriptor::reserved_name(int index) const {
+inline const std::string& Descriptor::reserved_name(int index) const {
return *reserved_names_[index];
}
@@ -1983,7 +1994,7 @@ inline bool EnumDescriptor::IsReservedNumber(int number) const {
return FindReservedRangeContainingNumber(number) != NULL;
}
-inline bool EnumDescriptor::IsReservedName(const string& name) const {
+inline bool EnumDescriptor::IsReservedName(const std::string& name) const {
for (int i = 0; i < reserved_name_count(); i++) {
if (name == reserved_name(i)) {
return true;
@@ -1994,13 +2005,13 @@ inline bool EnumDescriptor::IsReservedName(const string& name) const {
// 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 {
+inline const std::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);
+ internal::call_once(*type_once_, &FieldDescriptor::TypeOnceInit, this);
}
return type_;
}
@@ -2133,6 +2144,8 @@ inline const FieldDescriptor* OneofDescriptor::field(int index) const {
}
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_DESCRIPTOR_H__
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc
index 59b04aba..f85ed136 100644
--- a/src/google/protobuf/descriptor.pb.cc
+++ b/src/google/protobuf/descriptor.pb.cc
@@ -6,187 +6,154 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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 protobuf_google_2fprotobuf_2fdescriptor_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto;
-} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
+#include <google/protobuf/port_def.inc>
+
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto;
namespace google {
namespace protobuf {
class FileDescriptorSetDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet> _instance;
} _FileDescriptorSet_default_instance_;
class FileDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto> _instance;
} _FileDescriptorProto_default_instance_;
class DescriptorProto_ExtensionRangeDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange> _instance;
} _DescriptorProto_ExtensionRange_default_instance_;
class DescriptorProto_ReservedRangeDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange> _instance;
} _DescriptorProto_ReservedRange_default_instance_;
class DescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto> _instance;
} _DescriptorProto_default_instance_;
class ExtensionRangeOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<ExtensionRangeOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<ExtensionRangeOptions> _instance;
} _ExtensionRangeOptions_default_instance_;
class FieldDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto> _instance;
} _FieldDescriptorProto_default_instance_;
class OneofDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto> _instance;
} _OneofDescriptorProto_default_instance_;
class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto_EnumReservedRange>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto_EnumReservedRange> _instance;
} _EnumDescriptorProto_EnumReservedRange_default_instance_;
class EnumDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto> _instance;
} _EnumDescriptorProto_default_instance_;
class EnumValueDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto> _instance;
} _EnumValueDescriptorProto_default_instance_;
class ServiceDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto> _instance;
} _ServiceDescriptorProto_default_instance_;
class MethodDescriptorProtoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto> _instance;
} _MethodDescriptorProto_default_instance_;
class FileOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FileOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FileOptions> _instance;
} _FileOptions_default_instance_;
class MessageOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<MessageOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<MessageOptions> _instance;
} _MessageOptions_default_instance_;
class FieldOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FieldOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldOptions> _instance;
} _FieldOptions_default_instance_;
class OneofOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<OneofOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<OneofOptions> _instance;
} _OneofOptions_default_instance_;
class EnumOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumOptions> _instance;
} _EnumOptions_default_instance_;
class EnumValueOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions> _instance;
} _EnumValueOptions_default_instance_;
class ServiceOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions> _instance;
} _ServiceOptions_default_instance_;
class MethodOptionsDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<MethodOptions>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<MethodOptions> _instance;
} _MethodOptions_default_instance_;
class UninterpretedOption_NamePartDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart> _instance;
} _UninterpretedOption_NamePart_default_instance_;
class UninterpretedOptionDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption> _instance;
} _UninterpretedOption_default_instance_;
class SourceCodeInfo_LocationDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location> _instance;
} _SourceCodeInfo_Location_default_instance_;
class SourceCodeInfoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo> _instance;
} _SourceCodeInfo_default_instance_;
class GeneratedCodeInfo_AnnotationDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation> _instance;
} _GeneratedCodeInfo_Annotation_default_instance_;
class GeneratedCodeInfoDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo> _instance;
} _GeneratedCodeInfo_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto {
-static void InitDefaultsFileDescriptorSet() {
+static void InitDefaultsFileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -197,11 +164,11 @@ static void InitDefaultsFileDescriptorSet() {
::google::protobuf::FileDescriptorSet::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsFileDescriptorProto() {
+static void InitDefaultsFileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -212,16 +179,16 @@ static void InitDefaultsFileDescriptorProto() {
::google::protobuf::FileDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsFileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsDescriptorProto_ExtensionRange() {
+static void InitDefaultsDescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -232,11 +199,11 @@ static void InitDefaultsDescriptorProto_ExtensionRange() {
::google::protobuf::DescriptorProto_ExtensionRange::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsDescriptorProto_ReservedRange() {
+static void InitDefaultsDescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -247,10 +214,10 @@ static void InitDefaultsDescriptorProto_ReservedRange() {
::google::protobuf::DescriptorProto_ReservedRange::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}};
-static void InitDefaultsDescriptorProto() {
+static void InitDefaultsDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -261,16 +228,16 @@ static void InitDefaultsDescriptorProto() {
::google::protobuf::DescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<6> scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsExtensionRangeOptions() {
+static void InitDefaultsExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -281,11 +248,11 @@ static void InitDefaultsExtensionRangeOptions() {
::google::protobuf::ExtensionRangeOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsFieldDescriptorProto() {
+static void InitDefaultsFieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -296,11 +263,11 @@ static void InitDefaultsFieldDescriptorProto() {
::google::protobuf::FieldDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsOneofDescriptorProto() {
+static void InitDefaultsOneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -311,11 +278,11 @@ static void InitDefaultsOneofDescriptorProto() {
::google::protobuf::OneofDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsEnumDescriptorProto_EnumReservedRange() {
+static void InitDefaultsEnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -326,10 +293,10 @@ static void InitDefaultsEnumDescriptorProto_EnumReservedRange() {
::google::protobuf::EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto}, {}};
-static void InitDefaultsEnumDescriptorProto() {
+static void InitDefaultsEnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -340,13 +307,13 @@ static void InitDefaultsEnumDescriptorProto() {
::google::protobuf::EnumDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsEnumValueDescriptorProto() {
+static void InitDefaultsEnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -357,11 +324,11 @@ static void InitDefaultsEnumValueDescriptorProto() {
::google::protobuf::EnumValueDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsServiceDescriptorProto() {
+static void InitDefaultsServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -372,12 +339,12 @@ static void InitDefaultsServiceDescriptorProto() {
::google::protobuf::ServiceDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base,
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base,
+ &scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsMethodDescriptorProto() {
+static void InitDefaultsMethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -388,11 +355,11 @@ static void InitDefaultsMethodDescriptorProto() {
::google::protobuf::MethodDescriptorProto::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsFileOptions() {
+static void InitDefaultsFileOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -403,11 +370,11 @@ static void InitDefaultsFileOptions() {
::google::protobuf::FileOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFileOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsMessageOptions() {
+static void InitDefaultsMessageOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -418,11 +385,11 @@ static void InitDefaultsMessageOptions() {
::google::protobuf::MessageOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMessageOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsFieldOptions() {
+static void InitDefaultsFieldOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -433,11 +400,11 @@ static void InitDefaultsFieldOptions() {
::google::protobuf::FieldOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFieldOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsOneofOptions() {
+static void InitDefaultsOneofOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -448,11 +415,11 @@ static void InitDefaultsOneofOptions() {
::google::protobuf::OneofOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOneofOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsEnumOptions() {
+static void InitDefaultsEnumOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -463,11 +430,11 @@ static void InitDefaultsEnumOptions() {
::google::protobuf::EnumOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsEnumValueOptions() {
+static void InitDefaultsEnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -478,11 +445,11 @@ static void InitDefaultsEnumValueOptions() {
::google::protobuf::EnumValueOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsServiceOptions() {
+static void InitDefaultsServiceOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -493,11 +460,11 @@ static void InitDefaultsServiceOptions() {
::google::protobuf::ServiceOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsServiceOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsMethodOptions() {
+static void InitDefaultsMethodOptions_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -508,11 +475,11 @@ static void InitDefaultsMethodOptions() {
::google::protobuf::MethodOptions::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethodOptions_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsUninterpretedOption_NamePart() {
+static void InitDefaultsUninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -523,10 +490,10 @@ static void InitDefaultsUninterpretedOption_NamePart() {
::google::protobuf::UninterpretedOption_NamePart::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto}, {}};
-static void InitDefaultsUninterpretedOption() {
+static void InitDefaultsUninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -537,11 +504,11 @@ static void InitDefaultsUninterpretedOption() {
::google::protobuf::UninterpretedOption::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsUninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsSourceCodeInfo_Location() {
+static void InitDefaultsSourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -552,10 +519,10 @@ static void InitDefaultsSourceCodeInfo_Location() {
::google::protobuf::SourceCodeInfo_Location::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto}, {}};
-static void InitDefaultsSourceCodeInfo() {
+static void InitDefaultsSourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -566,11 +533,11 @@ static void InitDefaultsSourceCodeInfo() {
::google::protobuf::SourceCodeInfo::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsSourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base,}};
-static void InitDefaultsGeneratedCodeInfo_Annotation() {
+static void InitDefaultsGeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -581,10 +548,10 @@ static void InitDefaultsGeneratedCodeInfo_Annotation() {
::google::protobuf::GeneratedCodeInfo_Annotation::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsGeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto}, {}};
-static void InitDefaultsGeneratedCodeInfo() {
+static void InitDefaultsGeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -595,68 +562,69 @@ static void InitDefaultsGeneratedCodeInfo() {
::google::protobuf::GeneratedCodeInfo::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo}, {
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base,}};
-
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorSet.base);
- ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange.base);
- ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ReservedRange.base);
- ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_ExtensionRangeOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_FieldDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_OneofDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_EnumReservedRange.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumValueDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_ServiceDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_MethodDescriptorProto.base);
- ::google::protobuf::internal::InitSCC(&scc_info_FileOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_MessageOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_FieldOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_OneofOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumValueOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_ServiceOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_MethodOptions.base);
- ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_NamePart.base);
- ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption.base);
- ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_Location.base);
- ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo.base);
- ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation.base);
- ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo.base);
-}
-
-::google::protobuf::Metadata file_level_metadata[27];
-const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[6];
-
-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_),
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsGeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto}, {
+ &scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base,}};
+
+void InitDefaults_google_2fprotobuf_2fdescriptor_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
+}
+
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[27];
+const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[6];
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto = nullptr;
+
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorSet, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, package_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, dependency_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, public_dependency_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, weak_dependency_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, message_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, enum_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, service_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, extension_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, source_code_info_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileDescriptorProto, syntax_),
0,
1,
~0u,
@@ -669,41 +637,41 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, start_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ExtensionRange, end_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto_ReservedRange, start_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, field_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, nested_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, enum_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, extension_range_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, oneof_decl_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_range_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DescriptorProto, reserved_name_),
0,
~0u,
~0u,
@@ -714,28 +682,28 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ExtensionRangeOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, number_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, label_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, type_name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, extendee_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, default_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, oneof_index_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, json_name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldDescriptorProto, options_),
0,
6,
8,
@@ -746,104 +714,104 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofDescriptorProto, name_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto_EnumReservedRange, start_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumDescriptorProto, reserved_range_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueDescriptorProto, number_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceDescriptorProto, method_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, input_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, output_type_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodDescriptorProto, client_streaming_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, _internal_metadata_),
+ PROTOBUF_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, php_metadata_namespace_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_package_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_outer_classname_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_multiple_files_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_generate_equals_and_hash_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_string_check_utf8_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, optimize_for_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, go_package_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, cc_generic_services_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, java_generic_services_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, py_generic_services_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_generic_services_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, deprecated_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, cc_enable_arenas_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, objc_class_prefix_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, csharp_namespace_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, swift_prefix_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_class_prefix_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_namespace_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, php_metadata_namespace_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, ruby_package_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FileOptions, uninterpreted_option_),
0,
1,
10,
@@ -865,33 +833,33 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
8,
9,
~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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, message_set_wire_format_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, no_standard_descriptor_accessor_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, deprecated_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MessageOptions, map_entry_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, ctype_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, packed_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, jstype_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, lazy_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, deprecated_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, weak_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldOptions, uninterpreted_option_),
0,
1,
5,
@@ -899,74 +867,74 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::OneofOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, allow_alias_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumOptions, deprecated_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValueOptions, deprecated_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ServiceOptions, deprecated_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, _has_bits_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, deprecated_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::MethodOptions, idempotency_level_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption_NamePart, name_part_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, identifier_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, positive_int_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, negative_int_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, double_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, string_value_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UninterpretedOption, aggregate_value_),
~0u,
0,
3,
@@ -974,50 +942,50 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, path_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, span_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, leading_comments_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo_Location, trailing_comments_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceCodeInfo, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, path_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, source_file_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo_Annotation, begin_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::GeneratedCodeInfo, annotation_),
~0u,
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 6, sizeof(::google::protobuf::FileDescriptorSet)},
{ 7, 24, sizeof(::google::protobuf::FileDescriptorProto)},
{ 36, 44, sizeof(::google::protobuf::DescriptorProto_ExtensionRange)},
@@ -1077,201 +1045,183 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_GeneratedCodeInfo_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/descriptor.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, file_level_enum_descriptors, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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, 27);
-}
-
-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"
- "roto\"\333\003\n\023FileDescriptorProto\022\014\n\004name\030\001 \001"
- "(\t\022\017\n\007package\030\002 \001(\t\022\022\n\ndependency\030\003 \003(\t\022"
- "\031\n\021public_dependency\030\n \003(\005\022\027\n\017weak_depen"
- "dency\030\013 \003(\005\0226\n\014message_type\030\004 \003(\0132 .goog"
- "le.protobuf.DescriptorProto\0227\n\tenum_type"
- "\030\005 \003(\0132$.google.protobuf.EnumDescriptorP"
- "roto\0228\n\007service\030\006 \003(\0132\'.google.protobuf."
- "ServiceDescriptorProto\0228\n\textension\030\007 \003("
- "\0132%.google.protobuf.FieldDescriptorProto"
- "\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\"\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"
- "ype\030\003 \003(\0132 .google.protobuf.DescriptorPr"
- "oto\0227\n\tenum_type\030\004 \003(\0132$.google.protobuf"
- ".EnumDescriptorProto\022H\n\017extension_range\030"
- "\005 \003(\0132/.google.protobuf.DescriptorProto."
- "ExtensionRange\0229\n\noneof_decl\030\010 \003(\0132%.goo"
- "gle.protobuf.OneofDescriptorProto\0220\n\007opt"
- "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\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\"\246\006\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\022\036\n\026php_metadata_namesp"
- "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint"
- "erpreted_option\030\347\007 \003(\0132$.google.protobuf"
- ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005"
- "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003"
- "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027"
- "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037"
- "no_standard_descriptor_accessor\030\002 \001(\010:\005f"
- "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e"
- "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003("
- "\0132$.google.protobuf.UninterpretedOption*"
- "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022"
- ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp"
- "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j"
- "stype\030\006 \001(\0162$.google.protobuf.FieldOptio"
- "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals"
- "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001"
- "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013"
- "2$.google.protobuf.UninterpretedOption\"/"
- "\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_S"
- "TRING\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\024uninterpreted_option\030"
- "\347\007 \003(\0132$.google.protobuf.UninterpretedOp"
- "tion*\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\022"
- "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
- "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J"
- "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030"
- "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 "
- "\003(\0132$.google.protobuf.UninterpretedOptio"
- "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec"
- "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio"
- "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted"
- "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd"
- "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le"
- "vel\030\" \001(\0162/.google.protobuf.MethodOption"
- "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022"
- "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
- "protobuf.UninterpretedOption\"P\n\020Idempote"
- "ncyLevel\022\027\n\023IDEMPOTENCY_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\023UninterpretedOption\022;\n\004name\030\002 \003(\0132"
- "-.google.protobuf.UninterpretedOption.Na"
- "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi"
- "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val"
- "ue\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_exten"
- "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio"
- "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo"
- ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001"
- "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003"
- " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi"
- "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated"
- "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr"
- "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA"
- "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi"
- "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n"
- "\023com.google.protobufB\020DescriptorProtosH\001"
- "Z>github.com/golang/protobuf/protoc-gen-"
- "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog"
- "le.Protobuf.Reflection"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto, "google/protobuf/descriptor.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fdescriptor_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto, 27, file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto, file_level_service_descriptors_google_2fprotobuf_2fdescriptor_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fdescriptor_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fdescriptor_2eproto,
+ "\n google/protobuf/descriptor.proto\022\017goog"
+ "le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file"
+ "\030\001 \003(\0132$.google.protobuf.FileDescriptorP"
+ "roto\"\333\003\n\023FileDescriptorProto\022\014\n\004name\030\001 \001"
+ "(\t\022\017\n\007package\030\002 \001(\t\022\022\n\ndependency\030\003 \003(\t\022"
+ "\031\n\021public_dependency\030\n \003(\005\022\027\n\017weak_depen"
+ "dency\030\013 \003(\005\0226\n\014message_type\030\004 \003(\0132 .goog"
+ "le.protobuf.DescriptorProto\0227\n\tenum_type"
+ "\030\005 \003(\0132$.google.protobuf.EnumDescriptorP"
+ "roto\0228\n\007service\030\006 \003(\0132\'.google.protobuf."
+ "ServiceDescriptorProto\0228\n\textension\030\007 \003("
+ "\0132%.google.protobuf.FieldDescriptorProto"
+ "\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\"\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"
+ "ype\030\003 \003(\0132 .google.protobuf.DescriptorPr"
+ "oto\0227\n\tenum_type\030\004 \003(\0132$.google.protobuf"
+ ".EnumDescriptorProto\022H\n\017extension_range\030"
+ "\005 \003(\0132/.google.protobuf.DescriptorProto."
+ "ExtensionRange\0229\n\noneof_decl\030\010 \003(\0132%.goo"
+ "gle.protobuf.OneofDescriptorProto\0220\n\007opt"
+ "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\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\"\246\006\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\022\036\n\026php_metadata_namesp"
+ "ace\030, \001(\t\022\024\n\014ruby_package\030- \001(\t\022C\n\024unint"
+ "erpreted_option\030\347\007 \003(\0132$.google.protobuf"
+ ".UninterpretedOption\":\n\014OptimizeMode\022\t\n\005"
+ "SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003"
+ "*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\362\001\n\016MessageOptions\022&\n\027"
+ "message_set_wire_format\030\001 \001(\010:\005false\022.\n\037"
+ "no_standard_descriptor_accessor\030\002 \001(\010:\005f"
+ "alse\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tmap_e"
+ "ntry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347\007 \003("
+ "\0132$.google.protobuf.UninterpretedOption*"
+ "\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\tJ\004\010\t\020\n\"\236\003\n\014FieldOptions\022"
+ ":\n\005ctype\030\001 \001(\0162#.google.protobuf.FieldOp"
+ "tions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006j"
+ "stype\030\006 \001(\0162$.google.protobuf.FieldOptio"
+ "ns.JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005fals"
+ "e\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001"
+ "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013"
+ "2$.google.protobuf.UninterpretedOption\"/"
+ "\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_S"
+ "TRING\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\024uninterpreted_option\030"
+ "\347\007 \003(\0132$.google.protobuf.UninterpretedOp"
+ "tion*\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\022"
+ "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
+ "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002J"
+ "\004\010\005\020\006\"}\n\020EnumValueOptions\022\031\n\ndeprecated\030"
+ "\001 \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007 "
+ "\003(\0132$.google.protobuf.UninterpretedOptio"
+ "n*\t\010\350\007\020\200\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprec"
+ "ated\030! \001(\010:\005false\022C\n\024uninterpreted_optio"
+ "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted"
+ "Option*\t\010\350\007\020\200\200\200\200\002\"\255\002\n\rMethodOptions\022\031\n\nd"
+ "eprecated\030! \001(\010:\005false\022_\n\021idempotency_le"
+ "vel\030\" \001(\0162/.google.protobuf.MethodOption"
+ "s.IdempotencyLevel:\023IDEMPOTENCY_UNKNOWN\022"
+ "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google."
+ "protobuf.UninterpretedOption\"P\n\020Idempote"
+ "ncyLevel\022\027\n\023IDEMPOTENCY_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\023UninterpretedOption\022;\n\004name\030\002 \003(\0132"
+ "-.google.protobuf.UninterpretedOption.Na"
+ "mePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022posi"
+ "tive_int_value\030\004 \001(\004\022\032\n\022negative_int_val"
+ "ue\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_exten"
+ "sion\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010locatio"
+ "n\030\001 \003(\0132(.google.protobuf.SourceCodeInfo"
+ ".Location\032\206\001\n\010Location\022\020\n\004path\030\001 \003(\005B\002\020\001"
+ "\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leading_comments\030\003"
+ " \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031leadi"
+ "ng_detached_comments\030\006 \003(\t\"\247\001\n\021Generated"
+ "CodeInfo\022A\n\nannotation\030\001 \003(\0132-.google.pr"
+ "otobuf.GeneratedCodeInfo.Annotation\032O\n\nA"
+ "nnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source_fi"
+ "le\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B\217\001\n"
+ "\023com.google.protobufB\020DescriptorProtosH\001"
+ "Z>github.com/golang/protobuf/protoc-gen-"
+ "go/descriptor;descriptor\370\001\001\242\002\003GPB\252\002\032Goog"
+ "le.Protobuf.Reflection"
+,
+ "google/protobuf/descriptor.proto", &assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto, 6022,
+};
+
+void AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 6022);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/descriptor.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fdescriptor_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fdescriptor_2eproto = []() { AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto(); return true; }();
namespace google {
namespace protobuf {
const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor() {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[0];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[0];
}
bool FieldDescriptorProto_Type_IsValid(int value) {
switch (value) {
@@ -1323,8 +1273,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_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[1];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[1];
}
bool FieldDescriptorProto_Label_IsValid(int value) {
switch (value) {
@@ -1346,8 +1296,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_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[2];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[2];
}
bool FileOptions_OptimizeMode_IsValid(int value) {
switch (value) {
@@ -1369,8 +1319,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_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[3];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[3];
}
bool FieldOptions_CType_IsValid(int value) {
switch (value) {
@@ -1392,8 +1342,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_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[4];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[4];
}
bool FieldOptions_JSType_IsValid(int value) {
switch (value) {
@@ -1415,8 +1365,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_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_enum_descriptors[5];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fdescriptor_2eproto[5];
}
bool MethodOptions_IdempotencyLevel_IsValid(int value) {
switch (value) {
@@ -1442,14 +1392,16 @@ const int MethodOptions::IdempotencyLevel_ARRAYSIZE;
void FileDescriptorSet::InitAsDefaultInstance() {
}
+class FileDescriptorSet::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FileDescriptorSet::kFileFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FileDescriptorSet::FileDescriptorSet()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet)
}
@@ -1457,7 +1409,6 @@ FileDescriptorSet::FileDescriptorSet(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
file_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet)
@@ -1472,6 +1423,8 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from)
}
void FileDescriptorSet::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base);
}
FileDescriptorSet::~FileDescriptorSet() {
@@ -1487,18 +1440,13 @@ void FileDescriptorSet::ArenaDtor(void* object) {
FileDescriptorSet* _this = reinterpret_cast< FileDescriptorSet* >(object);
(void)_this;
}
-void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FileDescriptorSet::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FileDescriptorSet::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FileDescriptorSet& FileDescriptorSet::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorSet.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FileDescriptorSet_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -1514,9 +1462,64 @@ void FileDescriptorSet::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FileDescriptorSet::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FileDescriptorSet*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.FileDescriptorProto file = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FileDescriptorProto::_InternalParse;
+ object = msg->add_file();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FileDescriptorSet::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorSet)
for (;;) {
@@ -1526,8 +1529,7 @@ bool FileDescriptorSet::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.FileDescriptorProto file = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_file()));
} else {
@@ -1555,6 +1557,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FileDescriptorSet::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1610,6 +1613,10 @@ size_t FileDescriptorSet::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.FileDescriptorProto file = 1;
{
unsigned int count = static_cast<unsigned int>(this->file_size());
@@ -1630,7 +1637,7 @@ void FileDescriptorSet::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorSet)
GOOGLE_DCHECK_NE(&from, this);
const FileDescriptorSet* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FileDescriptorSet>(
+ ::google::protobuf::DynamicCastToGenerated<FileDescriptorSet>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileDescriptorSet)
@@ -1691,14 +1698,14 @@ void FileDescriptorSet::UnsafeArenaSwap(FileDescriptorSet* other) {
}
void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) {
using std::swap;
- CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
- swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ CastToBase(&file_)->InternalSwap(CastToBase(&other->file_));
}
::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -1710,6 +1717,35 @@ void FileDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_FileDescriptorProto_default_instance_._instance.get_mutable()->source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(
::google::protobuf::SourceCodeInfo::internal_default_instance());
}
+class FileDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(FileDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_package(FileDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static const ::google::protobuf::FileOptions& options(const FileDescriptorProto* msg);
+ static void set_has_options(FileDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static const ::google::protobuf::SourceCodeInfo& source_code_info(const FileDescriptorProto* msg);
+ static void set_has_source_code_info(FileDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+ static void set_has_syntax(FileDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+};
+
+const ::google::protobuf::FileOptions&
+FileDescriptorProto::HasBitSetters::options(const FileDescriptorProto* msg) {
+ return *msg->options_;
+}
+const ::google::protobuf::SourceCodeInfo&
+FileDescriptorProto::HasBitSetters::source_code_info(const FileDescriptorProto* msg) {
+ return *msg->source_code_info_;
+}
void FileDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::FileOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -1717,9 +1753,9 @@ void FileDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options)
}
@@ -1730,9 +1766,9 @@ void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info(
}
source_code_info_ = source_code_info;
if (source_code_info) {
- set_has_source_code_info();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_source_code_info();
+ _has_bits_[0] &= ~0x00000010u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
}
@@ -1753,8 +1789,6 @@ const int FileDescriptorProto::kSyntaxFieldNumber;
FileDescriptorProto::FileDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto)
}
@@ -1768,7 +1802,6 @@ FileDescriptorProto::FileDescriptorProto(::google::protobuf::Arena* arena)
extension_(arena),
public_dependency_(arena),
weak_dependency_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto)
@@ -1814,6 +1847,8 @@ FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
}
void FileDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1840,18 +1875,13 @@ void FileDescriptorProto::ArenaDtor(void* object) {
FileDescriptorProto* _this = reinterpret_cast< FileDescriptorProto* >(object);
(void)_this;
}
-void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FileDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FileDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FileDescriptorProto& FileDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FileDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -1870,7 +1900,7 @@ void FileDescriptorProto::Clear() {
public_dependency_.Clear();
weak_dependency_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 31u) {
+ if (cached_has_bits & 0x0000001fu) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -1893,9 +1923,261 @@ void FileDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FileDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FileDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string package = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.package");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_package();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated string dependency = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.dependency");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->add_dependency();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.DescriptorProto message_type = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::DescriptorProto::_InternalParse;
+ object = msg->add_message_type();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumDescriptorProto::_InternalParse;
+ object = msg->add_enum_type();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.ServiceDescriptorProto service = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::ServiceDescriptorProto::_InternalParse;
+ object = msg->add_service();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.FieldDescriptorProto extension = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse;
+ object = msg->add_extension();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 58 && (ptr += 1));
+ break;
+ }
+ // optional .google.protobuf.FileOptions options = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FileOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // optional .google.protobuf.SourceCodeInfo source_code_info = 9;
+ case 9: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::SourceCodeInfo::_InternalParse;
+ object = msg->mutable_source_code_info();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // repeated int32 public_dependency = 10;
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) == 80) {
+ do {
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->add_public_dependency(value);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 80 && (ptr += 1));
+ break;
+ } else if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::PackedInt32Parser;
+ object = msg->mutable_public_dependency();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated int32 weak_dependency = 11;
+ case 11: {
+ if (static_cast<::google::protobuf::uint8>(tag) == 88) {
+ do {
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->add_weak_dependency(value);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 88 && (ptr += 1));
+ break;
+ } else if (static_cast<::google::protobuf::uint8>(tag) != 90) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::PackedInt32Parser;
+ object = msg->mutable_weak_dependency();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string syntax = 12;
+ case 12: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 98) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileDescriptorProto.syntax");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_syntax();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FileDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileDescriptorProto)
for (;;) {
@@ -1905,8 +2187,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1921,8 +2202,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional string package = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1937,8 +2217,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated string dependency = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_dependency()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -1954,8 +2233,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.DescriptorProto message_type = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_message_type()));
} else {
@@ -1966,8 +2244,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_enum_type()));
} else {
@@ -1978,8 +2255,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_service()));
} else {
@@ -1990,8 +2266,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_extension()));
} else {
@@ -2002,8 +2277,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FileOptions options = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -2014,8 +2288,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
case 9: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (74 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_code_info()));
} else {
@@ -2026,14 +2299,11 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated int32 public_dependency = 10;
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (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 (
- static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
+ } else if (static_cast< ::google::protobuf::uint8>(tag) == (82 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_public_dependency())));
@@ -2045,14 +2315,11 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// repeated int32 weak_dependency = 11;
case 11: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(88u /* 88 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (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 (
- static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
+ } else if (static_cast< ::google::protobuf::uint8>(tag) == (90 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_weak_dependency())));
@@ -2064,8 +2331,7 @@ bool FileDescriptorProto::MergePartialFromCodedStream(
// optional string syntax = 12;
case 12: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(98u /* 98 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (98 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_syntax()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -2097,6 +2363,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FileDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2174,13 +2441,13 @@ void FileDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.FileOptions options = 8;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, this->_internal_options(), output);
+ 8, HasBitSetters::options(this), output);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 9, this->_internal_source_code_info(), output);
+ 9, HasBitSetters::source_code_info(this), output);
}
// repeated int32 public_dependency = 10;
@@ -2288,14 +2555,14 @@ void FileDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, this->_internal_options(), deterministic, target);
+ 8, HasBitSetters::options(this), deterministic, target);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 9, this->_internal_source_code_info(), deterministic, target);
+ 9, HasBitSetters::source_code_info(this), deterministic, target);
}
// repeated int32 public_dependency = 10;
@@ -2334,6 +2601,10 @@ size_t FileDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated string dependency = 3;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->dependency_size());
@@ -2404,37 +2675,38 @@ size_t FileDescriptorProto::ByteSizeLong() const {
total_size += data_size;
}
- if (_has_bits_[0 / 32] & 31u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x0000001fu) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional string package = 2;
- if (has_package()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->package());
}
// optional string syntax = 12;
- if (has_syntax()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->syntax());
}
// optional .google.protobuf.FileOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
}
// optional .google.protobuf.SourceCodeInfo source_code_info = 9;
- if (has_source_code_info()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*source_code_info_);
@@ -2450,7 +2722,7 @@ void FileDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const FileDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FileDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<FileDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileDescriptorProto)
@@ -2476,7 +2748,7 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) {
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 & 0x0000001fu) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -2541,6 +2813,8 @@ void FileDescriptorProto::UnsafeArenaSwap(FileDescriptorProto* other) {
}
void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
dependency_.InternalSwap(CastToBase(&other->dependency_));
CastToBase(&message_type_)->InternalSwap(CastToBase(&other->message_type_));
CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_));
@@ -2556,13 +2830,11 @@ void FileDescriptorProto::InternalSwap(FileDescriptorProto* other) {
GetArenaNoVirtual());
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_);
}
::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -2572,6 +2844,24 @@ 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());
}
+class DescriptorProto_ExtensionRange::HasBitSetters {
+ public:
+ static void set_has_start(DescriptorProto_ExtensionRange* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_end(DescriptorProto_ExtensionRange* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static const ::google::protobuf::ExtensionRangeOptions& options(const DescriptorProto_ExtensionRange* msg);
+ static void set_has_options(DescriptorProto_ExtensionRange* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+};
+
+const ::google::protobuf::ExtensionRangeOptions&
+DescriptorProto_ExtensionRange::HasBitSetters::options(const DescriptorProto_ExtensionRange* msg) {
+ return *msg->options_;
+}
void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
::google::protobuf::ExtensionRangeOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -2579,9 +2869,9 @@ void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000001u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
}
@@ -2593,15 +2883,12 @@ const int DescriptorProto_ExtensionRange::kOptionsFieldNumber;
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange)
@@ -2623,6 +2910,8 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP
}
void DescriptorProto_ExtensionRange::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base);
::memset(&options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&options_)) + sizeof(end_));
@@ -2642,18 +2931,13 @@ 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::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void DescriptorProto_ExtensionRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ExtensionRange.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_DescriptorProto_ExtensionRange_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -2669,7 +2953,7 @@ void DescriptorProto_ExtensionRange::Clear() {
GOOGLE_DCHECK(options_ != NULL);
options_->Clear();
}
- if (cached_has_bits & 6u) {
+ if (cached_has_bits & 0x00000006u) {
::memset(&start_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -2678,9 +2962,81 @@ void DescriptorProto_ExtensionRange::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* DescriptorProto_ExtensionRange::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<DescriptorProto_ExtensionRange*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional int32 start = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_start(value);
+ break;
+ }
+ // optional int32 end = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_end(value);
+ break;
+ }
+ // optional .google.protobuf.ExtensionRangeOptions options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::ExtensionRangeOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ExtensionRange)
for (;;) {
@@ -2690,9 +3046,8 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
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();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_start(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &start_)));
@@ -2704,9 +3059,8 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
// optional int32 end = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_end();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_end(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
@@ -2718,8 +3072,7 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
// optional .google.protobuf.ExtensionRangeOptions options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -2747,6 +3100,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2768,7 +3122,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
// optional .google.protobuf.ExtensionRangeOptions options = 3;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->_internal_options(), output);
+ 3, HasBitSetters::options(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2800,7 +3154,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, this->_internal_options(), deterministic, target);
+ 3, HasBitSetters::options(this), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -2820,23 +3174,28 @@ size_t DescriptorProto_ExtensionRange::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 7u) {
+ ::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 & 0x00000007u) {
// optional .google.protobuf.ExtensionRangeOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
}
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->start());
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->end());
@@ -2852,7 +3211,7 @@ void DescriptorProto_ExtensionRange::MergeFrom(const ::google::protobuf::Message
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange)
GOOGLE_DCHECK_NE(&from, this);
const DescriptorProto_ExtensionRange* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto_ExtensionRange>(
+ ::google::protobuf::DynamicCastToGenerated<DescriptorProto_ExtensionRange>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto.ExtensionRange)
@@ -2871,7 +3230,7 @@ void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRa
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
mutable_options()->::google::protobuf::ExtensionRangeOptions::MergeFrom(from.options());
}
@@ -2927,16 +3286,16 @@ void DescriptorProto_ExtensionRange::UnsafeArenaSwap(DescriptorProto_ExtensionRa
}
void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
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_);
}
::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -2944,6 +3303,16 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange
void DescriptorProto_ReservedRange::InitAsDefaultInstance() {
}
+class DescriptorProto_ReservedRange::HasBitSetters {
+ public:
+ static void set_has_start(DescriptorProto_ReservedRange* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_end(DescriptorProto_ReservedRange* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DescriptorProto_ReservedRange::kStartFieldNumber;
const int DescriptorProto_ReservedRange::kEndFieldNumber;
@@ -2951,15 +3320,12 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber;
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange)
}
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange)
@@ -2994,18 +3360,13 @@ 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::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void DescriptorProto_ReservedRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto_ReservedRange.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_DescriptorProto_ReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -3017,7 +3378,7 @@ void DescriptorProto_ReservedRange::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
::memset(&start_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -3026,9 +3387,66 @@ void DescriptorProto_ReservedRange::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* DescriptorProto_ReservedRange::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<DescriptorProto_ReservedRange*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional int32 start = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_start(value);
+ break;
+ }
+ // optional int32 end = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_end(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto.ReservedRange)
for (;;) {
@@ -3038,9 +3456,8 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
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();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_start(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &start_)));
@@ -3052,9 +3469,8 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
// optional int32 end = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_end();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_end(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
@@ -3083,6 +3499,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DescriptorProto_ReservedRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -3143,16 +3560,21 @@ size_t DescriptorProto_ReservedRange::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 3u) {
+ ::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 & 0x00000003u) {
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->start());
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->end());
@@ -3168,7 +3590,7 @@ void DescriptorProto_ReservedRange::MergeFrom(const ::google::protobuf::Message&
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ReservedRange)
GOOGLE_DCHECK_NE(&from, this);
const DescriptorProto_ReservedRange* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto_ReservedRange>(
+ ::google::protobuf::DynamicCastToGenerated<DescriptorProto_ReservedRange>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto.ReservedRange)
@@ -3187,7 +3609,7 @@ void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRang
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
start_ = from.start_;
}
@@ -3237,15 +3659,15 @@ void DescriptorProto_ReservedRange::UnsafeArenaSwap(DescriptorProto_ReservedRang
}
void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
swap(start_, other->start_);
swap(end_, other->end_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata DescriptorProto_ReservedRange::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -3255,6 +3677,21 @@ void DescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_DescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MessageOptions*>(
::google::protobuf::MessageOptions::internal_default_instance());
}
+class DescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(DescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static const ::google::protobuf::MessageOptions& options(const DescriptorProto* msg);
+ static void set_has_options(DescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::MessageOptions&
+DescriptorProto::HasBitSetters::options(const DescriptorProto* msg) {
+ return *msg->options_;
+}
void DescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::MessageOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -3262,9 +3699,9 @@ void DescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options)
}
@@ -3283,8 +3720,6 @@ const int DescriptorProto::kReservedNameFieldNumber;
DescriptorProto::DescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto)
}
@@ -3299,7 +3734,6 @@ DescriptorProto::DescriptorProto(::google::protobuf::Arena* arena)
oneof_decl_(arena),
reserved_range_(arena),
reserved_name_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto)
@@ -3331,6 +3765,8 @@ DescriptorProto::DescriptorProto(const DescriptorProto& from)
}
void DescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -3350,18 +3786,13 @@ void DescriptorProto::ArenaDtor(void* object) {
DescriptorProto* _this = reinterpret_cast< DescriptorProto* >(object);
(void)_this;
}
-void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void DescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void DescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const DescriptorProto& DescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_DescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_DescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -3381,7 +3812,7 @@ void DescriptorProto::Clear() {
reserved_range_.Clear();
reserved_name_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -3394,9 +3825,222 @@ void DescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* DescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<DescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.DescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.FieldDescriptorProto field = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse;
+ object = msg->add_field();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.DescriptorProto nested_type = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::DescriptorProto::_InternalParse;
+ object = msg->add_nested_type();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumDescriptorProto::_InternalParse;
+ object = msg->add_enum_type();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::DescriptorProto_ExtensionRange::_InternalParse;
+ object = msg->add_extension_range();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.FieldDescriptorProto extension = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FieldDescriptorProto::_InternalParse;
+ object = msg->add_extension();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
+ break;
+ }
+ // optional .google.protobuf.MessageOptions options = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::MessageOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::OneofDescriptorProto::_InternalParse;
+ object = msg->add_oneof_decl();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 66 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
+ case 9: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::DescriptorProto_ReservedRange::_InternalParse;
+ object = msg->add_reserved_range();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 74 && (ptr += 1));
+ break;
+ }
+ // repeated string reserved_name = 10;
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.DescriptorProto.reserved_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->add_reserved_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 82 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DescriptorProto)
for (;;) {
@@ -3406,8 +4050,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -3422,8 +4065,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.FieldDescriptorProto field = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_field()));
} else {
@@ -3434,8 +4076,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.DescriptorProto nested_type = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_nested_type()));
} else {
@@ -3446,8 +4087,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_enum_type()));
} else {
@@ -3458,8 +4098,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_extension_range()));
} else {
@@ -3470,8 +4109,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_extension()));
} else {
@@ -3482,8 +4120,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.MessageOptions options = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -3494,8 +4131,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_oneof_decl()));
} else {
@@ -3506,8 +4142,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
case 9: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (74 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_reserved_range()));
} else {
@@ -3518,8 +4153,7 @@ bool DescriptorProto::MergePartialFromCodedStream(
// repeated string reserved_name = 10;
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (82 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_reserved_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -3552,6 +4186,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -3618,7 +4253,7 @@ void DescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.MessageOptions options = 7;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 7, this->_internal_options(), output);
+ 7, HasBitSetters::options(this), output);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
@@ -3719,7 +4354,7 @@ void DescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 7, this->_internal_options(), deterministic, target);
+ 7, HasBitSetters::options(this), deterministic, target);
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
@@ -3765,6 +4400,10 @@ size_t DescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.FieldDescriptorProto field = 2;
{
unsigned int count = static_cast<unsigned int>(this->field_size());
@@ -3850,16 +4489,17 @@ size_t DescriptorProto::ByteSizeLong() const {
this->reserved_name(i));
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional .google.protobuf.MessageOptions options = 7;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
@@ -3875,7 +4515,7 @@ void DescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const DescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<DescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DescriptorProto)
@@ -3902,7 +4542,7 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) {
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 & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -3960,6 +4600,8 @@ void DescriptorProto::UnsafeArenaSwap(DescriptorProto* other) {
}
void DescriptorProto::InternalSwap(DescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&field_)->InternalSwap(CastToBase(&other->field_));
CastToBase(&nested_type_)->InternalSwap(CastToBase(&other->nested_type_));
CastToBase(&enum_type_)->InternalSwap(CastToBase(&other->enum_type_));
@@ -3971,13 +4613,11 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) {
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(options_, other->options_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata DescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -3985,14 +4625,16 @@ void DescriptorProto::InternalSwap(DescriptorProto* other) {
void ExtensionRangeOptions::InitAsDefaultInstance() {
}
+class ExtensionRangeOptions::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ExtensionRangeOptions::kUninterpretedOptionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ExtensionRangeOptions::ExtensionRangeOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ExtensionRangeOptions)
}
@@ -4001,7 +4643,6 @@ ExtensionRangeOptions::ExtensionRangeOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions)
@@ -4017,6 +4658,8 @@ ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from)
}
void ExtensionRangeOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
}
ExtensionRangeOptions::~ExtensionRangeOptions() {
@@ -4032,18 +4675,13 @@ void ExtensionRangeOptions::ArenaDtor(void* object) {
ExtensionRangeOptions* _this = reinterpret_cast< ExtensionRangeOptions* >(object);
(void)_this;
}
-void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void ExtensionRangeOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void ExtensionRangeOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-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 ExtensionRangeOptions& ExtensionRangeOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ExtensionRangeOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ExtensionRangeOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -4060,9 +4698,71 @@ void ExtensionRangeOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ExtensionRangeOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<ExtensionRangeOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ExtensionRangeOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ExtensionRangeOptions)
for (;;) {
@@ -4072,8 +4772,7 @@ bool ExtensionRangeOptions::MergePartialFromCodedStream(
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 */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -4107,6 +4806,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ExtensionRangeOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -4124,8 +4824,7 @@ void ExtensionRangeOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -4172,6 +4871,10 @@ size_t ExtensionRangeOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -4192,7 +4895,7 @@ 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>(
+ ::google::protobuf::DynamicCastToGenerated<ExtensionRangeOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ExtensionRangeOptions)
@@ -4258,15 +4961,15 @@ void ExtensionRangeOptions::UnsafeArenaSwap(ExtensionRangeOptions* other) {
}
void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) {
using std::swap;
- CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
_extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
}
::google::protobuf::Metadata ExtensionRangeOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -4276,6 +4979,45 @@ void FieldDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_FieldDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::FieldOptions*>(
::google::protobuf::FieldOptions::internal_default_instance());
}
+class FieldDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_number(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000040u;
+ }
+ static void set_has_label(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000100u;
+ }
+ static void set_has_type(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000200u;
+ }
+ static void set_has_type_name(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static void set_has_extendee(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_default_value(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_oneof_index(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000080u;
+ }
+ static void set_has_json_name(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+ static const ::google::protobuf::FieldOptions& options(const FieldDescriptorProto* msg);
+ static void set_has_options(FieldDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000020u;
+ }
+};
+
+const ::google::protobuf::FieldOptions&
+FieldDescriptorProto::HasBitSetters::options(const FieldDescriptorProto* msg) {
+ return *msg->options_;
+}
void FieldDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::FieldOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -4283,9 +5025,9 @@ void FieldDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000020u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000020u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
@@ -4304,15 +5046,12 @@ const int FieldDescriptorProto::kOptionsFieldNumber;
FieldDescriptorProto::FieldDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto)
}
FieldDescriptorProto::FieldDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto)
@@ -4359,6 +5098,8 @@ FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
}
void FieldDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -4390,18 +5131,13 @@ void FieldDescriptorProto::ArenaDtor(void* object) {
FieldDescriptorProto* _this = reinterpret_cast< FieldDescriptorProto* >(object);
(void)_this;
}
-void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FieldDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FieldDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FieldDescriptorProto& FieldDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FieldDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -4413,7 +5149,7 @@ void FieldDescriptorProto::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x0000003fu) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -4434,12 +5170,12 @@ void FieldDescriptorProto::Clear() {
options_->Clear();
}
}
- if (cached_has_bits & 192u) {
+ if (cached_has_bits & 0x000000c0u) {
::memset(&number_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&oneof_index_) -
reinterpret_cast<char*>(&number_)) + sizeof(oneof_index_));
}
- if (cached_has_bits & 768u) {
+ if (cached_has_bits & 0x00000300u) {
label_ = 1;
type_ = 1;
}
@@ -4447,9 +5183,189 @@ void FieldDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FieldDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FieldDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string extendee = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.extendee");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_extendee();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional int32 number = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_number(value);
+ break;
+ }
+ // optional .google.protobuf.FieldDescriptorProto.Label label = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::FieldDescriptorProto_Label_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(4, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::FieldDescriptorProto_Label value = static_cast<::google::protobuf::FieldDescriptorProto_Label>(val);
+ msg->set_label(value);
+ break;
+ }
+ // optional .google.protobuf.FieldDescriptorProto.Type type = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::FieldDescriptorProto_Type_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(5, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::FieldDescriptorProto_Type value = static_cast<::google::protobuf::FieldDescriptorProto_Type>(val);
+ msg->set_type(value);
+ break;
+ }
+ // optional string type_name = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.type_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_type_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string default_value = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.default_value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_default_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional .google.protobuf.FieldOptions options = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::FieldOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // optional int32 oneof_index = 9;
+ case 9: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 72) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_oneof_index(value);
+ break;
+ }
+ // optional string json_name = 10;
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldDescriptorProto.json_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_json_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FieldDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldDescriptorProto)
for (;;) {
@@ -4459,8 +5375,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -4475,8 +5390,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string extendee = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_extendee()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -4491,9 +5405,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional int32 number = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_number();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_number(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
@@ -4505,9 +5418,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -4515,7 +5427,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
set_label(static_cast< ::google::protobuf::FieldDescriptorProto_Label >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 4, static_cast< ::google::protobuf::uint64>(value));
+ 4, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -4525,9 +5437,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -4535,7 +5446,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
set_type(static_cast< ::google::protobuf::FieldDescriptorProto_Type >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 5, static_cast< ::google::protobuf::uint64>(value));
+ 5, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -4545,8 +5456,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string type_name = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -4561,8 +5471,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string default_value = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_default_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -4577,8 +5486,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.FieldOptions options = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -4589,9 +5497,8 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional int32 oneof_index = 9;
case 9: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
- set_has_oneof_index();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (72 & 0xFF)) {
+ HasBitSetters::set_has_oneof_index(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &oneof_index_)));
@@ -4603,8 +5510,7 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
// optional string json_name = 10;
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (82 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_json_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -4636,6 +5542,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FieldDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -4704,7 +5611,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.FieldOptions options = 8;
if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 8, this->_internal_options(), output);
+ 8, HasBitSetters::options(this), output);
}
// optional int32 oneof_index = 9;
@@ -4802,7 +5709,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 8, this->_internal_options(), deterministic, target);
+ 8, HasBitSetters::options(this), deterministic, target);
}
// optional int32 oneof_index = 9;
@@ -4838,73 +5745,78 @@ size_t FieldDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 255u) {
+ ::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 & 0x000000ffu) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional string extendee = 2;
- if (has_extendee()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->extendee());
}
// optional string type_name = 6;
- if (has_type_name()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->type_name());
}
// optional string default_value = 7;
- if (has_default_value()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->default_value());
}
// optional string json_name = 10;
- if (has_json_name()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->json_name());
}
// optional .google.protobuf.FieldOptions options = 8;
- if (has_options()) {
+ if (cached_has_bits & 0x00000020u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
}
// optional int32 number = 3;
- if (has_number()) {
+ if (cached_has_bits & 0x00000040u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->number());
}
// optional int32 oneof_index = 9;
- if (has_oneof_index()) {
+ if (cached_has_bits & 0x00000080u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->oneof_index());
}
}
- if (_has_bits_[8 / 32] & 768u) {
+ if (cached_has_bits & 0x00000300u) {
// optional .google.protobuf.FieldDescriptorProto.Label label = 4;
- if (has_label()) {
+ if (cached_has_bits & 0x00000100u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->label());
}
// optional .google.protobuf.FieldDescriptorProto.Type type = 5;
- if (has_type()) {
+ if (cached_has_bits & 0x00000200u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->type());
}
@@ -4919,7 +5831,7 @@ void FieldDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const FieldDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FieldDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<FieldDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldDescriptorProto)
@@ -4938,7 +5850,7 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -4965,7 +5877,7 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
}
_has_bits_[0] |= cached_has_bits;
}
- if (cached_has_bits & 768u) {
+ if (cached_has_bits & 0x00000300u) {
if (cached_has_bits & 0x00000100u) {
label_ = from.label_;
}
@@ -5018,6 +5930,8 @@ void FieldDescriptorProto::UnsafeArenaSwap(FieldDescriptorProto* other) {
}
void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
extendee_.Swap(&other->extendee_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
@@ -5033,13 +5947,11 @@ void FieldDescriptorProto::InternalSwap(FieldDescriptorProto* other) {
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_);
}
::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -5049,6 +5961,21 @@ void OneofDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_OneofDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::OneofOptions*>(
::google::protobuf::OneofOptions::internal_default_instance());
}
+class OneofDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(OneofDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static const ::google::protobuf::OneofOptions& options(const OneofDescriptorProto* msg);
+ static void set_has_options(OneofDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::OneofOptions&
+OneofDescriptorProto::HasBitSetters::options(const OneofDescriptorProto* msg) {
+ return *msg->options_;
+}
void OneofDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::OneofOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -5056,9 +5983,9 @@ void OneofDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options)
}
@@ -5069,15 +5996,12 @@ const int OneofDescriptorProto::kOptionsFieldNumber;
OneofDescriptorProto::OneofDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto)
}
OneofDescriptorProto::OneofDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto)
@@ -5101,6 +6025,8 @@ OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
}
void OneofDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -5120,18 +6046,13 @@ void OneofDescriptorProto::ArenaDtor(void* object) {
OneofDescriptorProto* _this = reinterpret_cast< OneofDescriptorProto* >(object);
(void)_this;
}
-void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void OneofDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void OneofDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const OneofDescriptorProto& OneofDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_OneofDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -5143,7 +6064,7 @@ void OneofDescriptorProto::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -5156,9 +6077,77 @@ void OneofDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* OneofDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<OneofDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.OneofDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional .google.protobuf.OneofOptions options = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::OneofOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool OneofDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.OneofDescriptorProto)
for (;;) {
@@ -5168,8 +6157,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -5184,8 +6172,7 @@ bool OneofDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.OneofOptions options = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -5213,6 +6200,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void OneofDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -5234,7 +6222,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.OneofOptions options = 2;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->_internal_options(), output);
+ 2, HasBitSetters::options(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5267,7 +6255,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, this->_internal_options(), deterministic, target);
+ 2, HasBitSetters::options(this), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -5287,16 +6275,21 @@ size_t OneofDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 3u) {
+ ::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 & 0x00000003u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional .google.protobuf.OneofOptions options = 2;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
@@ -5312,7 +6305,7 @@ void OneofDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const OneofDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const OneofDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<OneofDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.OneofDescriptorProto)
@@ -5331,7 +6324,7 @@ void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -5383,16 +6376,16 @@ void OneofDescriptorProto::UnsafeArenaSwap(OneofDescriptorProto* other) {
}
void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(options_, other->options_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata OneofDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -5400,6 +6393,16 @@ void OneofDescriptorProto::InternalSwap(OneofDescriptorProto* other) {
void EnumDescriptorProto_EnumReservedRange::InitAsDefaultInstance() {
}
+class EnumDescriptorProto_EnumReservedRange::HasBitSetters {
+ public:
+ static void set_has_start(EnumDescriptorProto_EnumReservedRange* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_end(EnumDescriptorProto_EnumReservedRange* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumDescriptorProto_EnumReservedRange::kStartFieldNumber;
const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber;
@@ -5407,15 +6410,12 @@ const int EnumDescriptorProto_EnumReservedRange::kEndFieldNumber;
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
}
EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange)
@@ -5450,18 +6450,13 @@ void EnumDescriptorProto_EnumReservedRange::ArenaDtor(void* object) {
EnumDescriptorProto_EnumReservedRange* _this = reinterpret_cast< EnumDescriptorProto_EnumReservedRange* >(object);
(void)_this;
}
-void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumDescriptorProto_EnumReservedRange::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto_EnumReservedRange.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumDescriptorProto_EnumReservedRange_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -5473,7 +6468,7 @@ void EnumDescriptorProto_EnumReservedRange::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
::memset(&start_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&start_)) + sizeof(end_));
@@ -5482,9 +6477,66 @@ void EnumDescriptorProto_EnumReservedRange::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumDescriptorProto_EnumReservedRange::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumDescriptorProto_EnumReservedRange*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional int32 start = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_start(value);
+ break;
+ }
+ // optional int32 end = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_end(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto.EnumReservedRange)
for (;;) {
@@ -5494,9 +6546,8 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream(
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();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_start(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &start_)));
@@ -5508,9 +6559,8 @@ bool EnumDescriptorProto_EnumReservedRange::MergePartialFromCodedStream(
// optional int32 end = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_end();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_end(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
@@ -5539,6 +6589,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumDescriptorProto_EnumReservedRange::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -5599,16 +6650,21 @@ size_t EnumDescriptorProto_EnumReservedRange::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 3u) {
+ ::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 & 0x00000003u) {
// optional int32 start = 1;
- if (has_start()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->start());
}
// optional int32 end = 2;
- if (has_end()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->end());
@@ -5624,7 +6680,7 @@ void EnumDescriptorProto_EnumReservedRange::MergeFrom(const ::google::protobuf::
// @@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>(
+ ::google::protobuf::DynamicCastToGenerated<EnumDescriptorProto_EnumReservedRange>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumDescriptorProto.EnumReservedRange)
@@ -5643,7 +6699,7 @@ void EnumDescriptorProto_EnumReservedRange::MergeFrom(const EnumDescriptorProto_
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
start_ = from.start_;
}
@@ -5693,15 +6749,15 @@ void EnumDescriptorProto_EnumReservedRange::UnsafeArenaSwap(EnumDescriptorProto_
}
void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_EnumReservedRange* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
swap(start_, other->start_);
swap(end_, other->end_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -5711,6 +6767,21 @@ void EnumDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_EnumDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumOptions*>(
::google::protobuf::EnumOptions::internal_default_instance());
}
+class EnumDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(EnumDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static const ::google::protobuf::EnumOptions& options(const EnumDescriptorProto* msg);
+ static void set_has_options(EnumDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::EnumOptions&
+EnumDescriptorProto::HasBitSetters::options(const EnumDescriptorProto* msg) {
+ return *msg->options_;
+}
void EnumDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::EnumOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -5718,9 +6789,9 @@ void EnumDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options)
}
@@ -5734,8 +6805,6 @@ const int EnumDescriptorProto::kReservedNameFieldNumber;
EnumDescriptorProto::EnumDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto)
}
@@ -5745,7 +6814,6 @@ EnumDescriptorProto::EnumDescriptorProto(::google::protobuf::Arena* arena)
value_(arena),
reserved_range_(arena),
reserved_name_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto)
@@ -5772,6 +6840,8 @@ EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
}
void EnumDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -5791,18 +6861,13 @@ void EnumDescriptorProto::ArenaDtor(void* object) {
EnumDescriptorProto* _this = reinterpret_cast< EnumDescriptorProto* >(object);
(void)_this;
}
-void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const EnumDescriptorProto& EnumDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -5817,7 +6882,7 @@ void EnumDescriptorProto::Clear() {
reserved_range_.Clear();
reserved_name_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -5830,9 +6895,132 @@ void EnumDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.EnumDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.EnumValueDescriptorProto value = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumValueDescriptorProto::_InternalParse;
+ object = msg->add_value();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // optional .google.protobuf.EnumOptions options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumDescriptorProto_EnumReservedRange::_InternalParse;
+ object = msg->add_reserved_range();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1));
+ break;
+ }
+ // repeated string reserved_name = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.EnumDescriptorProto.reserved_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->add_reserved_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumDescriptorProto)
for (;;) {
@@ -5842,8 +7030,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -5858,8 +7045,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_value()));
} else {
@@ -5870,8 +7056,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.EnumOptions options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -5882,8 +7067,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
// 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 */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_reserved_range()));
} else {
@@ -5894,8 +7078,7 @@ bool EnumDescriptorProto::MergePartialFromCodedStream(
// repeated string reserved_name = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_reserved_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -5928,6 +7111,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -5958,7 +7142,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.EnumOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->_internal_options(), output);
+ 3, HasBitSetters::options(this), output);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
@@ -6018,7 +7202,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, this->_internal_options(), deterministic, target);
+ 3, HasBitSetters::options(this), deterministic, target);
}
// repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
@@ -6056,6 +7240,10 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
{
unsigned int count = static_cast<unsigned int>(this->value_size());
@@ -6086,16 +7274,17 @@ size_t EnumDescriptorProto::ByteSizeLong() const {
this->reserved_name(i));
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional .google.protobuf.EnumOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
@@ -6111,7 +7300,7 @@ void EnumDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const EnumDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const EnumDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<EnumDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumDescriptorProto)
@@ -6133,7 +7322,7 @@ void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) {
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 & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -6186,19 +7375,19 @@ void EnumDescriptorProto::UnsafeArenaSwap(EnumDescriptorProto* other) {
}
void EnumDescriptorProto::InternalSwap(EnumDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&value_)->InternalSwap(CastToBase(&other->value_));
CastToBase(&reserved_range_)->InternalSwap(CastToBase(&other->reserved_range_));
reserved_name_.InternalSwap(CastToBase(&other->reserved_name_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(options_, other->options_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -6208,6 +7397,24 @@ void EnumValueDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_EnumValueDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::EnumValueOptions*>(
::google::protobuf::EnumValueOptions::internal_default_instance());
}
+class EnumValueDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(EnumValueDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_number(EnumValueDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static const ::google::protobuf::EnumValueOptions& options(const EnumValueDescriptorProto* msg);
+ static void set_has_options(EnumValueDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::EnumValueOptions&
+EnumValueDescriptorProto::HasBitSetters::options(const EnumValueDescriptorProto* msg) {
+ return *msg->options_;
+}
void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::EnumValueOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -6215,9 +7422,9 @@ void EnumValueDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
}
@@ -6229,15 +7436,12 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber;
EnumValueDescriptorProto::EnumValueDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto)
}
EnumValueDescriptorProto::EnumValueDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto)
@@ -6262,6 +7466,8 @@ EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProt
}
void EnumValueDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&options_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&number_) -
@@ -6283,18 +7489,13 @@ void EnumValueDescriptorProto::ArenaDtor(void* object) {
EnumValueDescriptorProto* _this = reinterpret_cast< EnumValueDescriptorProto* >(object);
(void)_this;
}
-void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumValueDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumValueDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumValueDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -6306,7 +7507,7 @@ void EnumValueDescriptorProto::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -6320,9 +7521,87 @@ void EnumValueDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumValueDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumValueDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.EnumValueDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional int32 number = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_number(value);
+ break;
+ }
+ // optional .google.protobuf.EnumValueOptions options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumValueOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumValueDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValueDescriptorProto)
for (;;) {
@@ -6332,8 +7611,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -6348,9 +7626,8 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
// optional int32 number = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_number();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_number(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
@@ -6362,8 +7639,7 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.EnumValueOptions options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -6391,6 +7667,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumValueDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -6417,7 +7694,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.EnumValueOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->_internal_options(), output);
+ 3, HasBitSetters::options(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6455,7 +7732,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, this->_internal_options(), deterministic, target);
+ 3, HasBitSetters::options(this), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6475,23 +7752,28 @@ size_t EnumValueDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 7u) {
+ ::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 & 0x00000007u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional .google.protobuf.EnumValueOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
}
// optional int32 number = 2;
- if (has_number()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->number());
@@ -6507,7 +7789,7 @@ void EnumValueDescriptorProto::MergeFrom(const ::google::protobuf::Message& from
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const EnumValueDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const EnumValueDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<EnumValueDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumValueDescriptorProto)
@@ -6526,7 +7808,7 @@ void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -6582,17 +7864,17 @@ void EnumValueDescriptorProto::UnsafeArenaSwap(EnumValueDescriptorProto* other)
}
void EnumValueDescriptorProto::InternalSwap(EnumValueDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(options_, other->options_);
swap(number_, other->number_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -6602,6 +7884,21 @@ void ServiceDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_ServiceDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::ServiceOptions*>(
::google::protobuf::ServiceOptions::internal_default_instance());
}
+class ServiceDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(ServiceDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static const ::google::protobuf::ServiceOptions& options(const ServiceDescriptorProto* msg);
+ static void set_has_options(ServiceDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
+const ::google::protobuf::ServiceOptions&
+ServiceDescriptorProto::HasBitSetters::options(const ServiceDescriptorProto* msg) {
+ return *msg->options_;
+}
void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::ServiceOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -6609,9 +7906,9 @@ void ServiceDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options)
}
@@ -6623,8 +7920,6 @@ const int ServiceDescriptorProto::kOptionsFieldNumber;
ServiceDescriptorProto::ServiceDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto)
}
@@ -6632,7 +7927,6 @@ ServiceDescriptorProto::ServiceDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
method_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto)
@@ -6657,6 +7951,8 @@ ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& fro
}
void ServiceDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
}
@@ -6676,18 +7972,13 @@ void ServiceDescriptorProto::ArenaDtor(void* object) {
ServiceDescriptorProto* _this = reinterpret_cast< ServiceDescriptorProto* >(object);
(void)_this;
}
-void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void ServiceDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void ServiceDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ServiceDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -6700,7 +7991,7 @@ void ServiceDescriptorProto::Clear() {
method_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -6713,9 +8004,95 @@ void ServiceDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ServiceDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<ServiceDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.ServiceDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.MethodDescriptorProto method = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::MethodDescriptorProto::_InternalParse;
+ object = msg->add_method();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // optional .google.protobuf.ServiceOptions options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::ServiceOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ServiceDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ServiceDescriptorProto)
for (;;) {
@@ -6725,8 +8102,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -6741,8 +8117,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
// repeated .google.protobuf.MethodDescriptorProto method = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_method()));
} else {
@@ -6753,8 +8128,7 @@ bool ServiceDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.ServiceOptions options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -6782,6 +8156,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ServiceDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -6812,7 +8187,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.ServiceOptions options = 3;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 3, this->_internal_options(), output);
+ 3, HasBitSetters::options(this), output);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6853,7 +8228,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 3, this->_internal_options(), deterministic, target);
+ 3, HasBitSetters::options(this), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6873,6 +8248,10 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.MethodDescriptorProto method = 2;
{
unsigned int count = static_cast<unsigned int>(this->method_size());
@@ -6884,16 +8263,17 @@ size_t ServiceDescriptorProto::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional .google.protobuf.ServiceOptions options = 3;
- if (has_options()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
@@ -6909,7 +8289,7 @@ void ServiceDescriptorProto::MergeFrom(const ::google::protobuf::Message& from)
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const ServiceDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const ServiceDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<ServiceDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ServiceDescriptorProto)
@@ -6929,7 +8309,7 @@ void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) {
method_.MergeFrom(from.method_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -6982,17 +8362,17 @@ void ServiceDescriptorProto::UnsafeArenaSwap(ServiceDescriptorProto* other) {
}
void ServiceDescriptorProto::InternalSwap(ServiceDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&method_)->InternalSwap(CastToBase(&other->method_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(options_, other->options_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -7002,6 +8382,33 @@ void MethodDescriptorProto::InitAsDefaultInstance() {
::google::protobuf::_MethodDescriptorProto_default_instance_._instance.get_mutable()->options_ = const_cast< ::google::protobuf::MethodOptions*>(
::google::protobuf::MethodOptions::internal_default_instance());
}
+class MethodDescriptorProto::HasBitSetters {
+ public:
+ static void set_has_name(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_input_type(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_output_type(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static const ::google::protobuf::MethodOptions& options(const MethodDescriptorProto* msg);
+ static void set_has_options(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_client_streaming(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+ static void set_has_server_streaming(MethodDescriptorProto* msg) {
+ msg->_has_bits_[0] |= 0x00000020u;
+ }
+};
+
+const ::google::protobuf::MethodOptions&
+MethodDescriptorProto::HasBitSetters::options(const MethodDescriptorProto* msg) {
+ return *msg->options_;
+}
void MethodDescriptorProto::unsafe_arena_set_allocated_options(
::google::protobuf::MethodOptions* options) {
if (GetArenaNoVirtual() == NULL) {
@@ -7009,9 +8416,9 @@ void MethodDescriptorProto::unsafe_arena_set_allocated_options(
}
options_ = options;
if (options) {
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options)
}
@@ -7026,15 +8433,12 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber;
MethodDescriptorProto::MethodDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto)
}
MethodDescriptorProto::MethodDescriptorProto(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto)
@@ -7071,6 +8475,8 @@ MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
}
void MethodDescriptorProto::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -7096,18 +8502,13 @@ void MethodDescriptorProto::ArenaDtor(void* object) {
MethodDescriptorProto* _this = reinterpret_cast< MethodDescriptorProto* >(object);
(void)_this;
}
-void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void MethodDescriptorProto::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void MethodDescriptorProto::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const MethodDescriptorProto& MethodDescriptorProto::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodDescriptorProto.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_MethodDescriptorProto_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -7119,7 +8520,7 @@ void MethodDescriptorProto::Clear() {
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x0000000fu) {
if (cached_has_bits & 0x00000001u) {
name_.ClearNonDefaultToEmpty();
}
@@ -7141,9 +8542,129 @@ void MethodDescriptorProto::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* MethodDescriptorProto::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<MethodDescriptorProto*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string input_type = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.input_type");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_input_type();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string output_type = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.MethodDescriptorProto.output_type");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_output_type();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional .google.protobuf.MethodOptions options = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::MethodOptions::_InternalParse;
+ object = msg->mutable_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // optional bool client_streaming = 5 [default = false];
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_client_streaming(value);
+ break;
+ }
+ // optional bool server_streaming = 6 [default = false];
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_server_streaming(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool MethodDescriptorProto::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MethodDescriptorProto)
for (;;) {
@@ -7153,8 +8674,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7169,8 +8689,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional string input_type = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_input_type()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7185,8 +8704,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional string output_type = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_output_type()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7201,8 +8719,7 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional .google.protobuf.MethodOptions options = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_options()));
} else {
@@ -7213,9 +8730,8 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional bool client_streaming = 5 [default = false];
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- set_has_client_streaming();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
+ HasBitSetters::set_has_client_streaming(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &client_streaming_)));
@@ -7227,9 +8743,8 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
// optional bool server_streaming = 6 [default = false];
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
- set_has_server_streaming();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) {
+ HasBitSetters::set_has_server_streaming(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &server_streaming_)));
@@ -7258,6 +8773,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void MethodDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -7299,7 +8815,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
// optional .google.protobuf.MethodOptions options = 4;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->_internal_options(), output);
+ 4, HasBitSetters::options(this), output);
}
// optional bool client_streaming = 5 [default = false];
@@ -7364,7 +8880,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, this->_internal_options(), deterministic, target);
+ 4, HasBitSetters::options(this), deterministic, target);
}
// optional bool client_streaming = 5 [default = false];
@@ -7394,42 +8910,47 @@ size_t MethodDescriptorProto::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
- if (_has_bits_[0 / 32] & 63u) {
+ ::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 & 0x0000003fu) {
// optional string name = 1;
- if (has_name()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// optional string input_type = 2;
- if (has_input_type()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->input_type());
}
// optional string output_type = 3;
- if (has_output_type()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->output_type());
}
// optional .google.protobuf.MethodOptions options = 4;
- if (has_options()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*options_);
}
// optional bool client_streaming = 5 [default = false];
- if (has_client_streaming()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 1 + 1;
}
// optional bool server_streaming = 6 [default = false];
- if (has_server_streaming()) {
+ if (cached_has_bits & 0x00000020u) {
total_size += 1 + 1;
}
@@ -7443,7 +8964,7 @@ void MethodDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodDescriptorProto)
GOOGLE_DCHECK_NE(&from, this);
const MethodDescriptorProto* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const MethodDescriptorProto>(
+ ::google::protobuf::DynamicCastToGenerated<MethodDescriptorProto>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MethodDescriptorProto)
@@ -7462,7 +8983,7 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) {
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x0000003fu) {
if (cached_has_bits & 0x00000001u) {
set_name(from.name());
}
@@ -7527,6 +9048,8 @@ void MethodDescriptorProto::UnsafeArenaSwap(MethodDescriptorProto* other) {
}
void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
input_type_.Swap(&other->input_type_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
@@ -7536,13 +9059,11 @@ void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
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_);
}
::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -7550,6 +9071,70 @@ void MethodDescriptorProto::InternalSwap(MethodDescriptorProto* other) {
void FileOptions::InitAsDefaultInstance() {
}
+class FileOptions::HasBitSetters {
+ public:
+ static void set_has_java_package(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_java_outer_classname(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_java_multiple_files(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000400u;
+ }
+ static void set_has_java_generate_equals_and_hash(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000800u;
+ }
+ static void set_has_java_string_check_utf8(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00001000u;
+ }
+ static void set_has_optimize_for(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00080000u;
+ }
+ static void set_has_go_package(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static void set_has_cc_generic_services(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00002000u;
+ }
+ static void set_has_java_generic_services(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00004000u;
+ }
+ static void set_has_py_generic_services(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00008000u;
+ }
+ static void set_has_php_generic_services(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00010000u;
+ }
+ static void set_has_deprecated(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00020000u;
+ }
+ static void set_has_cc_enable_arenas(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00040000u;
+ }
+ static void set_has_objc_class_prefix(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_csharp_namespace(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+ static void set_has_swift_prefix(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000020u;
+ }
+ static void set_has_php_class_prefix(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000040u;
+ }
+ static void set_has_php_namespace(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000080u;
+ }
+ static void set_has_php_metadata_namespace(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000100u;
+ }
+ static void set_has_ruby_package(FileOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000200u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FileOptions::kJavaPackageFieldNumber;
const int FileOptions::kJavaOuterClassnameFieldNumber;
@@ -7576,8 +9161,6 @@ const int FileOptions::kUninterpretedOptionFieldNumber;
FileOptions::FileOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileOptions)
}
@@ -7586,7 +9169,6 @@ FileOptions::FileOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions)
@@ -7655,6 +9237,8 @@ FileOptions::FileOptions(const FileOptions& from)
}
void FileOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -7694,18 +9278,13 @@ void FileOptions::ArenaDtor(void* object) {
FileOptions* _this = reinterpret_cast< FileOptions* >(object);
(void)_this;
}
-void FileOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FileOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FileOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FileOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FileOptions& FileOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FileOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -7719,7 +9298,7 @@ void FileOptions::Clear() {
_extensions_.Clear();
uninterpreted_option_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
java_package_.ClearNonDefaultToEmpty();
}
@@ -7745,7 +9324,7 @@ void FileOptions::Clear() {
php_namespace_.ClearNonDefaultToEmpty();
}
}
- if (cached_has_bits & 768u) {
+ if (cached_has_bits & 0x00000300u) {
if (cached_has_bits & 0x00000100u) {
php_metadata_namespace_.ClearNonDefaultToEmpty();
}
@@ -7753,12 +9332,12 @@ void FileOptions::Clear() {
ruby_package_.ClearNonDefaultToEmpty();
}
}
- if (cached_has_bits & 64512u) {
+ if (cached_has_bits & 0x0000fc00u) {
::memset(&java_multiple_files_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&py_generic_services_) -
reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(py_generic_services_));
}
- if (cached_has_bits & 983040u) {
+ if (cached_has_bits & 0x000f0000u) {
::memset(&php_generic_services_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&cc_enable_arenas_) -
reinterpret_cast<char*>(&php_generic_services_)) + sizeof(cc_enable_arenas_));
@@ -7768,9 +9347,335 @@ void FileOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FileOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FileOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional string java_package = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.java_package");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_java_package();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string java_outer_classname = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.java_outer_classname");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_java_outer_classname();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
+ case 9: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 72) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::FileOptions_OptimizeMode_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(9, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::FileOptions_OptimizeMode value = static_cast<::google::protobuf::FileOptions_OptimizeMode>(val);
+ msg->set_optimize_for(value);
+ break;
+ }
+ // optional bool java_multiple_files = 10 [default = false];
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_java_multiple_files(value);
+ break;
+ }
+ // optional string go_package = 11;
+ case 11: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 90) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.go_package");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_go_package();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional bool cc_generic_services = 16 [default = false];
+ case 16: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 128) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_cc_generic_services(value);
+ break;
+ }
+ // optional bool java_generic_services = 17 [default = false];
+ case 17: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 136) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_java_generic_services(value);
+ break;
+ }
+ // optional bool py_generic_services = 18 [default = false];
+ case 18: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 144) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_py_generic_services(value);
+ break;
+ }
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
+ case 20: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 160) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_java_generate_equals_and_hash(value);
+ break;
+ }
+ // optional bool deprecated = 23 [default = false];
+ case 23: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 184) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // optional bool java_string_check_utf8 = 27 [default = false];
+ case 27: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 216) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_java_string_check_utf8(value);
+ break;
+ }
+ // optional bool cc_enable_arenas = 31 [default = false];
+ case 31: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 248) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_cc_enable_arenas(value);
+ break;
+ }
+ // optional string objc_class_prefix = 36;
+ case 36: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.objc_class_prefix");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_objc_class_prefix();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string csharp_namespace = 37;
+ case 37: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.csharp_namespace");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_csharp_namespace();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string swift_prefix = 39;
+ case 39: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.swift_prefix");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_swift_prefix();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string php_class_prefix = 40;
+ case 40: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_class_prefix");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_php_class_prefix();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string php_namespace = 41;
+ case 41: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_namespace");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_php_namespace();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional bool php_generic_services = 42 [default = false];
+ case 42: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_php_generic_services(value);
+ break;
+ }
+ // optional string php_metadata_namespace = 44;
+ case 44: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 98) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.php_metadata_namespace");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_php_metadata_namespace();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string ruby_package = 45;
+ case 45: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 106) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FileOptions.ruby_package");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_ruby_package();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FileOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FileOptions)
for (;;) {
@@ -7780,8 +9685,7 @@ bool FileOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string java_package = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_java_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7796,8 +9700,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string java_outer_classname = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_java_outer_classname()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7812,9 +9715,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
case 9: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(72u /* 72 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (72 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -7822,7 +9724,7 @@ bool FileOptions::MergePartialFromCodedStream(
set_optimize_for(static_cast< ::google::protobuf::FileOptions_OptimizeMode >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 9, static_cast< ::google::protobuf::uint64>(value));
+ 9, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -7832,9 +9734,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_multiple_files = 10 [default = false];
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
- set_has_java_multiple_files();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (80 & 0xFF)) {
+ HasBitSetters::set_has_java_multiple_files(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_multiple_files_)));
@@ -7846,8 +9747,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string go_package = 11;
case 11: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (90 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_go_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7862,9 +9762,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool cc_generic_services = 16 [default = false];
case 16: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(128u /* 128 & 0xFF */)) {
- set_has_cc_generic_services();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (128 & 0xFF)) {
+ HasBitSetters::set_has_cc_generic_services(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &cc_generic_services_)));
@@ -7876,9 +9775,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_generic_services = 17 [default = false];
case 17: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(136u /* 136 & 0xFF */)) {
- set_has_java_generic_services();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (136 & 0xFF)) {
+ HasBitSetters::set_has_java_generic_services(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_generic_services_)));
@@ -7890,9 +9788,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool py_generic_services = 18 [default = false];
case 18: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) {
- set_has_py_generic_services();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (144 & 0xFF)) {
+ HasBitSetters::set_has_py_generic_services(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &py_generic_services_)));
@@ -7904,9 +9801,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
case 20: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) {
- set_has_java_generate_equals_and_hash();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (160 & 0xFF)) {
+ HasBitSetters::set_has_java_generate_equals_and_hash(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_generate_equals_and_hash_)));
@@ -7918,9 +9814,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool deprecated = 23 [default = false];
case 23: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (184 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -7932,9 +9827,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool java_string_check_utf8 = 27 [default = false];
case 27: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(216u /* 216 & 0xFF */)) {
- set_has_java_string_check_utf8();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (216 & 0xFF)) {
+ HasBitSetters::set_has_java_string_check_utf8(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_string_check_utf8_)));
@@ -7946,9 +9840,8 @@ bool FileOptions::MergePartialFromCodedStream(
// optional bool cc_enable_arenas = 31 [default = false];
case 31: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(248u /* 248 & 0xFF */)) {
- set_has_cc_enable_arenas();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (248 & 0xFF)) {
+ HasBitSetters::set_has_cc_enable_arenas(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &cc_enable_arenas_)));
@@ -7960,8 +9853,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string objc_class_prefix = 36;
case 36: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 290 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (290 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_objc_class_prefix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7976,8 +9868,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string csharp_namespace = 37;
case 37: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 298 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (298 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_csharp_namespace()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -7992,8 +9883,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string swift_prefix = 39;
case 39: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 314 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (314 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_swift_prefix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -8008,8 +9898,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string php_class_prefix = 40;
case 40: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 322 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (322 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_php_class_prefix()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -8024,8 +9913,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string php_namespace = 41;
case 41: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(74u /* 330 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (330 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_php_namespace()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -8040,9 +9928,8 @@ bool FileOptions::MergePartialFromCodedStream(
// 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();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (336 & 0xFF)) {
+ HasBitSetters::set_has_php_generic_services(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &php_generic_services_)));
@@ -8054,8 +9941,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string php_metadata_namespace = 44;
case 44: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(98u /* 354 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (354 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_php_metadata_namespace()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -8070,8 +9956,7 @@ bool FileOptions::MergePartialFromCodedStream(
// optional string ruby_package = 45;
case 45: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(106u /* 362 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (362 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_ruby_package()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -8086,8 +9971,7 @@ bool FileOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -8121,6 +10005,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FileOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -8290,8 +10175,7 @@ void FileOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -8500,6 +10384,10 @@ size_t FileOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -8511,128 +10399,129 @@ size_t FileOptions::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 255u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x000000ffu) {
// optional string java_package = 1;
- if (has_java_package()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->java_package());
}
// optional string java_outer_classname = 8;
- if (has_java_outer_classname()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->java_outer_classname());
}
// optional string go_package = 11;
- if (has_go_package()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->go_package());
}
// optional string objc_class_prefix = 36;
- if (has_objc_class_prefix()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->objc_class_prefix());
}
// optional string csharp_namespace = 37;
- if (has_csharp_namespace()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->csharp_namespace());
}
// optional string swift_prefix = 39;
- if (has_swift_prefix()) {
+ if (cached_has_bits & 0x00000020u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->swift_prefix());
}
// optional string php_class_prefix = 40;
- if (has_php_class_prefix()) {
+ if (cached_has_bits & 0x00000040u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->php_class_prefix());
}
// optional string php_namespace = 41;
- if (has_php_namespace()) {
+ if (cached_has_bits & 0x00000080u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->php_namespace());
}
}
- if (_has_bits_[8 / 32] & 65280u) {
+ if (cached_has_bits & 0x0000ff00u) {
// optional string php_metadata_namespace = 44;
- if (has_php_metadata_namespace()) {
+ if (cached_has_bits & 0x00000100u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->php_metadata_namespace());
}
// optional string ruby_package = 45;
- if (has_ruby_package()) {
+ if (cached_has_bits & 0x00000200u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->ruby_package());
}
// optional bool java_multiple_files = 10 [default = false];
- if (has_java_multiple_files()) {
+ if (cached_has_bits & 0x00000400u) {
total_size += 1 + 1;
}
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- if (has_java_generate_equals_and_hash()) {
+ if (cached_has_bits & 0x00000800u) {
total_size += 2 + 1;
}
// optional bool java_string_check_utf8 = 27 [default = false];
- if (has_java_string_check_utf8()) {
+ if (cached_has_bits & 0x00001000u) {
total_size += 2 + 1;
}
// optional bool cc_generic_services = 16 [default = false];
- if (has_cc_generic_services()) {
+ if (cached_has_bits & 0x00002000u) {
total_size += 2 + 1;
}
// optional bool java_generic_services = 17 [default = false];
- if (has_java_generic_services()) {
+ if (cached_has_bits & 0x00004000u) {
total_size += 2 + 1;
}
// optional bool py_generic_services = 18 [default = false];
- if (has_py_generic_services()) {
+ if (cached_has_bits & 0x00008000u) {
total_size += 2 + 1;
}
}
- if (_has_bits_[16 / 32] & 983040u) {
+ if (cached_has_bits & 0x000f0000u) {
// optional bool php_generic_services = 42 [default = false];
- if (has_php_generic_services()) {
+ if (cached_has_bits & 0x00010000u) {
total_size += 2 + 1;
}
// optional bool deprecated = 23 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00020000u) {
total_size += 2 + 1;
}
// optional bool cc_enable_arenas = 31 [default = false];
- if (has_cc_enable_arenas()) {
+ if (cached_has_bits & 0x00040000u) {
total_size += 2 + 1;
}
// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED];
- if (has_optimize_for()) {
+ if (cached_has_bits & 0x00080000u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->optimize_for());
}
@@ -8647,7 +10536,7 @@ void FileOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileOptions)
GOOGLE_DCHECK_NE(&from, this);
const FileOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FileOptions>(
+ ::google::protobuf::DynamicCastToGenerated<FileOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FileOptions)
@@ -8668,7 +10557,7 @@ void FileOptions::MergeFrom(const FileOptions& from) {
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 255u) {
+ if (cached_has_bits & 0x000000ffu) {
if (cached_has_bits & 0x00000001u) {
set_java_package(from.java_package());
}
@@ -8694,7 +10583,7 @@ void FileOptions::MergeFrom(const FileOptions& from) {
set_php_namespace(from.php_namespace());
}
}
- if (cached_has_bits & 65280u) {
+ if (cached_has_bits & 0x0000ff00u) {
if (cached_has_bits & 0x00000100u) {
set_php_metadata_namespace(from.php_metadata_namespace());
}
@@ -8721,7 +10610,7 @@ void FileOptions::MergeFrom(const FileOptions& from) {
}
_has_bits_[0] |= cached_has_bits;
}
- if (cached_has_bits & 983040u) {
+ if (cached_has_bits & 0x000f0000u) {
if (cached_has_bits & 0x00010000u) {
php_generic_services_ = from.php_generic_services_;
}
@@ -8782,6 +10671,9 @@ void FileOptions::UnsafeArenaSwap(FileOptions* other) {
}
void FileOptions::InternalSwap(FileOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
java_package_.Swap(&other->java_package_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
@@ -8813,14 +10705,11 @@ void FileOptions::InternalSwap(FileOptions* other) {
swap(deprecated_, other->deprecated_);
swap(cc_enable_arenas_, other->cc_enable_arenas_);
swap(optimize_for_, other->optimize_for_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata FileOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -8828,6 +10717,22 @@ void FileOptions::InternalSwap(FileOptions* other) {
void MessageOptions::InitAsDefaultInstance() {
}
+class MessageOptions::HasBitSetters {
+ public:
+ static void set_has_message_set_wire_format(MessageOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_no_standard_descriptor_accessor(MessageOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_deprecated(MessageOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static void set_has_map_entry(MessageOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MessageOptions::kMessageSetWireFormatFieldNumber;
const int MessageOptions::kNoStandardDescriptorAccessorFieldNumber;
@@ -8838,8 +10743,6 @@ const int MessageOptions::kUninterpretedOptionFieldNumber;
MessageOptions::MessageOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MessageOptions)
}
@@ -8848,7 +10751,6 @@ MessageOptions::MessageOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions)
@@ -8867,6 +10769,8 @@ MessageOptions::MessageOptions(const MessageOptions& from)
}
void MessageOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
::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_));
@@ -8885,18 +10789,13 @@ void MessageOptions::ArenaDtor(void* object) {
MessageOptions* _this = reinterpret_cast< MessageOptions* >(object);
(void)_this;
}
-void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void MessageOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void MessageOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const MessageOptions& MessageOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MessageOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_MessageOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -8916,9 +10815,111 @@ void MessageOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* MessageOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<MessageOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional bool message_set_wire_format = 1 [default = false];
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_message_set_wire_format(value);
+ break;
+ }
+ // optional bool no_standard_descriptor_accessor = 2 [default = false];
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_no_standard_descriptor_accessor(value);
+ break;
+ }
+ // optional bool deprecated = 3 [default = false];
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // optional bool map_entry = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_map_entry(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool MessageOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MessageOptions)
for (;;) {
@@ -8928,9 +10929,8 @@ bool MessageOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool message_set_wire_format = 1 [default = false];
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- set_has_message_set_wire_format();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_message_set_wire_format(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &message_set_wire_format_)));
@@ -8942,9 +10942,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool no_standard_descriptor_accessor = 2 [default = false];
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_no_standard_descriptor_accessor();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_no_standard_descriptor_accessor(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &no_standard_descriptor_accessor_)));
@@ -8956,9 +10955,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -8970,9 +10968,8 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool map_entry = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
- set_has_map_entry();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
+ HasBitSetters::set_has_map_entry(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &map_entry_)));
@@ -8984,8 +10981,7 @@ bool MessageOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -9019,6 +11015,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void MessageOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -9057,8 +11054,7 @@ void MessageOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -9126,6 +11122,10 @@ size_t MessageOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -9137,24 +11137,25 @@ size_t MessageOptions::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 15u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x0000000fu) {
// optional bool message_set_wire_format = 1 [default = false];
- if (has_message_set_wire_format()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 + 1;
}
// optional bool no_standard_descriptor_accessor = 2 [default = false];
- if (has_no_standard_descriptor_accessor()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 + 1;
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 + 1;
}
// optional bool map_entry = 7;
- if (has_map_entry()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 + 1;
}
@@ -9168,7 +11169,7 @@ void MessageOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MessageOptions)
GOOGLE_DCHECK_NE(&from, this);
const MessageOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const MessageOptions>(
+ ::google::protobuf::DynamicCastToGenerated<MessageOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MessageOptions)
@@ -9189,7 +11190,7 @@ void MessageOptions::MergeFrom(const MessageOptions& from) {
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 15u) {
+ if (cached_has_bits & 0x0000000fu) {
if (cached_has_bits & 0x00000001u) {
message_set_wire_format_ = from.message_set_wire_format_;
}
@@ -9250,19 +11251,19 @@ void MessageOptions::UnsafeArenaSwap(MessageOptions* other) {
}
void MessageOptions::InternalSwap(MessageOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&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_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata MessageOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -9270,6 +11271,28 @@ void MessageOptions::InternalSwap(MessageOptions* other) {
void FieldOptions::InitAsDefaultInstance() {
}
+class FieldOptions::HasBitSetters {
+ public:
+ static void set_has_ctype(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_packed(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_jstype(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000020u;
+ }
+ static void set_has_lazy(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+ static void set_has_deprecated(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_weak(FieldOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FieldOptions::kCtypeFieldNumber;
const int FieldOptions::kPackedFieldNumber;
@@ -9282,8 +11305,6 @@ const int FieldOptions::kUninterpretedOptionFieldNumber;
FieldOptions::FieldOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldOptions)
}
@@ -9292,7 +11313,6 @@ FieldOptions::FieldOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions)
@@ -9311,6 +11331,8 @@ FieldOptions::FieldOptions(const FieldOptions& from)
}
void FieldOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
::memset(&ctype_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&jstype_) -
reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
@@ -9329,18 +11351,13 @@ void FieldOptions::ArenaDtor(void* object) {
FieldOptions* _this = reinterpret_cast< FieldOptions* >(object);
(void)_this;
}
-void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FieldOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FieldOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FieldOptions& FieldOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FieldOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FieldOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -9354,7 +11371,7 @@ void FieldOptions::Clear() {
_extensions_.Clear();
uninterpreted_option_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x0000003fu) {
::memset(&ctype_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&jstype_) -
reinterpret_cast<char*>(&ctype_)) + sizeof(jstype_));
@@ -9363,9 +11380,139 @@ void FieldOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FieldOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FieldOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::FieldOptions_CType_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(1, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::FieldOptions_CType value = static_cast<::google::protobuf::FieldOptions_CType>(val);
+ msg->set_ctype(value);
+ break;
+ }
+ // optional bool packed = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_packed(value);
+ break;
+ }
+ // optional bool deprecated = 3 [default = false];
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // optional bool lazy = 5 [default = false];
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_lazy(value);
+ break;
+ }
+ // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::FieldOptions_JSType_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(6, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::FieldOptions_JSType value = static_cast<::google::protobuf::FieldOptions_JSType>(val);
+ msg->set_jstype(value);
+ break;
+ }
+ // optional bool weak = 10 [default = false];
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 80) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_weak(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FieldOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldOptions)
for (;;) {
@@ -9375,9 +11522,8 @@ bool FieldOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -9385,7 +11531,7 @@ bool FieldOptions::MergePartialFromCodedStream(
set_ctype(static_cast< ::google::protobuf::FieldOptions_CType >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 1, static_cast< ::google::protobuf::uint64>(value));
+ 1, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -9395,9 +11541,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool packed = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_packed();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_packed(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &packed_)));
@@ -9409,9 +11554,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -9423,9 +11567,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool lazy = 5 [default = false];
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- set_has_lazy();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
+ HasBitSetters::set_has_lazy(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &lazy_)));
@@ -9437,9 +11580,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -9447,7 +11589,7 @@ bool FieldOptions::MergePartialFromCodedStream(
set_jstype(static_cast< ::google::protobuf::FieldOptions_JSType >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 6, static_cast< ::google::protobuf::uint64>(value));
+ 6, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -9457,9 +11599,8 @@ bool FieldOptions::MergePartialFromCodedStream(
// optional bool weak = 10 [default = false];
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(80u /* 80 & 0xFF */)) {
- set_has_weak();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (80 & 0xFF)) {
+ HasBitSetters::set_has_weak(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &weak_)));
@@ -9471,8 +11612,7 @@ bool FieldOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -9506,6 +11646,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FieldOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -9556,8 +11697,7 @@ void FieldOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -9637,6 +11777,10 @@ size_t FieldOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -9648,35 +11792,36 @@ size_t FieldOptions::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 63u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x0000003fu) {
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
- if (has_ctype()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->ctype());
}
// optional bool packed = 2;
- if (has_packed()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 + 1;
}
// optional bool lazy = 5 [default = false];
- if (has_lazy()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 + 1;
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 + 1;
}
// optional bool weak = 10 [default = false];
- if (has_weak()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 1 + 1;
}
// optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL];
- if (has_jstype()) {
+ if (cached_has_bits & 0x00000020u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->jstype());
}
@@ -9691,7 +11836,7 @@ void FieldOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldOptions)
GOOGLE_DCHECK_NE(&from, this);
const FieldOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FieldOptions>(
+ ::google::protobuf::DynamicCastToGenerated<FieldOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldOptions)
@@ -9712,7 +11857,7 @@ void FieldOptions::MergeFrom(const FieldOptions& from) {
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x0000003fu) {
if (cached_has_bits & 0x00000001u) {
ctype_ = from.ctype_;
}
@@ -9779,6 +11924,9 @@ void FieldOptions::UnsafeArenaSwap(FieldOptions* other) {
}
void FieldOptions::InternalSwap(FieldOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(ctype_, other->ctype_);
swap(packed_, other->packed_);
@@ -9786,14 +11934,11 @@ void FieldOptions::InternalSwap(FieldOptions* other) {
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_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata FieldOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -9801,14 +11946,16 @@ void FieldOptions::InternalSwap(FieldOptions* other) {
void OneofOptions::InitAsDefaultInstance() {
}
+class OneofOptions::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int OneofOptions::kUninterpretedOptionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
OneofOptions::OneofOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofOptions)
}
@@ -9817,7 +11964,6 @@ OneofOptions::OneofOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions)
@@ -9833,6 +11979,8 @@ OneofOptions::OneofOptions(const OneofOptions& from)
}
void OneofOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
}
OneofOptions::~OneofOptions() {
@@ -9848,18 +11996,13 @@ void OneofOptions::ArenaDtor(void* object) {
OneofOptions* _this = reinterpret_cast< OneofOptions* >(object);
(void)_this;
}
-void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void OneofOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void OneofOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const OneofOptions& OneofOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_OneofOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_OneofOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -9876,9 +12019,71 @@ void OneofOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* OneofOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<OneofOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool OneofOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.OneofOptions)
for (;;) {
@@ -9888,8 +12093,7 @@ bool OneofOptions::MergePartialFromCodedStream(
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 */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -9923,6 +12127,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void OneofOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -9940,8 +12145,7 @@ void OneofOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -9988,6 +12192,10 @@ size_t OneofOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -10008,7 +12216,7 @@ void OneofOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofOptions)
GOOGLE_DCHECK_NE(&from, this);
const OneofOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const OneofOptions>(
+ ::google::protobuf::DynamicCastToGenerated<OneofOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.OneofOptions)
@@ -10074,15 +12282,15 @@ void OneofOptions::UnsafeArenaSwap(OneofOptions* other) {
}
void OneofOptions::InternalSwap(OneofOptions* other) {
using std::swap;
- CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
_extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
}
::google::protobuf::Metadata OneofOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -10090,6 +12298,16 @@ void OneofOptions::InternalSwap(OneofOptions* other) {
void EnumOptions::InitAsDefaultInstance() {
}
+class EnumOptions::HasBitSetters {
+ public:
+ static void set_has_allow_alias(EnumOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_deprecated(EnumOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumOptions::kAllowAliasFieldNumber;
const int EnumOptions::kDeprecatedFieldNumber;
@@ -10098,8 +12316,6 @@ const int EnumOptions::kUninterpretedOptionFieldNumber;
EnumOptions::EnumOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumOptions)
}
@@ -10108,7 +12324,6 @@ EnumOptions::EnumOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions)
@@ -10127,6 +12342,8 @@ EnumOptions::EnumOptions(const EnumOptions& from)
}
void EnumOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
::memset(&allow_alias_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&deprecated_) -
reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_));
@@ -10145,18 +12362,13 @@ void EnumOptions::ArenaDtor(void* object) {
EnumOptions* _this = reinterpret_cast< EnumOptions* >(object);
(void)_this;
}
-void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const EnumOptions& EnumOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -10176,9 +12388,91 @@ void EnumOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional bool allow_alias = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_allow_alias(value);
+ break;
+ }
+ // optional bool deprecated = 3 [default = false];
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumOptions)
for (;;) {
@@ -10188,9 +12482,8 @@ bool EnumOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool allow_alias = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_allow_alias();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_allow_alias(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &allow_alias_)));
@@ -10202,9 +12495,8 @@ bool EnumOptions::MergePartialFromCodedStream(
// optional bool deprecated = 3 [default = false];
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -10216,8 +12508,7 @@ bool EnumOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -10251,6 +12542,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -10279,8 +12571,7 @@ void EnumOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -10338,6 +12629,10 @@ size_t EnumOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -10349,14 +12644,15 @@ size_t EnumOptions::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional bool allow_alias = 2;
- if (has_allow_alias()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 + 1;
}
// optional bool deprecated = 3 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 + 1;
}
@@ -10370,7 +12666,7 @@ void EnumOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumOptions)
GOOGLE_DCHECK_NE(&from, this);
const EnumOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const EnumOptions>(
+ ::google::protobuf::DynamicCastToGenerated<EnumOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumOptions)
@@ -10391,7 +12687,7 @@ void EnumOptions::MergeFrom(const EnumOptions& from) {
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
allow_alias_ = from.allow_alias_;
}
@@ -10446,17 +12742,17 @@ void EnumOptions::UnsafeArenaSwap(EnumOptions* other) {
}
void EnumOptions::InternalSwap(EnumOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&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_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata EnumOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -10464,6 +12760,13 @@ void EnumOptions::InternalSwap(EnumOptions* other) {
void EnumValueOptions::InitAsDefaultInstance() {
}
+class EnumValueOptions::HasBitSetters {
+ public:
+ static void set_has_deprecated(EnumValueOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumValueOptions::kDeprecatedFieldNumber;
const int EnumValueOptions::kUninterpretedOptionFieldNumber;
@@ -10471,8 +12774,6 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber;
EnumValueOptions::EnumValueOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions)
}
@@ -10481,7 +12782,6 @@ EnumValueOptions::EnumValueOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions)
@@ -10498,6 +12798,8 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
}
void EnumValueOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
deprecated_ = false;
}
@@ -10514,18 +12816,13 @@ void EnumValueOptions::ArenaDtor(void* object) {
EnumValueOptions* _this = reinterpret_cast< EnumValueOptions* >(object);
(void)_this;
}
-void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumValueOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumValueOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const EnumValueOptions& EnumValueOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_EnumValueOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumValueOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -10543,9 +12840,81 @@ void EnumValueOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumValueOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumValueOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional bool deprecated = 1 [default = false];
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumValueOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValueOptions)
for (;;) {
@@ -10555,9 +12924,8 @@ bool EnumValueOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 1 [default = false];
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -10569,8 +12937,7 @@ bool EnumValueOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -10604,6 +12971,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumValueOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -10627,8 +12995,7 @@ void EnumValueOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -10681,6 +13048,10 @@ size_t EnumValueOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -10693,7 +13064,8 @@ size_t EnumValueOptions::ByteSizeLong() const {
}
// optional bool deprecated = 1 [default = false];
- if (has_deprecated()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 + 1;
}
@@ -10706,7 +13078,7 @@ void EnumValueOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueOptions)
GOOGLE_DCHECK_NE(&from, this);
const EnumValueOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const EnumValueOptions>(
+ ::google::protobuf::DynamicCastToGenerated<EnumValueOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumValueOptions)
@@ -10775,16 +13147,16 @@ void EnumValueOptions::UnsafeArenaSwap(EnumValueOptions* other) {
}
void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(deprecated_, other->deprecated_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata EnumValueOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -10792,6 +13164,13 @@ void EnumValueOptions::InternalSwap(EnumValueOptions* other) {
void ServiceOptions::InitAsDefaultInstance() {
}
+class ServiceOptions::HasBitSetters {
+ public:
+ static void set_has_deprecated(ServiceOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ServiceOptions::kDeprecatedFieldNumber;
const int ServiceOptions::kUninterpretedOptionFieldNumber;
@@ -10799,8 +13178,6 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber;
ServiceOptions::ServiceOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions)
}
@@ -10809,7 +13186,6 @@ ServiceOptions::ServiceOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions)
@@ -10826,6 +13202,8 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from)
}
void ServiceOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
deprecated_ = false;
}
@@ -10842,18 +13220,13 @@ void ServiceOptions::ArenaDtor(void* object) {
ServiceOptions* _this = reinterpret_cast< ServiceOptions* >(object);
(void)_this;
}
-void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void ServiceOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void ServiceOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const ServiceOptions& ServiceOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_ServiceOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ServiceOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -10871,9 +13244,81 @@ void ServiceOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ServiceOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<ServiceOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional bool deprecated = 33 [default = false];
+ case 33: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ServiceOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ServiceOptions)
for (;;) {
@@ -10883,9 +13328,8 @@ bool ServiceOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 33 [default = false];
case 33: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (264 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -10897,8 +13341,7 @@ bool ServiceOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -10932,6 +13375,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ServiceOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -10955,8 +13399,7 @@ void ServiceOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -11009,6 +13452,10 @@ size_t ServiceOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -11021,7 +13468,8 @@ size_t ServiceOptions::ByteSizeLong() const {
}
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000001u) {
total_size += 2 + 1;
}
@@ -11034,7 +13482,7 @@ void ServiceOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceOptions)
GOOGLE_DCHECK_NE(&from, this);
const ServiceOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const ServiceOptions>(
+ ::google::protobuf::DynamicCastToGenerated<ServiceOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ServiceOptions)
@@ -11103,16 +13551,16 @@ void ServiceOptions::UnsafeArenaSwap(ServiceOptions* other) {
}
void ServiceOptions::InternalSwap(ServiceOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&other->uninterpreted_option_));
swap(deprecated_, other->deprecated_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata ServiceOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -11120,6 +13568,16 @@ void ServiceOptions::InternalSwap(ServiceOptions* other) {
void MethodOptions::InitAsDefaultInstance() {
}
+class MethodOptions::HasBitSetters {
+ public:
+ static void set_has_deprecated(MethodOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_idempotency_level(MethodOptions* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MethodOptions::kDeprecatedFieldNumber;
const int MethodOptions::kIdempotencyLevelFieldNumber;
@@ -11128,8 +13586,6 @@ const int MethodOptions::kUninterpretedOptionFieldNumber;
MethodOptions::MethodOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodOptions)
}
@@ -11138,7 +13594,6 @@ MethodOptions::MethodOptions(::google::protobuf::Arena* arena)
_extensions_(arena),
_internal_metadata_(arena),
uninterpreted_option_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions)
@@ -11157,6 +13612,8 @@ MethodOptions::MethodOptions(const MethodOptions& from)
}
void MethodOptions::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
::memset(&deprecated_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&idempotency_level_) -
reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
@@ -11175,18 +13632,13 @@ void MethodOptions::ArenaDtor(void* object) {
MethodOptions* _this = reinterpret_cast< MethodOptions* >(object);
(void)_this;
}
-void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void MethodOptions::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void MethodOptions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const MethodOptions& MethodOptions::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_MethodOptions.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_MethodOptions_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -11200,7 +13652,7 @@ void MethodOptions::Clear() {
_extensions_.Clear();
uninterpreted_option_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
::memset(&deprecated_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&idempotency_level_) -
reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_));
@@ -11209,9 +13661,95 @@ void MethodOptions::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* MethodOptions::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<MethodOptions*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // optional bool deprecated = 33 [default = false];
+ case 33: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_deprecated(value);
+ break;
+ }
+ // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
+ case 34: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (!::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(val)) {
+ ::google::protobuf::internal::WriteVarint(34, val, msg->mutable_unknown_fields());
+ break;
+ }
+ ::google::protobuf::MethodOptions_IdempotencyLevel value = static_cast<::google::protobuf::MethodOptions_IdempotencyLevel>(val);
+ msg->set_idempotency_level(value);
+ break;
+ }
+ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
+ case 999: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption::_InternalParse;
+ object = msg->add_uninterpreted_option();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 65535) == 16058 && (ptr += 2));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ if ((8000u <= tag)) {
+ auto res = msg->_extensions_.ParseField(tag, {_InternalParse, msg}, ptr, end,
+ internal_default_instance(), &msg->_internal_metadata_, ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ continue;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool MethodOptions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.MethodOptions)
for (;;) {
@@ -11221,9 +13759,8 @@ bool MethodOptions::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional bool deprecated = 33 [default = false];
case 33: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 264 & 0xFF */)) {
- set_has_deprecated();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (264 & 0xFF)) {
+ HasBitSetters::set_has_deprecated(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
@@ -11235,9 +13772,8 @@ bool MethodOptions::MergePartialFromCodedStream(
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
case 34: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 272 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (272 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -11245,7 +13781,7 @@ bool MethodOptions::MergePartialFromCodedStream(
set_idempotency_level(static_cast< ::google::protobuf::MethodOptions_IdempotencyLevel >(value));
} else {
mutable_unknown_fields()->AddVarint(
- 34, static_cast< ::google::protobuf::uint64>(value));
+ 34, static_cast<::google::protobuf::uint64>(value));
}
} else {
goto handle_unusual;
@@ -11255,8 +13791,7 @@ bool MethodOptions::MergePartialFromCodedStream(
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
case 999: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 7994 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (7994 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_uninterpreted_option()));
} else {
@@ -11290,6 +13825,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void MethodOptions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -11319,8 +13855,7 @@ void MethodOptions::SerializeWithCachedSizes(
}
// Extension range [1000, 536870912)
- _extensions_.SerializeWithCachedSizes(
- 1000, 536870912, output);
+ _extensions_.SerializeWithCachedSizes(1000, 536870912, output);
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
@@ -11379,6 +13914,10 @@ size_t MethodOptions::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
{
unsigned int count = static_cast<unsigned int>(this->uninterpreted_option_size());
@@ -11390,14 +13929,15 @@ size_t MethodOptions::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional bool deprecated = 33 [default = false];
- if (has_deprecated()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 2 + 1;
}
// optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN];
- if (has_idempotency_level()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 2 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->idempotency_level());
}
@@ -11412,7 +13952,7 @@ void MethodOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodOptions)
GOOGLE_DCHECK_NE(&from, this);
const MethodOptions* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const MethodOptions>(
+ ::google::protobuf::DynamicCastToGenerated<MethodOptions>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.MethodOptions)
@@ -11433,7 +13973,7 @@ void MethodOptions::MergeFrom(const MethodOptions& from) {
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
deprecated_ = from.deprecated_;
}
@@ -11488,17 +14028,17 @@ void MethodOptions::UnsafeArenaSwap(MethodOptions* other) {
}
void MethodOptions::InternalSwap(MethodOptions* other) {
using std::swap;
+ _extensions_.Swap(&other->_extensions_);
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&uninterpreted_option_)->InternalSwap(CastToBase(&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_);
- _extensions_.Swap(&other->_extensions_);
}
::google::protobuf::Metadata MethodOptions::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -11506,6 +14046,16 @@ void MethodOptions::InternalSwap(MethodOptions* other) {
void UninterpretedOption_NamePart::InitAsDefaultInstance() {
}
+class UninterpretedOption_NamePart::HasBitSetters {
+ public:
+ static void set_has_name_part(UninterpretedOption_NamePart* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_is_extension(UninterpretedOption_NamePart* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UninterpretedOption_NamePart::kNamePartFieldNumber;
const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
@@ -11513,15 +14063,12 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
UninterpretedOption_NamePart::UninterpretedOption_NamePart()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart)
}
UninterpretedOption_NamePart::UninterpretedOption_NamePart(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart)
@@ -11541,6 +14088,8 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp
}
void UninterpretedOption_NamePart::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base);
name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
is_extension_ = false;
}
@@ -11559,18 +14108,13 @@ 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::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void UninterpretedOption_NamePart::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption_NamePart.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_UninterpretedOption_NamePart_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -11590,9 +14134,72 @@ void UninterpretedOption_NamePart::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* UninterpretedOption_NamePart::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<UninterpretedOption_NamePart*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // required string name_part = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.NamePart.name_part");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_name_part();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // required bool is_extension = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_is_extension(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption.NamePart)
for (;;) {
@@ -11602,8 +14209,7 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required string name_part = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name_part()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -11618,9 +14224,8 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
// required bool is_extension = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- set_has_is_extension();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ HasBitSetters::set_has_is_extension(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &is_extension_)));
@@ -11649,6 +14254,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void UninterpretedOption_NamePart::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -11750,6 +14356,10 @@ size_t UninterpretedOption_NamePart::ByteSizeLong() const {
} else {
total_size += RequiredFieldsByteSizeFallback();
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
@@ -11759,7 +14369,7 @@ void UninterpretedOption_NamePart::MergeFrom(const ::google::protobuf::Message&
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption.NamePart)
GOOGLE_DCHECK_NE(&from, this);
const UninterpretedOption_NamePart* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const UninterpretedOption_NamePart>(
+ ::google::protobuf::DynamicCastToGenerated<UninterpretedOption_NamePart>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UninterpretedOption.NamePart)
@@ -11778,7 +14388,7 @@ void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart&
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_name_part(from.name_part());
}
@@ -11829,16 +14439,16 @@ void UninterpretedOption_NamePart::UnsafeArenaSwap(UninterpretedOption_NamePart*
}
void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
name_part_.Swap(&other->name_part_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(is_extension_, other->is_extension_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -11846,6 +14456,28 @@ void UninterpretedOption_NamePart::InternalSwap(UninterpretedOption_NamePart* ot
void UninterpretedOption::InitAsDefaultInstance() {
}
+class UninterpretedOption::HasBitSetters {
+ public:
+ static void set_has_identifier_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_positive_int_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000008u;
+ }
+ static void set_has_negative_int_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000010u;
+ }
+ static void set_has_double_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000020u;
+ }
+ static void set_has_string_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_aggregate_value(UninterpretedOption* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UninterpretedOption::kNameFieldNumber;
const int UninterpretedOption::kIdentifierValueFieldNumber;
@@ -11858,8 +14490,6 @@ const int UninterpretedOption::kAggregateValueFieldNumber;
UninterpretedOption::UninterpretedOption()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption)
}
@@ -11867,7 +14497,6 @@ UninterpretedOption::UninterpretedOption(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
name_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption)
@@ -11900,6 +14529,8 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
}
void UninterpretedOption::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base);
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -11924,18 +14555,13 @@ void UninterpretedOption::ArenaDtor(void* object) {
UninterpretedOption* _this = reinterpret_cast< UninterpretedOption* >(object);
(void)_this;
}
-void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void UninterpretedOption::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void UninterpretedOption::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const UninterpretedOption& UninterpretedOption::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_UninterpretedOption.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_UninterpretedOption_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -11948,7 +14574,7 @@ void UninterpretedOption::Clear() {
name_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
identifier_value_.ClearNonDefaultToEmpty();
}
@@ -11959,7 +14585,7 @@ void UninterpretedOption::Clear() {
aggregate_value_.ClearNonDefaultToEmpty();
}
}
- if (cached_has_bits & 56u) {
+ if (cached_has_bits & 0x00000038u) {
::memset(&positive_int_value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&double_value_) -
reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_));
@@ -11968,9 +14594,139 @@ void UninterpretedOption::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* UninterpretedOption::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<UninterpretedOption*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::UninterpretedOption_NamePart::_InternalParse;
+ object = msg->add_name();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // optional string identifier_value = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.identifier_value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_identifier_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional uint64 positive_int_value = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::uint64 value = val;
+ msg->set_positive_int_value(value);
+ break;
+ }
+ // optional int64 negative_int_value = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int64 value = val;
+ msg->set_negative_int_value(value);
+ break;
+ }
+ // optional double double_value = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 49) goto handle_unusual;
+ double val;
+ ::std::memcpy(&val, ptr, 8);
+ ptr += 8;
+ msg->set_double_value(val);
+ break;
+ }
+ // optional bytes string_value = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::StringParser;
+ ::std::string* str = msg->mutable_string_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ str->append(ptr, size);
+ ptr += size;
+ break;
+ }
+ // optional string aggregate_value = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 66) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.UninterpretedOption.aggregate_value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_aggregate_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool UninterpretedOption::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UninterpretedOption)
for (;;) {
@@ -11980,8 +14736,7 @@ bool UninterpretedOption::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_name()));
} else {
@@ -11992,8 +14747,7 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional string identifier_value = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_identifier_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -12008,9 +14762,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional uint64 positive_int_value = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
- set_has_positive_int_value();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
+ HasBitSetters::set_has_positive_int_value(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &positive_int_value_)));
@@ -12022,9 +14775,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional int64 negative_int_value = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- set_has_negative_int_value();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
+ HasBitSetters::set_has_negative_int_value(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &negative_int_value_)));
@@ -12036,9 +14788,8 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional double double_value = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) {
- set_has_double_value();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (49 & 0xFF)) {
+ HasBitSetters::set_has_double_value(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &double_value_)));
@@ -12050,8 +14801,7 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional bytes string_value = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_string_value()));
} else {
@@ -12062,8 +14812,7 @@ bool UninterpretedOption::MergePartialFromCodedStream(
// optional string aggregate_value = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (66 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_aggregate_value()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -12095,6 +14844,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void UninterpretedOption::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -12237,6 +14987,10 @@ size_t UninterpretedOption::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
{
unsigned int count = static_cast<unsigned int>(this->name_size());
@@ -12248,44 +15002,45 @@ size_t UninterpretedOption::ByteSizeLong() const {
}
}
- if (_has_bits_[0 / 32] & 63u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x0000003fu) {
// optional string identifier_value = 3;
- if (has_identifier_value()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->identifier_value());
}
// optional bytes string_value = 7;
- if (has_string_value()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::BytesSize(
this->string_value());
}
// optional string aggregate_value = 8;
- if (has_aggregate_value()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->aggregate_value());
}
// optional uint64 positive_int_value = 4;
- if (has_positive_int_value()) {
+ if (cached_has_bits & 0x00000008u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->positive_int_value());
}
// optional int64 negative_int_value = 5;
- if (has_negative_int_value()) {
+ if (cached_has_bits & 0x00000010u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->negative_int_value());
}
// optional double double_value = 6;
- if (has_double_value()) {
+ if (cached_has_bits & 0x00000020u) {
total_size += 1 + 8;
}
@@ -12299,7 +15054,7 @@ void UninterpretedOption::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption)
GOOGLE_DCHECK_NE(&from, this);
const UninterpretedOption* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const UninterpretedOption>(
+ ::google::protobuf::DynamicCastToGenerated<UninterpretedOption>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UninterpretedOption)
@@ -12319,7 +15074,7 @@ void UninterpretedOption::MergeFrom(const UninterpretedOption& from) {
name_.MergeFrom(from.name_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 63u) {
+ if (cached_has_bits & 0x0000003fu) {
if (cached_has_bits & 0x00000001u) {
set_identifier_value(from.identifier_value());
}
@@ -12382,6 +15137,8 @@ void UninterpretedOption::UnsafeArenaSwap(UninterpretedOption* other) {
}
void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
CastToBase(&name_)->InternalSwap(CastToBase(&other->name_));
identifier_value_.Swap(&other->identifier_value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
@@ -12392,13 +15149,11 @@ void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
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_);
}
::google::protobuf::Metadata UninterpretedOption::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -12406,6 +15161,16 @@ void UninterpretedOption::InternalSwap(UninterpretedOption* other) {
void SourceCodeInfo_Location::InitAsDefaultInstance() {
}
+class SourceCodeInfo_Location::HasBitSetters {
+ public:
+ static void set_has_leading_comments(SourceCodeInfo_Location* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_trailing_comments(SourceCodeInfo_Location* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceCodeInfo_Location::kPathFieldNumber;
const int SourceCodeInfo_Location::kSpanFieldNumber;
@@ -12416,8 +15181,6 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber;
SourceCodeInfo_Location::SourceCodeInfo_Location()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location)
}
@@ -12427,7 +15190,6 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(::google::protobuf::Arena* aren
path_(arena),
span_(arena),
leading_detached_comments_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location)
@@ -12454,6 +15216,8 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location&
}
void SourceCodeInfo_Location::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base);
leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -12473,18 +15237,13 @@ 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::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void SourceCodeInfo_Location::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* SourceCodeInfo_Location::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo_Location.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_SourceCodeInfo_Location_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -12499,7 +15258,7 @@ void SourceCodeInfo_Location::Clear() {
span_.Clear();
leading_detached_comments_.Clear();
cached_has_bits = _has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
leading_comments_.ClearNonDefaultToEmpty();
}
@@ -12511,9 +15270,143 @@ void SourceCodeInfo_Location::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* SourceCodeInfo_Location::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<SourceCodeInfo_Location*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated int32 path = 1 [packed = true];
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) == 10) {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::PackedInt32Parser;
+ object = msg->mutable_path();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ } else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ do {
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->add_path(value);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1));
+ break;
+ }
+ // repeated int32 span = 2 [packed = true];
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) == 18) {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::PackedInt32Parser;
+ object = msg->mutable_span();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ } else if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ do {
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->add_span(value);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 16 && (ptr += 1));
+ break;
+ }
+ // optional string leading_comments = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.leading_comments");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_leading_comments();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional string trailing_comments = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.trailing_comments");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_trailing_comments();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated string leading_detached_comments = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.SourceCodeInfo.Location.leading_detached_comments");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->add_leading_detached_comments();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 50 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SourceCodeInfo_Location::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo.Location)
for (;;) {
@@ -12523,14 +15416,11 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int32 path = 1 [packed = true];
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_path())));
- } else if (
- static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ } else if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 10u, input, this->mutable_path())));
@@ -12542,14 +15432,11 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// repeated int32 span = 2 [packed = true];
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_span())));
- } else if (
- static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
+ } else if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 18u, input, this->mutable_span())));
@@ -12561,8 +15448,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// optional string leading_comments = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_leading_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -12577,8 +15463,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// optional string trailing_comments = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_trailing_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -12593,8 +15478,7 @@ bool SourceCodeInfo_Location::MergePartialFromCodedStream(
// repeated string leading_detached_comments = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_leading_detached_comments()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -12627,6 +15511,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -12637,8 +15522,8 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
// 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(static_cast< ::google::protobuf::uint32>(
- _path_cached_byte_size_));
+ output->WriteVarint32(_path_cached_byte_size_.load(
+ std::memory_order_relaxed));
}
for (int i = 0, n = this->path_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
@@ -12648,8 +15533,8 @@ 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(static_cast< ::google::protobuf::uint32>(
- _span_cached_byte_size_));
+ output->WriteVarint32(_span_cached_byte_size_.load(
+ std::memory_order_relaxed));
}
for (int i = 0, n = this->span_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
@@ -12708,8 +15593,8 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- static_cast< ::google::protobuf::int32>(
- _path_cached_byte_size_), target);
+ _path_cached_byte_size_.load(std::memory_order_relaxed),
+ target);
target = ::google::protobuf::internal::WireFormatLite::
WriteInt32NoTagToArray(this->path_, target);
}
@@ -12721,8 +15606,8 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- static_cast< ::google::protobuf::int32>(
- _span_cached_byte_size_), target);
+ _span_cached_byte_size_.load(std::memory_order_relaxed),
+ target);
target = ::google::protobuf::internal::WireFormatLite::
WriteInt32NoTagToArray(this->span_, target);
}
@@ -12777,6 +15662,10 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
{
size_t data_size = ::google::protobuf::internal::WireFormatLite::
@@ -12784,12 +15673,11 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
- static_cast< ::google::protobuf::int32>(data_size));
+ static_cast<::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _path_cached_byte_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _path_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
total_size += data_size;
}
@@ -12800,12 +15688,11 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
- static_cast< ::google::protobuf::int32>(data_size));
+ static_cast<::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _span_cached_byte_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _span_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
total_size += data_size;
}
@@ -12817,16 +15704,17 @@ size_t SourceCodeInfo_Location::ByteSizeLong() const {
this->leading_detached_comments(i));
}
- if (_has_bits_[0 / 32] & 3u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000003u) {
// optional string leading_comments = 3;
- if (has_leading_comments()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->leading_comments());
}
// optional string trailing_comments = 4;
- if (has_trailing_comments()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->trailing_comments());
@@ -12842,7 +15730,7 @@ void SourceCodeInfo_Location::MergeFrom(const ::google::protobuf::Message& from)
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo.Location)
GOOGLE_DCHECK_NE(&from, this);
const SourceCodeInfo_Location* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const SourceCodeInfo_Location>(
+ ::google::protobuf::DynamicCastToGenerated<SourceCodeInfo_Location>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceCodeInfo.Location)
@@ -12864,7 +15752,7 @@ void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) {
span_.MergeFrom(from.span_);
leading_detached_comments_.MergeFrom(from.leading_detached_comments_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 3u) {
+ if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
set_leading_comments(from.leading_comments());
}
@@ -12913,6 +15801,8 @@ void SourceCodeInfo_Location::UnsafeArenaSwap(SourceCodeInfo_Location* other) {
}
void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
path_.InternalSwap(&other->path_);
span_.InternalSwap(&other->span_);
leading_detached_comments_.InternalSwap(CastToBase(&other->leading_detached_comments_));
@@ -12920,13 +15810,11 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
GetArenaNoVirtual());
trailing_comments_.Swap(&other->trailing_comments_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata SourceCodeInfo_Location::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -12934,14 +15822,16 @@ void SourceCodeInfo_Location::InternalSwap(SourceCodeInfo_Location* other) {
void SourceCodeInfo::InitAsDefaultInstance() {
}
+class SourceCodeInfo::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceCodeInfo::kLocationFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SourceCodeInfo::SourceCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo)
}
@@ -12949,7 +15839,6 @@ SourceCodeInfo::SourceCodeInfo(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
location_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo)
@@ -12964,6 +15853,8 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from)
}
void SourceCodeInfo::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
}
SourceCodeInfo::~SourceCodeInfo() {
@@ -12979,18 +15870,13 @@ void SourceCodeInfo::ArenaDtor(void* object) {
SourceCodeInfo* _this = reinterpret_cast< SourceCodeInfo* >(object);
(void)_this;
}
-void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void SourceCodeInfo::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void SourceCodeInfo::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const SourceCodeInfo& SourceCodeInfo::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_SourceCodeInfo.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_SourceCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -13006,9 +15892,64 @@ void SourceCodeInfo::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* SourceCodeInfo::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<SourceCodeInfo*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.SourceCodeInfo.Location location = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::SourceCodeInfo_Location::_InternalParse;
+ object = msg->add_location();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SourceCodeInfo::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceCodeInfo)
for (;;) {
@@ -13018,8 +15959,7 @@ bool SourceCodeInfo::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_location()));
} else {
@@ -13047,6 +15987,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SourceCodeInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -13102,6 +16043,10 @@ size_t SourceCodeInfo::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
{
unsigned int count = static_cast<unsigned int>(this->location_size());
@@ -13122,7 +16067,7 @@ void SourceCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
const SourceCodeInfo* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const SourceCodeInfo>(
+ ::google::protobuf::DynamicCastToGenerated<SourceCodeInfo>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceCodeInfo)
@@ -13182,14 +16127,14 @@ void SourceCodeInfo::UnsafeArenaSwap(SourceCodeInfo* other) {
}
void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
using std::swap;
- CastToBase(&location_)->InternalSwap(CastToBase(&other->location_));
- swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ CastToBase(&location_)->InternalSwap(CastToBase(&other->location_));
}
::google::protobuf::Metadata SourceCodeInfo::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -13197,6 +16142,19 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) {
void GeneratedCodeInfo_Annotation::InitAsDefaultInstance() {
}
+class GeneratedCodeInfo_Annotation::HasBitSetters {
+ public:
+ static void set_has_source_file(GeneratedCodeInfo_Annotation* msg) {
+ msg->_has_bits_[0] |= 0x00000001u;
+ }
+ static void set_has_begin(GeneratedCodeInfo_Annotation* msg) {
+ msg->_has_bits_[0] |= 0x00000002u;
+ }
+ static void set_has_end(GeneratedCodeInfo_Annotation* msg) {
+ msg->_has_bits_[0] |= 0x00000004u;
+ }
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GeneratedCodeInfo_Annotation::kPathFieldNumber;
const int GeneratedCodeInfo_Annotation::kSourceFileFieldNumber;
@@ -13206,8 +16164,6 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber;
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
@@ -13215,7 +16171,6 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::google::protobuf::A
: ::google::protobuf::Message(),
_internal_metadata_(arena),
path_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation)
@@ -13238,6 +16193,8 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn
}
void GeneratedCodeInfo_Annotation::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base);
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&begin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
@@ -13258,18 +16215,13 @@ 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::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo_Annotation.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_GeneratedCodeInfo_Annotation_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -13285,7 +16237,7 @@ void GeneratedCodeInfo_Annotation::Clear() {
if (cached_has_bits & 0x00000001u) {
source_file_.ClearNonDefaultToEmpty();
}
- if (cached_has_bits & 6u) {
+ if (cached_has_bits & 0x00000006u) {
::memset(&begin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&end_) -
reinterpret_cast<char*>(&begin_)) + sizeof(end_));
@@ -13294,9 +16246,105 @@ void GeneratedCodeInfo_Annotation::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* GeneratedCodeInfo_Annotation::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<GeneratedCodeInfo_Annotation*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated int32 path = 1 [packed = true];
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) == 10) {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::PackedInt32Parser;
+ object = msg->mutable_path();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ } else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ do {
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->add_path(value);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1));
+ break;
+ }
+ // optional string source_file = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.GeneratedCodeInfo.Annotation.source_file");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8Verify;
+ ::std::string* str = msg->mutable_source_file();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // optional int32 begin = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_begin(value);
+ break;
+ }
+ // optional int32 end = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_end(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo.Annotation)
for (;;) {
@@ -13306,14 +16354,11 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int32 path = 1 [packed = true];
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, this->mutable_path())));
- } else if (
- static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ } else if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
1, 10u, input, this->mutable_path())));
@@ -13325,8 +16370,7 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional string source_file = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_source_file()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
@@ -13341,9 +16385,8 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional int32 begin = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
- set_has_begin();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
+ HasBitSetters::set_has_begin(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &begin_)));
@@ -13355,9 +16398,8 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
// optional int32 end = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
- set_has_end();
+ if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
+ HasBitSetters::set_has_end(this);
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
@@ -13386,6 +16428,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -13396,8 +16439,8 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
// 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(static_cast< ::google::protobuf::uint32>(
- _path_cached_byte_size_));
+ output->WriteVarint32(_path_cached_byte_size_.load(
+ std::memory_order_relaxed));
}
for (int i = 0, n = this->path_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteInt32NoTag(
@@ -13446,8 +16489,8 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
- static_cast< ::google::protobuf::int32>(
- _path_cached_byte_size_), target);
+ _path_cached_byte_size_.load(std::memory_order_relaxed),
+ target);
target = ::google::protobuf::internal::WireFormatLite::
WriteInt32NoTagToArray(this->path_, target);
}
@@ -13491,6 +16534,10 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated int32 path = 1 [packed = true];
{
size_t data_size = ::google::protobuf::internal::WireFormatLite::
@@ -13498,32 +16545,32 @@ size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const {
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
- static_cast< ::google::protobuf::int32>(data_size));
+ static_cast<::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _path_cached_byte_size_ = cached_size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ _path_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
total_size += data_size;
}
- if (_has_bits_[0 / 32] & 7u) {
+ cached_has_bits = _has_bits_[0];
+ if (cached_has_bits & 0x00000007u) {
// optional string source_file = 2;
- if (has_source_file()) {
+ if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->source_file());
}
// optional int32 begin = 3;
- if (has_begin()) {
+ if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->begin());
}
// optional int32 end = 4;
- if (has_end()) {
+ if (cached_has_bits & 0x00000004u) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->end());
@@ -13539,7 +16586,7 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const ::google::protobuf::Message&
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
GOOGLE_DCHECK_NE(&from, this);
const GeneratedCodeInfo_Annotation* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const GeneratedCodeInfo_Annotation>(
+ ::google::protobuf::DynamicCastToGenerated<GeneratedCodeInfo_Annotation>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.GeneratedCodeInfo.Annotation)
@@ -13559,7 +16606,7 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation&
path_.MergeFrom(from.path_);
cached_has_bits = from._has_bits_[0];
- if (cached_has_bits & 7u) {
+ if (cached_has_bits & 0x00000007u) {
if (cached_has_bits & 0x00000001u) {
set_source_file(from.source_file());
}
@@ -13612,18 +16659,18 @@ void GeneratedCodeInfo_Annotation::UnsafeArenaSwap(GeneratedCodeInfo_Annotation*
}
void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
path_.InternalSwap(&other->path_);
source_file_.Swap(&other->source_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(begin_, other->begin_);
swap(end_, other->end_);
- swap(_has_bits_[0], other->_has_bits_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -13631,14 +16678,16 @@ void GeneratedCodeInfo_Annotation::InternalSwap(GeneratedCodeInfo_Annotation* ot
void GeneratedCodeInfo::InitAsDefaultInstance() {
}
+class GeneratedCodeInfo::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int GeneratedCodeInfo::kAnnotationFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
GeneratedCodeInfo::GeneratedCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo)
}
@@ -13646,7 +16695,6 @@ GeneratedCodeInfo::GeneratedCodeInfo(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
annotation_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo)
@@ -13661,6 +16709,8 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from)
}
void GeneratedCodeInfo::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
}
GeneratedCodeInfo::~GeneratedCodeInfo() {
@@ -13676,18 +16726,13 @@ void GeneratedCodeInfo::ArenaDtor(void* object) {
GeneratedCodeInfo* _this = reinterpret_cast< GeneratedCodeInfo* >(object);
(void)_this;
}
-void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void GeneratedCodeInfo::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void GeneratedCodeInfo::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
- ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_GeneratedCodeInfo.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_GeneratedCodeInfo_google_2fprotobuf_2fdescriptor_2eproto.base);
return *internal_default_instance();
}
@@ -13703,9 +16748,64 @@ void GeneratedCodeInfo::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* GeneratedCodeInfo::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<GeneratedCodeInfo*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::GeneratedCodeInfo_Annotation::_InternalParse;
+ object = msg->add_annotation();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool GeneratedCodeInfo::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.GeneratedCodeInfo)
for (;;) {
@@ -13715,8 +16815,7 @@ bool GeneratedCodeInfo::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_annotation()));
} else {
@@ -13744,6 +16843,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void GeneratedCodeInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -13799,6 +16899,10 @@ size_t GeneratedCodeInfo::ByteSizeLong() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
{
unsigned int count = static_cast<unsigned int>(this->annotation_size());
@@ -13819,7 +16923,7 @@ void GeneratedCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo)
GOOGLE_DCHECK_NE(&from, this);
const GeneratedCodeInfo* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const GeneratedCodeInfo>(
+ ::google::protobuf::DynamicCastToGenerated<GeneratedCodeInfo>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.GeneratedCodeInfo)
@@ -13879,14 +16983,14 @@ void GeneratedCodeInfo::UnsafeArenaSwap(GeneratedCodeInfo* other) {
}
void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
using std::swap;
- CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_));
- swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(_has_bits_[0], other->_has_bits_[0]);
+ CastToBase(&annotation_)->InternalSwap(CastToBase(&other->annotation_));
}
::google::protobuf::Metadata GeneratedCodeInfo::GetMetadata() const {
- protobuf_google_2fprotobuf_2fdescriptor_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fdescriptor_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fdescriptor_2eproto[kIndexInFileMessages];
}
@@ -13895,88 +16999,89 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorSet >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorSet >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FileDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FileDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ExtensionRange >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ExtensionRange >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto_ReservedRange >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto_ReservedRange >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::DescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::DescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage< ::google::protobuf::ExtensionRangeOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::ExtensionRangeOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::FieldDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FieldDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::OneofDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::OneofDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto_EnumReservedRange >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumValueDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::ServiceDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::ServiceDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage< ::google::protobuf::MethodDescriptorProto >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::MethodDescriptorProto >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FileOptions* Arena::CreateMaybeMessage< ::google::protobuf::FileOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FileOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage< ::google::protobuf::MessageOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::MessageOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage< ::google::protobuf::FieldOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FieldOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage< ::google::protobuf::OneofOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::OneofOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage< ::google::protobuf::EnumValueOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumValueOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage< ::google::protobuf::ServiceOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::ServiceOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage< ::google::protobuf::MethodOptions >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::MethodOptions >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption_NamePart >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption_NamePart >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage< ::google::protobuf::UninterpretedOption >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::UninterpretedOption >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo_Location >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo_Location >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::SourceCodeInfo >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::SourceCodeInfo >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo_Annotation >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo_Annotation >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage< ::google::protobuf::GeneratedCodeInfo >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::GeneratedCodeInfo >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index d7b2270b..c4b83652 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -32,134 +33,132 @@
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fdescriptor_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fdescriptor_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[27]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fdescriptor_2eproto();
namespace google {
namespace protobuf {
class DescriptorProto;
class DescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_;
class DescriptorProto_ExtensionRange;
class DescriptorProto_ExtensionRangeDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_;
+PROTOBUF_EXPORT extern DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_;
class DescriptorProto_ReservedRange;
class DescriptorProto_ReservedRangeDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_;
+PROTOBUF_EXPORT extern DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_;
class EnumDescriptorProto;
class EnumDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_;
class EnumDescriptorProto_EnumReservedRange;
class EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_;
+PROTOBUF_EXPORT extern EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_;
class EnumOptions;
class EnumOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_;
+PROTOBUF_EXPORT extern EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_;
class EnumValueDescriptorProto;
class EnumValueDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_;
class EnumValueOptions;
class EnumValueOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_;
+PROTOBUF_EXPORT extern EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_;
class ExtensionRangeOptions;
class ExtensionRangeOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_;
+PROTOBUF_EXPORT extern ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_;
class FieldDescriptorProto;
class FieldDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_;
class FieldOptions;
class FieldOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_;
+PROTOBUF_EXPORT extern FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_;
class FileDescriptorProto;
class FileDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_;
class FileDescriptorSet;
class FileDescriptorSetDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_;
+PROTOBUF_EXPORT extern FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_;
class FileOptions;
class FileOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_;
+PROTOBUF_EXPORT extern FileOptionsDefaultTypeInternal _FileOptions_default_instance_;
class GeneratedCodeInfo;
class GeneratedCodeInfoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_;
+PROTOBUF_EXPORT extern GeneratedCodeInfoDefaultTypeInternal _GeneratedCodeInfo_default_instance_;
class GeneratedCodeInfo_Annotation;
class GeneratedCodeInfo_AnnotationDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_;
+PROTOBUF_EXPORT extern GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_;
class MessageOptions;
class MessageOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_;
+PROTOBUF_EXPORT extern MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_;
class MethodDescriptorProto;
class MethodDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_;
class MethodOptions;
class MethodOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_;
+PROTOBUF_EXPORT extern MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_;
class OneofDescriptorProto;
class OneofDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_;
class OneofOptions;
class OneofOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_;
+PROTOBUF_EXPORT extern OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_;
class ServiceDescriptorProto;
class ServiceDescriptorProtoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_;
+PROTOBUF_EXPORT extern ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_;
class ServiceOptions;
class ServiceOptionsDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_;
+PROTOBUF_EXPORT extern ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_;
class SourceCodeInfo;
class SourceCodeInfoDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_;
+PROTOBUF_EXPORT extern SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_;
class SourceCodeInfo_Location;
class SourceCodeInfo_LocationDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_;
+PROTOBUF_EXPORT extern SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_;
class UninterpretedOption;
class UninterpretedOptionDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_;
+PROTOBUF_EXPORT extern UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_;
class UninterpretedOption_NamePart;
class UninterpretedOption_NamePartDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*);
+PROTOBUF_EXPORT extern UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ExtensionRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ExtensionRange>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::DescriptorProto_ReservedRange* Arena::CreateMaybeMessage<::google::protobuf::DescriptorProto_ReservedRange>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumDescriptorProto_EnumReservedRange* Arena::CreateMaybeMessage<::google::protobuf::EnumDescriptorProto_EnumReservedRange>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumValueDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::EnumValueDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumValueOptions* Arena::CreateMaybeMessage<::google::protobuf::EnumValueOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::ExtensionRangeOptions* Arena::CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FieldDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FieldDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FieldOptions* Arena::CreateMaybeMessage<::google::protobuf::FieldOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FileDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FileDescriptorSet* Arena::CreateMaybeMessage<::google::protobuf::FileDescriptorSet>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FileOptions* Arena::CreateMaybeMessage<::google::protobuf::FileOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::GeneratedCodeInfo_Annotation* Arena::CreateMaybeMessage<::google::protobuf::GeneratedCodeInfo_Annotation>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::MessageOptions* Arena::CreateMaybeMessage<::google::protobuf::MessageOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::MethodDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::MethodDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::MethodOptions* Arena::CreateMaybeMessage<::google::protobuf::MethodOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::OneofDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::OneofDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::OneofOptions* Arena::CreateMaybeMessage<::google::protobuf::OneofOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::ServiceDescriptorProto* Arena::CreateMaybeMessage<::google::protobuf::ServiceDescriptorProto>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::ServiceOptions* Arena::CreateMaybeMessage<::google::protobuf::ServiceOptions>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::SourceCodeInfo_Location* Arena::CreateMaybeMessage<::google::protobuf::SourceCodeInfo_Location>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::UninterpretedOption* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::UninterpretedOption_NamePart* Arena::CreateMaybeMessage<::google::protobuf::UninterpretedOption_NamePart>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -185,12 +184,12 @@ enum FieldDescriptorProto_Type {
FieldDescriptorProto_Type_TYPE_SINT32 = 17,
FieldDescriptorProto_Type_TYPE_SINT64 = 18
};
-LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value);
+PROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value);
const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MIN = FieldDescriptorProto_Type_TYPE_DOUBLE;
const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MAX = FieldDescriptorProto_Type_TYPE_SINT64;
const int FieldDescriptorProto_Type_Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor();
inline const ::std::string& FieldDescriptorProto_Type_Name(FieldDescriptorProto_Type value) {
return ::google::protobuf::internal::NameOfEnum(
FieldDescriptorProto_Type_descriptor(), value);
@@ -205,12 +204,12 @@ enum FieldDescriptorProto_Label {
FieldDescriptorProto_Label_LABEL_REQUIRED = 2,
FieldDescriptorProto_Label_LABEL_REPEATED = 3
};
-LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value);
+PROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value);
const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MIN = FieldDescriptorProto_Label_LABEL_OPTIONAL;
const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MAX = FieldDescriptorProto_Label_LABEL_REPEATED;
const int FieldDescriptorProto_Label_Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor();
inline const ::std::string& FieldDescriptorProto_Label_Name(FieldDescriptorProto_Label value) {
return ::google::protobuf::internal::NameOfEnum(
FieldDescriptorProto_Label_descriptor(), value);
@@ -225,12 +224,12 @@ enum FileOptions_OptimizeMode {
FileOptions_OptimizeMode_CODE_SIZE = 2,
FileOptions_OptimizeMode_LITE_RUNTIME = 3
};
-LIBPROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value);
+PROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value);
const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MIN = FileOptions_OptimizeMode_SPEED;
const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MAX = FileOptions_OptimizeMode_LITE_RUNTIME;
const int FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor();
inline const ::std::string& FileOptions_OptimizeMode_Name(FileOptions_OptimizeMode value) {
return ::google::protobuf::internal::NameOfEnum(
FileOptions_OptimizeMode_descriptor(), value);
@@ -245,12 +244,12 @@ enum FieldOptions_CType {
FieldOptions_CType_CORD = 1,
FieldOptions_CType_STRING_PIECE = 2
};
-LIBPROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value);
+PROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value);
const FieldOptions_CType FieldOptions_CType_CType_MIN = FieldOptions_CType_STRING;
const FieldOptions_CType FieldOptions_CType_CType_MAX = FieldOptions_CType_STRING_PIECE;
const int FieldOptions_CType_CType_ARRAYSIZE = FieldOptions_CType_CType_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor();
inline const ::std::string& FieldOptions_CType_Name(FieldOptions_CType value) {
return ::google::protobuf::internal::NameOfEnum(
FieldOptions_CType_descriptor(), value);
@@ -265,12 +264,12 @@ enum FieldOptions_JSType {
FieldOptions_JSType_JS_STRING = 1,
FieldOptions_JSType_JS_NUMBER = 2
};
-LIBPROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value);
+PROTOBUF_EXPORT bool FieldOptions_JSType_IsValid(int value);
const FieldOptions_JSType FieldOptions_JSType_JSType_MIN = FieldOptions_JSType_JS_NORMAL;
const FieldOptions_JSType FieldOptions_JSType_JSType_MAX = FieldOptions_JSType_JS_NUMBER;
const int FieldOptions_JSType_JSType_ARRAYSIZE = FieldOptions_JSType_JSType_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor();
inline const ::std::string& FieldOptions_JSType_Name(FieldOptions_JSType value) {
return ::google::protobuf::internal::NameOfEnum(
FieldOptions_JSType_descriptor(), value);
@@ -285,12 +284,12 @@ enum MethodOptions_IdempotencyLevel {
MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS = 1,
MethodOptions_IdempotencyLevel_IDEMPOTENT = 2
};
-LIBPROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value);
+PROTOBUF_EXPORT bool MethodOptions_IdempotencyLevel_IsValid(int value);
const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN;
const MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX = MethodOptions_IdempotencyLevel_IDEMPOTENT;
const int MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* MethodOptions_IdempotencyLevel_descriptor();
inline const ::std::string& MethodOptions_IdempotencyLevel_Name(MethodOptions_IdempotencyLevel value) {
return ::google::protobuf::internal::NameOfEnum(
MethodOptions_IdempotencyLevel_descriptor(), value);
@@ -302,7 +301,7 @@ inline bool MethodOptions_IdempotencyLevel_Parse(
}
// ===================================================================
-class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ {
+class PROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorSet) */ {
public:
FileDescriptorSet();
virtual ~FileDescriptorSet();
@@ -341,7 +340,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FileDescriptorSet& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -375,8 +376,13 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -422,6 +428,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
// @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -430,11 +437,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ {
+class PROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ {
public:
FileDescriptorProto();
virtual ~FileDescriptorProto();
@@ -473,7 +480,9 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FileDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -507,8 +516,13 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -559,8 +573,8 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
#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();
+ const ::google::protobuf::RepeatedPtrField<::std::string>& dependency() const;
+ ::google::protobuf::RepeatedPtrField<::std::string>* mutable_dependency();
// repeated .google.protobuf.DescriptorProto message_type = 4;
int message_type_size() const;
@@ -648,11 +662,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -672,11 +686,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::std::string* mutable_package();
::std::string* release_package();
void set_allocated_package(::std::string* package);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -696,11 +710,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::std::string* mutable_syntax();
::std::string* release_syntax();
void set_allocated_syntax(::std::string* syntax);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -710,9 +724,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 8;
- private:
- const ::google::protobuf::FileOptions& _internal_options() const;
- public:
const ::google::protobuf::FileOptions& options() const;
::google::protobuf::FileOptions* release_options();
::google::protobuf::FileOptions* mutable_options();
@@ -725,9 +736,6 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
bool has_source_code_info() const;
void clear_source_code_info();
static const int kSourceCodeInfoFieldNumber = 9;
- private:
- const ::google::protobuf::SourceCodeInfo& _internal_source_code_info() const;
- public:
const ::google::protobuf::SourceCodeInfo& source_code_info() const;
::google::protobuf::SourceCodeInfo* release_source_code_info();
::google::protobuf::SourceCodeInfo* mutable_source_code_info();
@@ -738,16 +746,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
// @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_package();
- void clear_has_package();
- void set_has_options();
- void clear_has_options();
- void set_has_source_code_info();
- void clear_has_source_code_info();
- void set_has_syntax();
- void clear_has_syntax();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -755,7 +754,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
typedef void DestructorSkippable_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- ::google::protobuf::RepeatedPtrField< ::std::string> dependency_;
+ ::google::protobuf::RepeatedPtrField<::std::string> dependency_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto > service_;
@@ -767,11 +766,11 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::google::protobuf::internal::ArenaStringPtr syntax_;
::google::protobuf::FileOptions* options_;
::google::protobuf::SourceCodeInfo* source_code_info_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ {
+class PROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ {
public:
DescriptorProto_ExtensionRange();
virtual ~DescriptorProto_ExtensionRange();
@@ -810,7 +809,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const DescriptorProto_ExtensionRange& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -844,8 +845,13 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -881,9 +887,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- private:
- const ::google::protobuf::ExtensionRangeOptions& _internal_options() const;
- public:
const ::google::protobuf::ExtensionRangeOptions& options() const;
::google::protobuf::ExtensionRangeOptions* release_options();
::google::protobuf::ExtensionRangeOptions* mutable_options();
@@ -908,12 +911,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
// @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange)
private:
- void set_has_start();
- void clear_has_start();
- void set_has_end();
- void clear_has_end();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -924,11 +922,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
::google::protobuf::ExtensionRangeOptions* options_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ {
+class PROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ {
public:
DescriptorProto_ReservedRange();
virtual ~DescriptorProto_ReservedRange();
@@ -967,7 +965,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const DescriptorProto_ReservedRange& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1001,8 +1001,13 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1050,10 +1055,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
// @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ReservedRange)
private:
- void set_has_start();
- void clear_has_start();
- void set_has_end();
- void clear_has_end();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1063,11 +1065,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ {
+class PROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ {
public:
DescriptorProto();
virtual ~DescriptorProto();
@@ -1106,7 +1108,9 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const DescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1140,8 +1144,13 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1279,8 +1288,8 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
#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();
+ 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;
@@ -1296,11 +1305,11 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1310,9 +1319,6 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 7;
- private:
- const ::google::protobuf::MessageOptions& _internal_options() const;
- public:
const ::google::protobuf::MessageOptions& options() const;
::google::protobuf::MessageOptions* release_options();
::google::protobuf::MessageOptions* mutable_options();
@@ -1323,10 +1329,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
// @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1341,14 +1344,14 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
::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::RepeatedPtrField<::std::string> reserved_name_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::MessageOptions* options_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ {
+class PROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ExtensionRangeOptions) */ {
public:
ExtensionRangeOptions();
virtual ~ExtensionRangeOptions();
@@ -1387,7 +1390,9 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const ExtensionRangeOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1421,8 +1426,13 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1469,6 +1479,7 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ExtensionRangeOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.ExtensionRangeOptions)
private:
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -1479,11 +1490,11 @@ class LIBPROTOBUF_EXPORT ExtensionRangeOptions : public ::google::protobuf::Mess
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ {
+class PROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ {
public:
FieldDescriptorProto();
virtual ~FieldDescriptorProto();
@@ -1522,7 +1533,9 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FieldDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1556,8 +1569,13 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1689,11 +1707,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1713,11 +1731,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::std::string* mutable_extendee();
::std::string* release_extendee();
void set_allocated_extendee(::std::string* extendee);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1737,11 +1755,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::std::string* mutable_type_name();
::std::string* release_type_name();
void set_allocated_type_name(::std::string* type_name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1761,11 +1779,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1785,11 +1803,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1799,9 +1817,6 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 8;
- private:
- const ::google::protobuf::FieldOptions& _internal_options() const;
- public:
const ::google::protobuf::FieldOptions& options() const;
::google::protobuf::FieldOptions* release_options();
::google::protobuf::FieldOptions* mutable_options();
@@ -1840,26 +1855,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
// @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_number();
- void clear_has_number();
- void set_has_label();
- void clear_has_label();
- void set_has_type();
- void clear_has_type();
- void set_has_type_name();
- void clear_has_type_name();
- void set_has_extendee();
- void clear_has_extendee();
- void set_has_default_value();
- void clear_has_default_value();
- void set_has_oneof_index();
- void clear_has_oneof_index();
- void set_has_json_name();
- void clear_has_json_name();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1877,11 +1873,11 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
::google::protobuf::int32 oneof_index_;
int label_;
int type_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ {
+class PROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ {
public:
OneofDescriptorProto();
virtual ~OneofDescriptorProto();
@@ -1920,7 +1916,9 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const OneofDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1954,8 +1952,13 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2001,11 +2004,11 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2015,9 +2018,6 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 2;
- private:
- const ::google::protobuf::OneofOptions& _internal_options() const;
- public:
const ::google::protobuf::OneofOptions& options() const;
::google::protobuf::OneofOptions* release_options();
::google::protobuf::OneofOptions* mutable_options();
@@ -2028,10 +2028,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
// @@protoc_insertion_point(class_scope:google.protobuf.OneofDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2041,11 +2038,11 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::OneofOptions* options_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ {
+class PROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto.EnumReservedRange) */ {
public:
EnumDescriptorProto_EnumReservedRange();
virtual ~EnumDescriptorProto_EnumReservedRange();
@@ -2084,7 +2081,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumDescriptorProto_EnumReservedRange& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -2118,8 +2117,13 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2167,10 +2171,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
// @@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();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2180,11 +2181,11 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto_EnumReservedRange : public ::google
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ {
+class PROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ {
public:
EnumDescriptorProto();
virtual ~EnumDescriptorProto();
@@ -2223,7 +2224,9 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -2257,8 +2260,13 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2335,8 +2343,8 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
#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();
+ 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;
@@ -2352,11 +2360,11 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2366,9 +2374,6 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- private:
- const ::google::protobuf::EnumOptions& _internal_options() const;
- public:
const ::google::protobuf::EnumOptions& options() const;
::google::protobuf::EnumOptions* release_options();
::google::protobuf::EnumOptions* mutable_options();
@@ -2379,10 +2384,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
// @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2392,14 +2394,14 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
mutable ::google::protobuf::internal::CachedSize _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::RepeatedPtrField<::std::string> reserved_name_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumOptions* options_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ {
+class PROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ {
public:
EnumValueDescriptorProto();
virtual ~EnumValueDescriptorProto();
@@ -2438,7 +2440,9 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumValueDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -2472,8 +2476,13 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2519,11 +2528,11 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2533,9 +2542,6 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- private:
- const ::google::protobuf::EnumValueOptions& _internal_options() const;
- public:
const ::google::protobuf::EnumValueOptions& options() const;
::google::protobuf::EnumValueOptions* release_options();
::google::protobuf::EnumValueOptions* mutable_options();
@@ -2553,12 +2559,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_number();
- void clear_has_number();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2569,11 +2570,11 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumValueOptions* options_;
::google::protobuf::int32 number_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ {
+class PROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ {
public:
ServiceDescriptorProto();
virtual ~ServiceDescriptorProto();
@@ -2612,7 +2613,9 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const ServiceDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -2646,8 +2649,13 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2705,11 +2713,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2719,9 +2727,6 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
- private:
- const ::google::protobuf::ServiceOptions& _internal_options() const;
- public:
const ::google::protobuf::ServiceOptions& options() const;
::google::protobuf::ServiceOptions* release_options();
::google::protobuf::ServiceOptions* mutable_options();
@@ -2732,10 +2737,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
// @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_options();
- void clear_has_options();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2746,11 +2748,11 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::ServiceOptions* options_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ {
+class PROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ {
public:
MethodDescriptorProto();
virtual ~MethodDescriptorProto();
@@ -2789,7 +2791,9 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const MethodDescriptorProto& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -2823,8 +2827,13 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -2870,11 +2879,11 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2894,11 +2903,11 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2918,11 +2927,11 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -2932,9 +2941,6 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
bool has_options() const;
void clear_options();
static const int kOptionsFieldNumber = 4;
- private:
- const ::google::protobuf::MethodOptions& _internal_options() const;
- public:
const ::google::protobuf::MethodOptions& options() const;
::google::protobuf::MethodOptions* release_options();
::google::protobuf::MethodOptions* mutable_options();
@@ -2959,18 +2965,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
// @@protoc_insertion_point(class_scope:google.protobuf.MethodDescriptorProto)
private:
- void set_has_name();
- void clear_has_name();
- void set_has_input_type();
- void clear_has_input_type();
- void set_has_output_type();
- void clear_has_output_type();
- void set_has_options();
- void clear_has_options();
- void set_has_client_streaming();
- void clear_has_client_streaming();
- void set_has_server_streaming();
- void clear_has_server_streaming();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -2984,11 +2979,11 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::google::protobuf::MethodOptions* options_;
bool client_streaming_;
bool server_streaming_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ {
+class PROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ {
public:
FileOptions();
virtual ~FileOptions();
@@ -3027,7 +3022,9 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FileOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -3061,8 +3058,13 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -3148,11 +3150,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3172,11 +3174,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3196,11 +3198,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3220,11 +3222,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3244,11 +3246,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3268,11 +3270,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3292,11 +3294,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3316,11 +3318,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -3340,11 +3342,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::std::string* mutable_php_metadata_namespace();
::std::string* release_php_metadata_namespace();
void set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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_metadata_namespace();
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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_metadata_namespace(
@@ -3364,11 +3366,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::std::string* mutable_ruby_package();
::std::string* release_ruby_package();
void set_allocated_ruby_package(::std::string* ruby_package);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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_ruby_package();
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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_ruby_package(
@@ -3382,11 +3384,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void set_java_multiple_files(bool value);
// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
- GOOGLE_PROTOBUF_DEPRECATED_ATTR bool has_java_generate_equals_and_hash() const;
- GOOGLE_PROTOBUF_DEPRECATED_ATTR void clear_java_generate_equals_and_hash();
- GOOGLE_PROTOBUF_DEPRECATED_ATTR static const int kJavaGenerateEqualsAndHashFieldNumber = 20;
- GOOGLE_PROTOBUF_DEPRECATED_ATTR bool java_generate_equals_and_hash() const;
- GOOGLE_PROTOBUF_DEPRECATED_ATTR void set_java_generate_equals_and_hash(bool value);
+ PROTOBUF_DEPRECATED bool has_java_generate_equals_and_hash() const;
+ PROTOBUF_DEPRECATED void clear_java_generate_equals_and_hash();
+ PROTOBUF_DEPRECATED static const int kJavaGenerateEqualsAndHashFieldNumber = 20;
+ PROTOBUF_DEPRECATED bool java_generate_equals_and_hash() const;
+ PROTOBUF_DEPRECATED void set_java_generate_equals_and_hash(bool value);
// optional bool java_string_check_utf8 = 27 [default = false];
bool has_java_string_check_utf8() const;
@@ -3447,46 +3449,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FileOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.FileOptions)
private:
- void set_has_java_package();
- void clear_has_java_package();
- void set_has_java_outer_classname();
- void clear_has_java_outer_classname();
- void set_has_java_multiple_files();
- void clear_has_java_multiple_files();
- void set_has_java_generate_equals_and_hash();
- void clear_has_java_generate_equals_and_hash();
- void set_has_java_string_check_utf8();
- void clear_has_java_string_check_utf8();
- void set_has_optimize_for();
- void clear_has_optimize_for();
- void set_has_go_package();
- void clear_has_go_package();
- void set_has_cc_generic_services();
- void clear_has_cc_generic_services();
- void set_has_java_generic_services();
- 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();
- void clear_has_cc_enable_arenas();
- void set_has_objc_class_prefix();
- void clear_has_objc_class_prefix();
- void set_has_csharp_namespace();
- 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();
- void set_has_php_metadata_namespace();
- void clear_has_php_metadata_namespace();
- void set_has_ruby_package();
- void clear_has_ruby_package();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -3517,11 +3480,11 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool deprecated_;
bool cc_enable_arenas_;
int optimize_for_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ {
+class PROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ {
public:
MessageOptions();
virtual ~MessageOptions();
@@ -3560,7 +3523,9 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const MessageOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -3594,8 +3559,13 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -3670,14 +3640,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MessageOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions)
private:
- void set_has_message_set_wire_format();
- void clear_has_message_set_wire_format();
- void set_has_no_standard_descriptor_accessor();
- void clear_has_no_standard_descriptor_accessor();
- void set_has_deprecated();
- void clear_has_deprecated();
- void set_has_map_entry();
- void clear_has_map_entry();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -3692,11 +3655,11 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
bool no_standard_descriptor_accessor_;
bool deprecated_;
bool map_entry_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ {
+class PROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ {
public:
FieldOptions();
virtual ~FieldOptions();
@@ -3735,7 +3698,9 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FieldOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -3769,8 +3734,13 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -3915,18 +3885,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FieldOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions)
private:
- void set_has_ctype();
- void clear_has_ctype();
- void set_has_packed();
- void clear_has_packed();
- void set_has_jstype();
- void clear_has_jstype();
- void set_has_lazy();
- void clear_has_lazy();
- void set_has_deprecated();
- void clear_has_deprecated();
- void set_has_weak();
- void clear_has_weak();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -3943,11 +3902,11 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
bool deprecated_;
bool weak_;
int jstype_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ {
+class PROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ {
public:
OneofOptions();
virtual ~OneofOptions();
@@ -3986,7 +3945,9 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const OneofOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4020,8 +3981,13 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4068,6 +4034,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(OneofOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.OneofOptions)
private:
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -4078,11 +4045,11 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ {
+class PROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ {
public:
EnumOptions();
virtual ~EnumOptions();
@@ -4121,7 +4088,9 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4155,8 +4124,13 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4217,10 +4191,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions)
private:
- void set_has_allow_alias();
- void clear_has_allow_alias();
- void set_has_deprecated();
- void clear_has_deprecated();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -4233,11 +4204,11 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool allow_alias_;
bool deprecated_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ {
+class PROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ {
public:
EnumValueOptions();
virtual ~EnumValueOptions();
@@ -4276,7 +4247,9 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumValueOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4310,8 +4283,13 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4365,8 +4343,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumValueOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions)
private:
- void set_has_deprecated();
- void clear_has_deprecated();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -4378,11 +4355,11 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ {
+class PROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ {
public:
ServiceOptions();
virtual ~ServiceOptions();
@@ -4421,7 +4398,9 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const ServiceOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4455,8 +4434,13 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4510,8 +4494,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ServiceOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions)
private:
- void set_has_deprecated();
- void clear_has_deprecated();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -4523,11 +4506,11 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ {
+class PROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ {
public:
MethodOptions();
virtual ~MethodOptions();
@@ -4566,7 +4549,9 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const MethodOptions& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4600,8 +4585,13 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4690,10 +4680,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MethodOptions)
// @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions)
private:
- void set_has_deprecated();
- void clear_has_deprecated();
- void set_has_idempotency_level();
- void clear_has_idempotency_level();
+ class HasBitSetters;
::google::protobuf::internal::ExtensionSet _extensions_;
@@ -4706,11 +4693,11 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
int idempotency_level_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ {
+class PROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ {
public:
UninterpretedOption_NamePart();
virtual ~UninterpretedOption_NamePart();
@@ -4749,7 +4736,9 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const UninterpretedOption_NamePart& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4783,8 +4772,13 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -4830,11 +4824,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -4849,10 +4843,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
// @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption.NamePart)
private:
- void set_has_name_part();
- void clear_has_name_part();
- void set_has_is_extension();
- void clear_has_is_extension();
+ class HasBitSetters;
// helper for ByteSizeLong()
size_t RequiredFieldsByteSizeFallback() const;
@@ -4865,11 +4856,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_part_;
bool is_extension_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ {
+class PROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ {
public:
UninterpretedOption();
virtual ~UninterpretedOption();
@@ -4908,7 +4899,9 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const UninterpretedOption& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -4942,8 +4935,13 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -5003,11 +5001,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::std::string* mutable_identifier_value();
::std::string* release_identifier_value();
void set_allocated_identifier_value(::std::string* identifier_value);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5027,11 +5025,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5051,11 +5049,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5084,18 +5082,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
// @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption)
private:
- void set_has_identifier_value();
- void clear_has_identifier_value();
- void set_has_positive_int_value();
- void clear_has_positive_int_value();
- void set_has_negative_int_value();
- void clear_has_negative_int_value();
- void set_has_double_value();
- void clear_has_double_value();
- void set_has_string_value();
- void clear_has_string_value();
- void set_has_aggregate_value();
- void clear_has_aggregate_value();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -5110,11 +5097,11 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
::google::protobuf::uint64 positive_int_value_;
::google::protobuf::int64 negative_int_value_;
double double_value_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ {
+class PROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ {
public:
SourceCodeInfo_Location();
virtual ~SourceCodeInfo_Location();
@@ -5153,7 +5140,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const SourceCodeInfo_Location& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -5187,8 +5176,13 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -5263,8 +5257,8 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
#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();
+ 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;
@@ -5280,11 +5274,11 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5304,11 +5298,11 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::std::string* mutable_trailing_comments();
::std::string* release_trailing_comments();
void set_allocated_trailing_comments(::std::string* trailing_comments);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5316,10 +5310,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
// @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo.Location)
private:
- void set_has_leading_comments();
- void clear_has_leading_comments();
- void set_has_trailing_comments();
- void clear_has_trailing_comments();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -5328,17 +5319,17 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
- mutable int _path_cached_byte_size_;
+ mutable std::atomic<int> _path_cached_byte_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_;
- mutable int _span_cached_byte_size_;
- ::google::protobuf::RepeatedPtrField< ::std::string> leading_detached_comments_;
+ mutable std::atomic<int> _span_cached_byte_size_;
+ ::google::protobuf::RepeatedPtrField<::std::string> leading_detached_comments_;
::google::protobuf::internal::ArenaStringPtr leading_comments_;
::google::protobuf::internal::ArenaStringPtr trailing_comments_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ {
+class PROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ {
public:
SourceCodeInfo();
virtual ~SourceCodeInfo();
@@ -5377,7 +5368,9 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const SourceCodeInfo& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -5411,8 +5404,13 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -5460,6 +5458,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
// @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -5468,11 +5467,11 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ {
+class PROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ {
public:
GeneratedCodeInfo_Annotation();
virtual ~GeneratedCodeInfo_Annotation();
@@ -5511,7 +5510,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const GeneratedCodeInfo_Annotation& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -5545,8 +5546,13 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -5604,11 +5610,11 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -5630,12 +5636,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
// @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo.Annotation)
private:
- void set_has_source_file();
- void clear_has_source_file();
- void set_has_begin();
- void clear_has_begin();
- void set_has_end();
- void clear_has_end();
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -5644,15 +5645,15 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
- mutable int _path_cached_byte_size_;
+ mutable std::atomic<int> _path_cached_byte_size_;
::google::protobuf::internal::ArenaStringPtr source_file_;
::google::protobuf::int32 begin_;
::google::protobuf::int32 end_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ {
+class PROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ {
public:
GeneratedCodeInfo();
virtual ~GeneratedCodeInfo();
@@ -5691,7 +5692,9 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const GeneratedCodeInfo& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -5725,8 +5728,13 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -5774,6 +5782,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
// @@protoc_insertion_point(class_scope:google.protobuf.GeneratedCodeInfo)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -5782,7 +5791,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_;
- friend struct ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto;
};
// ===================================================================
@@ -5833,28 +5842,22 @@ FileDescriptorSet::file() const {
inline bool FileDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void FileDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void FileDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void FileDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& FileDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name)
return name_.Get();
}
inline void FileDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.name)
@@ -5862,20 +5865,20 @@ inline void FileDescriptorProto::set_name(::std::string&& value) {
#endif
inline void FileDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -5884,14 +5887,14 @@ inline ::std::string* FileDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -5900,7 +5903,7 @@ inline void FileDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -5908,9 +5911,9 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -5921,28 +5924,22 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_name(
inline bool FileDescriptorProto::has_package() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void FileDescriptorProto::set_has_package() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void FileDescriptorProto::clear_has_package() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void FileDescriptorProto::clear_package() {
package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_package();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& FileDescriptorProto::package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package)
return package_.Get();
}
inline void FileDescriptorProto::set_package(const ::std::string& value) {
- set_has_package();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
package_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.package)
@@ -5950,20 +5947,20 @@ inline void FileDescriptorProto::set_package(::std::string&& value) {
#endif
inline void FileDescriptorProto::set_package(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_package();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_package();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.package)
return package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -5972,14 +5969,14 @@ inline ::std::string* FileDescriptorProto::release_package() {
if (!has_package()) {
return NULL;
}
- clear_has_package();
+ _has_bits_[0] &= ~0x00000002u;
return package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_package(::std::string* package) {
if (package != NULL) {
- set_has_package();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_package();
+ _has_bits_[0] &= ~0x00000002u;
}
package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), package,
GetArenaNoVirtual());
@@ -5988,7 +5985,7 @@ inline void FileDescriptorProto::set_allocated_package(::std::string* 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();
+ _has_bits_[0] &= ~0x00000002u;
return package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -5996,9 +5993,9 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_package(
::std::string* package) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (package != NULL) {
- set_has_package();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_package();
+ _has_bits_[0] &= ~0x00000002u;
}
package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
package, GetArenaNoVirtual());
@@ -6063,12 +6060,12 @@ inline 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)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline const ::google::protobuf::RepeatedPtrField<::std::string>&
FileDescriptorProto::dependency() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.dependency)
return dependency_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::google::protobuf::RepeatedPtrField<::std::string>*
FileDescriptorProto::mutable_dependency() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.dependency)
return &dependency_;
@@ -6258,18 +6255,9 @@ FileDescriptorProto::extension() const {
inline bool FileDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void FileDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void FileDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void FileDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::FileOptions& FileDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000008u;
}
inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
const ::google::protobuf::FileOptions* p = options_;
@@ -6279,7 +6267,7 @@ inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() con
}
inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
::google::protobuf::FileOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -6289,13 +6277,13 @@ inline ::google::protobuf::FileOptions* FileDescriptorProto::release_options() {
}
inline ::google::protobuf::FileOptions* FileDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
::google::protobuf::FileOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::FileOptions>(GetArenaNoVirtual());
options_ = p;
@@ -6315,9 +6303,9 @@ inline void FileDescriptorProto::set_allocated_options(::google::protobuf::FileO
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.options)
@@ -6327,18 +6315,9 @@ inline void FileDescriptorProto::set_allocated_options(::google::protobuf::FileO
inline bool FileDescriptorProto::has_source_code_info() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void FileDescriptorProto::set_has_source_code_info() {
- _has_bits_[0] |= 0x00000010u;
-}
-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_->Clear();
- clear_has_source_code_info();
-}
-inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::_internal_source_code_info() const {
- return *source_code_info_;
+ _has_bits_[0] &= ~0x00000010u;
}
inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
const ::google::protobuf::SourceCodeInfo* p = source_code_info_;
@@ -6348,7 +6327,7 @@ inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_cod
}
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();
+ _has_bits_[0] &= ~0x00000010u;
::google::protobuf::SourceCodeInfo* temp = source_code_info_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -6358,13 +6337,13 @@ inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::release_source_c
}
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();
+ _has_bits_[0] &= ~0x00000010u;
::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();
+ _has_bits_[0] |= 0x00000010u;
if (source_code_info_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::SourceCodeInfo>(GetArenaNoVirtual());
source_code_info_ = p;
@@ -6384,9 +6363,9 @@ inline void FileDescriptorProto::set_allocated_source_code_info(::google::protob
source_code_info = ::google::protobuf::internal::GetOwnedMessage(
message_arena, source_code_info, submessage_arena);
}
- set_has_source_code_info();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_source_code_info();
+ _has_bits_[0] &= ~0x00000010u;
}
source_code_info_ = source_code_info;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.source_code_info)
@@ -6396,28 +6375,22 @@ inline void FileDescriptorProto::set_allocated_source_code_info(::google::protob
inline bool FileDescriptorProto::has_syntax() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void FileDescriptorProto::set_has_syntax() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void FileDescriptorProto::clear_has_syntax() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void FileDescriptorProto::clear_syntax() {
syntax_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_syntax();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& FileDescriptorProto::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax)
return syntax_.Get();
}
inline void FileDescriptorProto::set_syntax(const ::std::string& value) {
- set_has_syntax();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
syntax_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileDescriptorProto.syntax)
@@ -6425,20 +6398,20 @@ inline void FileDescriptorProto::set_syntax(::std::string&& value) {
#endif
inline void FileDescriptorProto::set_syntax(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_syntax();
+ _has_bits_[0] |= 0x00000004u;
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) {
- set_has_syntax();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.syntax)
return syntax_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -6447,14 +6420,14 @@ inline ::std::string* FileDescriptorProto::release_syntax() {
if (!has_syntax()) {
return NULL;
}
- clear_has_syntax();
+ _has_bits_[0] &= ~0x00000004u;
return syntax_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
if (syntax != NULL) {
- set_has_syntax();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_syntax();
+ _has_bits_[0] &= ~0x00000004u;
}
syntax_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), syntax,
GetArenaNoVirtual());
@@ -6463,7 +6436,7 @@ inline void FileDescriptorProto::set_allocated_syntax(::std::string* 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();
+ _has_bits_[0] &= ~0x00000004u;
return syntax_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -6471,9 +6444,9 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax(
::std::string* syntax) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (syntax != NULL) {
- set_has_syntax();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_syntax();
+ _has_bits_[0] &= ~0x00000004u;
}
syntax_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
syntax, GetArenaNoVirtual());
@@ -6488,22 +6461,16 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_syntax(
inline bool DescriptorProto_ExtensionRange::has_start() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void DescriptorProto_ExtensionRange::set_has_start() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void DescriptorProto_ExtensionRange::clear_has_start() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void DescriptorProto_ExtensionRange::clear_start() {
start_ = 0;
- clear_has_start();
+ _has_bits_[0] &= ~0x00000002u;
}
inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.start)
return start_;
}
inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) {
- set_has_start();
+ _has_bits_[0] |= 0x00000002u;
start_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.start)
}
@@ -6512,22 +6479,16 @@ inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32
inline bool DescriptorProto_ExtensionRange::has_end() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void DescriptorProto_ExtensionRange::set_has_end() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void DescriptorProto_ExtensionRange::clear_has_end() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void DescriptorProto_ExtensionRange::clear_end() {
end_ = 0;
- clear_has_end();
+ _has_bits_[0] &= ~0x00000004u;
}
inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.end)
return end_;
}
inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) {
- set_has_end();
+ _has_bits_[0] |= 0x00000004u;
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end)
}
@@ -6536,18 +6497,9 @@ inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 va
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::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_ExtensionRange::options() const {
const ::google::protobuf::ExtensionRangeOptions* p = options_;
@@ -6557,7 +6509,7 @@ inline const ::google::protobuf::ExtensionRangeOptions& DescriptorProto_Extensio
}
inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.ExtensionRange.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000001u;
::google::protobuf::ExtensionRangeOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -6567,13 +6519,13 @@ inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange
}
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();
+ _has_bits_[0] &= ~0x00000001u;
::google::protobuf::ExtensionRangeOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000001u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::ExtensionRangeOptions>(GetArenaNoVirtual());
options_ = p;
@@ -6593,9 +6545,9 @@ inline void DescriptorProto_ExtensionRange::set_allocated_options(::google::prot
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000001u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options)
@@ -6609,22 +6561,16 @@ inline void DescriptorProto_ExtensionRange::set_allocated_options(::google::prot
inline bool DescriptorProto_ReservedRange::has_start() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void DescriptorProto_ReservedRange::set_has_start() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void DescriptorProto_ReservedRange::clear_has_start() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void DescriptorProto_ReservedRange::clear_start() {
start_ = 0;
- clear_has_start();
+ _has_bits_[0] &= ~0x00000001u;
}
inline ::google::protobuf::int32 DescriptorProto_ReservedRange::start() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.start)
return start_;
}
inline void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 value) {
- set_has_start();
+ _has_bits_[0] |= 0x00000001u;
start_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.start)
}
@@ -6633,22 +6579,16 @@ inline void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 v
inline bool DescriptorProto_ReservedRange::has_end() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void DescriptorProto_ReservedRange::set_has_end() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void DescriptorProto_ReservedRange::clear_has_end() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void DescriptorProto_ReservedRange::clear_end() {
end_ = 0;
- clear_has_end();
+ _has_bits_[0] &= ~0x00000002u;
}
inline ::google::protobuf::int32 DescriptorProto_ReservedRange::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.end)
return end_;
}
inline void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 value) {
- set_has_end();
+ _has_bits_[0] |= 0x00000002u;
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.end)
}
@@ -6661,28 +6601,22 @@ inline void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 val
inline bool DescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void DescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void DescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void DescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& DescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name)
return name_.Get();
}
inline void DescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.DescriptorProto.name)
@@ -6690,20 +6624,20 @@ inline void DescriptorProto::set_name(::std::string&& value) {
#endif
inline void DescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -6712,14 +6646,14 @@ inline ::std::string* DescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void DescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -6728,7 +6662,7 @@ inline void DescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -6736,9 +6670,9 @@ inline void DescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -6929,18 +6863,9 @@ DescriptorProto::oneof_decl() const {
inline bool DescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void DescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void DescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void DescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::MessageOptions& DescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
const ::google::protobuf::MessageOptions* p = options_;
@@ -6950,7 +6875,7 @@ inline const ::google::protobuf::MessageOptions& DescriptorProto::options() cons
}
inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::MessageOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -6960,13 +6885,13 @@ inline ::google::protobuf::MessageOptions* DescriptorProto::release_options() {
}
inline ::google::protobuf::MessageOptions* DescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.DescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::MessageOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::MessageOptions>(GetArenaNoVirtual());
options_ = p;
@@ -6986,9 +6911,9 @@ inline void DescriptorProto::set_allocated_options(::google::protobuf::MessageOp
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.options)
@@ -7082,12 +7007,12 @@ inline 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)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline const ::google::protobuf::RepeatedPtrField<::std::string>&
DescriptorProto::reserved_name() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_name)
return reserved_name_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::google::protobuf::RepeatedPtrField<::std::string>*
DescriptorProto::mutable_reserved_name() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_name)
return &reserved_name_;
@@ -7135,28 +7060,22 @@ ExtensionRangeOptions::uninterpreted_option() const {
inline bool FieldDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void FieldDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void FieldDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void FieldDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& FieldDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name)
return name_.Get();
}
inline void FieldDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.name)
@@ -7164,20 +7083,20 @@ inline void FieldDescriptorProto::set_name(::std::string&& value) {
#endif
inline void FieldDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7186,14 +7105,14 @@ inline ::std::string* FieldDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -7202,7 +7121,7 @@ inline void FieldDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7210,9 +7129,9 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -7223,22 +7142,16 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_name(
inline bool FieldDescriptorProto::has_number() const {
return (_has_bits_[0] & 0x00000040u) != 0;
}
-inline void FieldDescriptorProto::set_has_number() {
- _has_bits_[0] |= 0x00000040u;
-}
-inline void FieldDescriptorProto::clear_has_number() {
- _has_bits_[0] &= ~0x00000040u;
-}
inline void FieldDescriptorProto::clear_number() {
number_ = 0;
- clear_has_number();
+ _has_bits_[0] &= ~0x00000040u;
}
inline ::google::protobuf::int32 FieldDescriptorProto::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.number)
return number_;
}
inline void FieldDescriptorProto::set_number(::google::protobuf::int32 value) {
- set_has_number();
+ _has_bits_[0] |= 0x00000040u;
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.number)
}
@@ -7247,15 +7160,9 @@ inline void FieldDescriptorProto::set_number(::google::protobuf::int32 value) {
inline bool FieldDescriptorProto::has_label() const {
return (_has_bits_[0] & 0x00000100u) != 0;
}
-inline void FieldDescriptorProto::set_has_label() {
- _has_bits_[0] |= 0x00000100u;
-}
-inline void FieldDescriptorProto::clear_has_label() {
- _has_bits_[0] &= ~0x00000100u;
-}
inline void FieldDescriptorProto::clear_label() {
label_ = 1;
- clear_has_label();
+ _has_bits_[0] &= ~0x00000100u;
}
inline ::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.label)
@@ -7263,7 +7170,7 @@ inline ::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::labe
}
inline void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) {
assert(::google::protobuf::FieldDescriptorProto_Label_IsValid(value));
- set_has_label();
+ _has_bits_[0] |= 0x00000100u;
label_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.label)
}
@@ -7272,15 +7179,9 @@ inline void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorP
inline bool FieldDescriptorProto::has_type() const {
return (_has_bits_[0] & 0x00000200u) != 0;
}
-inline void FieldDescriptorProto::set_has_type() {
- _has_bits_[0] |= 0x00000200u;
-}
-inline void FieldDescriptorProto::clear_has_type() {
- _has_bits_[0] &= ~0x00000200u;
-}
inline void FieldDescriptorProto::clear_type() {
type_ = 1;
- clear_has_type();
+ _has_bits_[0] &= ~0x00000200u;
}
inline ::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type)
@@ -7288,7 +7189,7 @@ inline ::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type(
}
inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) {
assert(::google::protobuf::FieldDescriptorProto_Type_IsValid(value));
- set_has_type();
+ _has_bits_[0] |= 0x00000200u;
type_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type)
}
@@ -7297,28 +7198,22 @@ inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorPr
inline bool FieldDescriptorProto::has_type_name() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void FieldDescriptorProto::set_has_type_name() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void FieldDescriptorProto::clear_has_type_name() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void FieldDescriptorProto::clear_type_name() {
type_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_type_name();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& FieldDescriptorProto::type_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name)
return type_name_.Get();
}
inline void FieldDescriptorProto::set_type_name(const ::std::string& value) {
- set_has_type_name();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
type_name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.type_name)
@@ -7326,20 +7221,20 @@ inline void FieldDescriptorProto::set_type_name(::std::string&& value) {
#endif
inline void FieldDescriptorProto::set_type_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_type_name();
+ _has_bits_[0] |= 0x00000004u;
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) {
- set_has_type_name();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.type_name)
return type_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7348,14 +7243,14 @@ inline ::std::string* FieldDescriptorProto::release_type_name() {
if (!has_type_name()) {
return NULL;
}
- clear_has_type_name();
+ _has_bits_[0] &= ~0x00000004u;
return type_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
if (type_name != NULL) {
- set_has_type_name();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_type_name();
+ _has_bits_[0] &= ~0x00000004u;
}
type_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_name,
GetArenaNoVirtual());
@@ -7364,7 +7259,7 @@ inline void FieldDescriptorProto::set_allocated_type_name(::std::string* type_na
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();
+ _has_bits_[0] &= ~0x00000004u;
return type_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7372,9 +7267,9 @@ 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();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_type_name();
+ _has_bits_[0] &= ~0x00000004u;
}
type_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
type_name, GetArenaNoVirtual());
@@ -7385,28 +7280,22 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_type_name(
inline bool FieldDescriptorProto::has_extendee() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void FieldDescriptorProto::set_has_extendee() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void FieldDescriptorProto::clear_has_extendee() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void FieldDescriptorProto::clear_extendee() {
extendee_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_extendee();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& FieldDescriptorProto::extendee() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee)
return extendee_.Get();
}
inline void FieldDescriptorProto::set_extendee(const ::std::string& value) {
- set_has_extendee();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
extendee_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.extendee)
@@ -7414,20 +7303,20 @@ inline void FieldDescriptorProto::set_extendee(::std::string&& value) {
#endif
inline void FieldDescriptorProto::set_extendee(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_extendee();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_extendee();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.extendee)
return extendee_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7436,14 +7325,14 @@ inline ::std::string* FieldDescriptorProto::release_extendee() {
if (!has_extendee()) {
return NULL;
}
- clear_has_extendee();
+ _has_bits_[0] &= ~0x00000002u;
return extendee_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
if (extendee != NULL) {
- set_has_extendee();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_extendee();
+ _has_bits_[0] &= ~0x00000002u;
}
extendee_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), extendee,
GetArenaNoVirtual());
@@ -7452,7 +7341,7 @@ inline void FieldDescriptorProto::set_allocated_extendee(::std::string* 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();
+ _has_bits_[0] &= ~0x00000002u;
return extendee_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7460,9 +7349,9 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee(
::std::string* extendee) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (extendee != NULL) {
- set_has_extendee();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_extendee();
+ _has_bits_[0] &= ~0x00000002u;
}
extendee_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
extendee, GetArenaNoVirtual());
@@ -7473,28 +7362,22 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_extendee(
inline bool FieldDescriptorProto::has_default_value() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void FieldDescriptorProto::set_has_default_value() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void FieldDescriptorProto::clear_has_default_value() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void FieldDescriptorProto::clear_default_value() {
default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_default_value();
+ _has_bits_[0] &= ~0x00000008u;
}
inline const ::std::string& FieldDescriptorProto::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value)
return default_value_.Get();
}
inline void FieldDescriptorProto::set_default_value(const ::std::string& value) {
- set_has_default_value();
+ _has_bits_[0] |= 0x00000008u;
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();
+ _has_bits_[0] |= 0x00000008u;
default_value_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.default_value)
@@ -7502,20 +7385,20 @@ inline void FieldDescriptorProto::set_default_value(::std::string&& value) {
#endif
inline void FieldDescriptorProto::set_default_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_default_value();
+ _has_bits_[0] |= 0x00000008u;
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) {
- set_has_default_value();
+ _has_bits_[0] |= 0x00000008u;
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();
+ _has_bits_[0] |= 0x00000008u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.default_value)
return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7524,14 +7407,14 @@ inline ::std::string* FieldDescriptorProto::release_default_value() {
if (!has_default_value()) {
return NULL;
}
- clear_has_default_value();
+ _has_bits_[0] &= ~0x00000008u;
return default_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
- set_has_default_value();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_default_value();
+ _has_bits_[0] &= ~0x00000008u;
}
default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value,
GetArenaNoVirtual());
@@ -7540,7 +7423,7 @@ inline void FieldDescriptorProto::set_allocated_default_value(::std::string* def
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();
+ _has_bits_[0] &= ~0x00000008u;
return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7548,9 +7431,9 @@ 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();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_default_value();
+ _has_bits_[0] &= ~0x00000008u;
}
default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
default_value, GetArenaNoVirtual());
@@ -7561,22 +7444,16 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_default_value(
inline bool FieldDescriptorProto::has_oneof_index() const {
return (_has_bits_[0] & 0x00000080u) != 0;
}
-inline void FieldDescriptorProto::set_has_oneof_index() {
- _has_bits_[0] |= 0x00000080u;
-}
-inline void FieldDescriptorProto::clear_has_oneof_index() {
- _has_bits_[0] &= ~0x00000080u;
-}
inline void FieldDescriptorProto::clear_oneof_index() {
oneof_index_ = 0;
- clear_has_oneof_index();
+ _has_bits_[0] &= ~0x00000080u;
}
inline ::google::protobuf::int32 FieldDescriptorProto::oneof_index() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.oneof_index)
return oneof_index_;
}
inline void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 value) {
- set_has_oneof_index();
+ _has_bits_[0] |= 0x00000080u;
oneof_index_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.oneof_index)
}
@@ -7585,28 +7462,22 @@ inline void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 valu
inline bool FieldDescriptorProto::has_json_name() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void FieldDescriptorProto::set_has_json_name() {
- _has_bits_[0] |= 0x00000010u;
-}
-inline void FieldDescriptorProto::clear_has_json_name() {
- _has_bits_[0] &= ~0x00000010u;
-}
inline void FieldDescriptorProto::clear_json_name() {
json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_json_name();
+ _has_bits_[0] &= ~0x00000010u;
}
inline const ::std::string& FieldDescriptorProto::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name)
return json_name_.Get();
}
inline void FieldDescriptorProto::set_json_name(const ::std::string& value) {
- set_has_json_name();
+ _has_bits_[0] |= 0x00000010u;
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();
+ _has_bits_[0] |= 0x00000010u;
json_name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FieldDescriptorProto.json_name)
@@ -7614,20 +7485,20 @@ inline void FieldDescriptorProto::set_json_name(::std::string&& value) {
#endif
inline void FieldDescriptorProto::set_json_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_json_name();
+ _has_bits_[0] |= 0x00000010u;
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) {
- set_has_json_name();
+ _has_bits_[0] |= 0x00000010u;
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();
+ _has_bits_[0] |= 0x00000010u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.json_name)
return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7636,14 +7507,14 @@ inline ::std::string* FieldDescriptorProto::release_json_name() {
if (!has_json_name()) {
return NULL;
}
- clear_has_json_name();
+ _has_bits_[0] &= ~0x00000010u;
return json_name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
- set_has_json_name();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_json_name();
+ _has_bits_[0] &= ~0x00000010u;
}
json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name,
GetArenaNoVirtual());
@@ -7652,7 +7523,7 @@ inline void FieldDescriptorProto::set_allocated_json_name(::std::string* json_na
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();
+ _has_bits_[0] &= ~0x00000010u;
return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7660,9 +7531,9 @@ 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();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_json_name();
+ _has_bits_[0] &= ~0x00000010u;
}
json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
json_name, GetArenaNoVirtual());
@@ -7673,18 +7544,9 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_json_name(
inline bool FieldDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
-inline void FieldDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000020u;
-}
-inline void FieldDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000020u;
-}
inline void FieldDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000020u;
}
inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
const ::google::protobuf::FieldOptions* p = options_;
@@ -7694,7 +7556,7 @@ inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() c
}
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000020u;
::google::protobuf::FieldOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -7704,13 +7566,13 @@ inline ::google::protobuf::FieldOptions* FieldDescriptorProto::release_options()
}
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FieldDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000020u;
::google::protobuf::FieldOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000020u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::FieldOptions>(GetArenaNoVirtual());
options_ = p;
@@ -7730,9 +7592,9 @@ inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::Fiel
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000020u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000020u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
@@ -7746,28 +7608,22 @@ inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::Fiel
inline bool OneofDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void OneofDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void OneofDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void OneofDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& OneofDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name)
return name_.Get();
}
inline void OneofDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.OneofDescriptorProto.name)
@@ -7775,20 +7631,20 @@ inline void OneofDescriptorProto::set_name(::std::string&& value) {
#endif
inline void OneofDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -7797,14 +7653,14 @@ inline ::std::string* OneofDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void OneofDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -7813,7 +7669,7 @@ inline void OneofDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -7821,9 +7677,9 @@ inline void OneofDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -7834,18 +7690,9 @@ inline void OneofDescriptorProto::unsafe_arena_set_allocated_name(
inline bool OneofDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void OneofDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void OneofDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void OneofDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
const ::google::protobuf::OneofOptions* p = options_;
@@ -7855,7 +7702,7 @@ inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() c
}
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::OneofOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -7865,13 +7712,13 @@ inline ::google::protobuf::OneofOptions* OneofDescriptorProto::release_options()
}
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.OneofDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::OneofOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::OneofOptions>(GetArenaNoVirtual());
options_ = p;
@@ -7891,9 +7738,9 @@ inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::Oneo
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options)
@@ -7907,22 +7754,16 @@ inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::Oneo
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();
+ _has_bits_[0] &= ~0x00000001u;
}
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();
+ _has_bits_[0] |= 0x00000001u;
start_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.start)
}
@@ -7931,22 +7772,16 @@ inline void EnumDescriptorProto_EnumReservedRange::set_start(::google::protobuf:
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();
+ _has_bits_[0] &= ~0x00000002u;
}
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();
+ _has_bits_[0] |= 0x00000002u;
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.EnumReservedRange.end)
}
@@ -7959,28 +7794,22 @@ inline void EnumDescriptorProto_EnumReservedRange::set_end(::google::protobuf::i
inline bool EnumDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void EnumDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void EnumDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void EnumDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& EnumDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name)
return name_.Get();
}
inline void EnumDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumDescriptorProto.name)
@@ -7988,20 +7817,20 @@ inline void EnumDescriptorProto::set_name(::std::string&& value) {
#endif
inline void EnumDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8010,14 +7839,14 @@ inline ::std::string* EnumDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -8026,7 +7855,7 @@ inline void EnumDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8034,9 +7863,9 @@ inline void EnumDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -8077,18 +7906,9 @@ EnumDescriptorProto::value() const {
inline bool EnumDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void EnumDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void EnumDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void EnumDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
const ::google::protobuf::EnumOptions* p = options_;
@@ -8098,7 +7918,7 @@ inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() con
}
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::EnumOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -8108,13 +7928,13 @@ inline ::google::protobuf::EnumOptions* EnumDescriptorProto::release_options() {
}
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::EnumOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::EnumOptions>(GetArenaNoVirtual());
options_ = p;
@@ -8134,9 +7954,9 @@ inline void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumO
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options)
@@ -8230,12 +8050,12 @@ inline void EnumDescriptorProto::add_reserved_name(const char* value, size_t siz
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>&
+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>*
+inline ::google::protobuf::RepeatedPtrField<::std::string>*
EnumDescriptorProto::mutable_reserved_name() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_name)
return &reserved_name_;
@@ -8249,28 +8069,22 @@ EnumDescriptorProto::mutable_reserved_name() {
inline bool EnumValueDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void EnumValueDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void EnumValueDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void EnumValueDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& EnumValueDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name)
return name_.Get();
}
inline void EnumValueDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.EnumValueDescriptorProto.name)
@@ -8278,20 +8092,20 @@ inline void EnumValueDescriptorProto::set_name(::std::string&& value) {
#endif
inline void EnumValueDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8300,14 +8114,14 @@ inline ::std::string* EnumValueDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -8316,7 +8130,7 @@ inline void EnumValueDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8324,9 +8138,9 @@ inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -8337,22 +8151,16 @@ inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_name(
inline bool EnumValueDescriptorProto::has_number() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void EnumValueDescriptorProto::set_has_number() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void EnumValueDescriptorProto::clear_has_number() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void EnumValueDescriptorProto::clear_number() {
number_ = 0;
- clear_has_number();
+ _has_bits_[0] &= ~0x00000004u;
}
inline ::google::protobuf::int32 EnumValueDescriptorProto::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.number)
return number_;
}
inline void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) {
- set_has_number();
+ _has_bits_[0] |= 0x00000004u;
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.number)
}
@@ -8361,18 +8169,9 @@ inline void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value
inline bool EnumValueDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void EnumValueDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void EnumValueDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void EnumValueDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
const ::google::protobuf::EnumValueOptions* p = options_;
@@ -8382,7 +8181,7 @@ inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::opt
}
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::EnumValueOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -8392,13 +8191,13 @@ inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::release_o
}
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValueDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::EnumValueOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::EnumValueOptions>(GetArenaNoVirtual());
options_ = p;
@@ -8418,9 +8217,9 @@ inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
@@ -8434,28 +8233,22 @@ inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::
inline bool ServiceDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void ServiceDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void ServiceDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void ServiceDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& ServiceDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name)
return name_.Get();
}
inline void ServiceDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.ServiceDescriptorProto.name)
@@ -8463,20 +8256,20 @@ inline void ServiceDescriptorProto::set_name(::std::string&& value) {
#endif
inline void ServiceDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8485,14 +8278,14 @@ inline ::std::string* ServiceDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -8501,7 +8294,7 @@ inline void ServiceDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8509,9 +8302,9 @@ inline void ServiceDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -8552,18 +8345,9 @@ ServiceDescriptorProto::method() const {
inline bool ServiceDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void ServiceDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void ServiceDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void ServiceDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
const ::google::protobuf::ServiceOptions* p = options_;
@@ -8573,7 +8357,7 @@ inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options
}
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::ServiceOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -8583,13 +8367,13 @@ inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::release_optio
}
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.ServiceDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
::google::protobuf::ServiceOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::ServiceOptions>(GetArenaNoVirtual());
options_ = p;
@@ -8609,9 +8393,9 @@ inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::Se
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000002u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options)
@@ -8625,28 +8409,22 @@ inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::Se
inline bool MethodDescriptorProto::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void MethodDescriptorProto::set_has_name() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void MethodDescriptorProto::clear_has_name() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void MethodDescriptorProto::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& MethodDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name)
return name_.Get();
}
inline void MethodDescriptorProto::set_name(const ::std::string& value) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.name)
@@ -8654,20 +8432,20 @@ inline void MethodDescriptorProto::set_name(::std::string&& value) {
#endif
inline void MethodDescriptorProto::set_name(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8676,14 +8454,14 @@ inline ::std::string* MethodDescriptorProto::release_name() {
if (!has_name()) {
return NULL;
}
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
@@ -8692,7 +8470,7 @@ inline void MethodDescriptorProto::set_allocated_name(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8700,9 +8478,9 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
- set_has_name();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name();
+ _has_bits_[0] &= ~0x00000001u;
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
@@ -8713,28 +8491,22 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_name(
inline bool MethodDescriptorProto::has_input_type() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void MethodDescriptorProto::set_has_input_type() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void MethodDescriptorProto::clear_has_input_type() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void MethodDescriptorProto::clear_input_type() {
input_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_input_type();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& MethodDescriptorProto::input_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type)
return input_type_.Get();
}
inline void MethodDescriptorProto::set_input_type(const ::std::string& value) {
- set_has_input_type();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
input_type_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.input_type)
@@ -8742,20 +8514,20 @@ inline void MethodDescriptorProto::set_input_type(::std::string&& value) {
#endif
inline void MethodDescriptorProto::set_input_type(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_input_type();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_input_type();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.input_type)
return input_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8764,14 +8536,14 @@ inline ::std::string* MethodDescriptorProto::release_input_type() {
if (!has_input_type()) {
return NULL;
}
- clear_has_input_type();
+ _has_bits_[0] &= ~0x00000002u;
return input_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
if (input_type != NULL) {
- set_has_input_type();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_input_type();
+ _has_bits_[0] &= ~0x00000002u;
}
input_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), input_type,
GetArenaNoVirtual());
@@ -8780,7 +8552,7 @@ inline void MethodDescriptorProto::set_allocated_input_type(::std::string* input
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();
+ _has_bits_[0] &= ~0x00000002u;
return input_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8788,9 +8560,9 @@ 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();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_input_type();
+ _has_bits_[0] &= ~0x00000002u;
}
input_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
input_type, GetArenaNoVirtual());
@@ -8801,28 +8573,22 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_input_type(
inline bool MethodDescriptorProto::has_output_type() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void MethodDescriptorProto::set_has_output_type() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void MethodDescriptorProto::clear_has_output_type() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void MethodDescriptorProto::clear_output_type() {
output_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_output_type();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& MethodDescriptorProto::output_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type)
return output_type_.Get();
}
inline void MethodDescriptorProto::set_output_type(const ::std::string& value) {
- set_has_output_type();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
output_type_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.MethodDescriptorProto.output_type)
@@ -8830,20 +8596,20 @@ inline void MethodDescriptorProto::set_output_type(::std::string&& value) {
#endif
inline void MethodDescriptorProto::set_output_type(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_output_type();
+ _has_bits_[0] |= 0x00000004u;
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) {
- set_has_output_type();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.output_type)
return output_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -8852,14 +8618,14 @@ inline ::std::string* MethodDescriptorProto::release_output_type() {
if (!has_output_type()) {
return NULL;
}
- clear_has_output_type();
+ _has_bits_[0] &= ~0x00000004u;
return output_type_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
if (output_type != NULL) {
- set_has_output_type();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_output_type();
+ _has_bits_[0] &= ~0x00000004u;
}
output_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), output_type,
GetArenaNoVirtual());
@@ -8868,7 +8634,7 @@ inline void MethodDescriptorProto::set_allocated_output_type(::std::string* outp
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();
+ _has_bits_[0] &= ~0x00000004u;
return output_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -8876,9 +8642,9 @@ 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();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_output_type();
+ _has_bits_[0] &= ~0x00000004u;
}
output_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
output_type, GetArenaNoVirtual());
@@ -8889,18 +8655,9 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_output_type(
inline bool MethodDescriptorProto::has_options() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void MethodDescriptorProto::set_has_options() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void MethodDescriptorProto::clear_has_options() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void MethodDescriptorProto::clear_options() {
if (options_ != NULL) options_->Clear();
- clear_has_options();
-}
-inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::_internal_options() const {
- return *options_;
+ _has_bits_[0] &= ~0x00000008u;
}
inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
const ::google::protobuf::MethodOptions* p = options_;
@@ -8910,7 +8667,7 @@ inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options()
}
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
::google::protobuf::MethodOptions* temp = options_;
if (GetArenaNoVirtual() != NULL) {
temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);
@@ -8920,13 +8677,13 @@ inline ::google::protobuf::MethodOptions* MethodDescriptorProto::release_options
}
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::unsafe_arena_release_options() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.MethodDescriptorProto.options)
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
::google::protobuf::MethodOptions* temp = options_;
options_ = NULL;
return temp;
}
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
if (options_ == NULL) {
auto* p = CreateMaybeMessage<::google::protobuf::MethodOptions>(GetArenaNoVirtual());
options_ = p;
@@ -8946,9 +8703,9 @@ inline void MethodDescriptorProto::set_allocated_options(::google::protobuf::Met
options = ::google::protobuf::internal::GetOwnedMessage(
message_arena, options, submessage_arena);
}
- set_has_options();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_options();
+ _has_bits_[0] &= ~0x00000008u;
}
options_ = options;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.options)
@@ -8958,22 +8715,16 @@ inline void MethodDescriptorProto::set_allocated_options(::google::protobuf::Met
inline bool MethodDescriptorProto::has_client_streaming() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void MethodDescriptorProto::set_has_client_streaming() {
- _has_bits_[0] |= 0x00000010u;
-}
-inline void MethodDescriptorProto::clear_has_client_streaming() {
- _has_bits_[0] &= ~0x00000010u;
-}
inline void MethodDescriptorProto::clear_client_streaming() {
client_streaming_ = false;
- clear_has_client_streaming();
+ _has_bits_[0] &= ~0x00000010u;
}
inline bool MethodDescriptorProto::client_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.client_streaming)
return client_streaming_;
}
inline void MethodDescriptorProto::set_client_streaming(bool value) {
- set_has_client_streaming();
+ _has_bits_[0] |= 0x00000010u;
client_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.client_streaming)
}
@@ -8982,22 +8733,16 @@ inline void MethodDescriptorProto::set_client_streaming(bool value) {
inline bool MethodDescriptorProto::has_server_streaming() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
-inline void MethodDescriptorProto::set_has_server_streaming() {
- _has_bits_[0] |= 0x00000020u;
-}
-inline void MethodDescriptorProto::clear_has_server_streaming() {
- _has_bits_[0] &= ~0x00000020u;
-}
inline void MethodDescriptorProto::clear_server_streaming() {
server_streaming_ = false;
- clear_has_server_streaming();
+ _has_bits_[0] &= ~0x00000020u;
}
inline bool MethodDescriptorProto::server_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.server_streaming)
return server_streaming_;
}
inline void MethodDescriptorProto::set_server_streaming(bool value) {
- set_has_server_streaming();
+ _has_bits_[0] |= 0x00000020u;
server_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.server_streaming)
}
@@ -9010,28 +8755,22 @@ inline void MethodDescriptorProto::set_server_streaming(bool value) {
inline bool FileOptions::has_java_package() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void FileOptions::set_has_java_package() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void FileOptions::clear_has_java_package() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void FileOptions::clear_java_package() {
java_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_java_package();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& FileOptions::java_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package)
return java_package_.Get();
}
inline void FileOptions::set_java_package(const ::std::string& value) {
- set_has_java_package();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
java_package_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_package)
@@ -9039,20 +8778,20 @@ inline void FileOptions::set_java_package(::std::string&& value) {
#endif
inline void FileOptions::set_java_package(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_java_package();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_java_package();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_package)
return java_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9061,14 +8800,14 @@ inline ::std::string* FileOptions::release_java_package() {
if (!has_java_package()) {
return NULL;
}
- clear_has_java_package();
+ _has_bits_[0] &= ~0x00000001u;
return java_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_java_package(::std::string* java_package) {
if (java_package != NULL) {
- set_has_java_package();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_java_package();
+ _has_bits_[0] &= ~0x00000001u;
}
java_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_package,
GetArenaNoVirtual());
@@ -9077,7 +8816,7 @@ inline void FileOptions::set_allocated_java_package(::std::string* 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();
+ _has_bits_[0] &= ~0x00000001u;
return java_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9085,9 +8824,9 @@ 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();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_java_package();
+ _has_bits_[0] &= ~0x00000001u;
}
java_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
java_package, GetArenaNoVirtual());
@@ -9098,28 +8837,22 @@ inline void FileOptions::unsafe_arena_set_allocated_java_package(
inline bool FileOptions::has_java_outer_classname() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void FileOptions::set_has_java_outer_classname() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void FileOptions::clear_has_java_outer_classname() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void FileOptions::clear_java_outer_classname() {
java_outer_classname_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_java_outer_classname();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& FileOptions::java_outer_classname() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname)
return java_outer_classname_.Get();
}
inline void FileOptions::set_java_outer_classname(const ::std::string& value) {
- set_has_java_outer_classname();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
java_outer_classname_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.java_outer_classname)
@@ -9127,20 +8860,20 @@ inline void FileOptions::set_java_outer_classname(::std::string&& value) {
#endif
inline void FileOptions::set_java_outer_classname(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_java_outer_classname();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_java_outer_classname();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_outer_classname)
return java_outer_classname_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9149,14 +8882,14 @@ inline ::std::string* FileOptions::release_java_outer_classname() {
if (!has_java_outer_classname()) {
return NULL;
}
- clear_has_java_outer_classname();
+ _has_bits_[0] &= ~0x00000002u;
return java_outer_classname_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) {
if (java_outer_classname != NULL) {
- set_has_java_outer_classname();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_java_outer_classname();
+ _has_bits_[0] &= ~0x00000002u;
}
java_outer_classname_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), java_outer_classname,
GetArenaNoVirtual());
@@ -9165,7 +8898,7 @@ inline void FileOptions::set_allocated_java_outer_classname(::std::string* java_
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();
+ _has_bits_[0] &= ~0x00000002u;
return java_outer_classname_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9173,9 +8906,9 @@ 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();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_java_outer_classname();
+ _has_bits_[0] &= ~0x00000002u;
}
java_outer_classname_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
java_outer_classname, GetArenaNoVirtual());
@@ -9186,22 +8919,16 @@ inline void FileOptions::unsafe_arena_set_allocated_java_outer_classname(
inline bool FileOptions::has_java_multiple_files() const {
return (_has_bits_[0] & 0x00000400u) != 0;
}
-inline void FileOptions::set_has_java_multiple_files() {
- _has_bits_[0] |= 0x00000400u;
-}
-inline void FileOptions::clear_has_java_multiple_files() {
- _has_bits_[0] &= ~0x00000400u;
-}
inline void FileOptions::clear_java_multiple_files() {
java_multiple_files_ = false;
- clear_has_java_multiple_files();
+ _has_bits_[0] &= ~0x00000400u;
}
inline bool FileOptions::java_multiple_files() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_multiple_files)
return java_multiple_files_;
}
inline void FileOptions::set_java_multiple_files(bool value) {
- set_has_java_multiple_files();
+ _has_bits_[0] |= 0x00000400u;
java_multiple_files_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_multiple_files)
}
@@ -9210,22 +8937,16 @@ inline void FileOptions::set_java_multiple_files(bool value) {
inline bool FileOptions::has_java_generate_equals_and_hash() const {
return (_has_bits_[0] & 0x00000800u) != 0;
}
-inline void FileOptions::set_has_java_generate_equals_and_hash() {
- _has_bits_[0] |= 0x00000800u;
-}
-inline void FileOptions::clear_has_java_generate_equals_and_hash() {
- _has_bits_[0] &= ~0x00000800u;
-}
inline void FileOptions::clear_java_generate_equals_and_hash() {
java_generate_equals_and_hash_ = false;
- clear_has_java_generate_equals_and_hash();
+ _has_bits_[0] &= ~0x00000800u;
}
inline 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_;
}
inline void FileOptions::set_java_generate_equals_and_hash(bool value) {
- set_has_java_generate_equals_and_hash();
+ _has_bits_[0] |= 0x00000800u;
java_generate_equals_and_hash_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generate_equals_and_hash)
}
@@ -9234,22 +8955,16 @@ inline void FileOptions::set_java_generate_equals_and_hash(bool value) {
inline bool FileOptions::has_java_string_check_utf8() const {
return (_has_bits_[0] & 0x00001000u) != 0;
}
-inline void FileOptions::set_has_java_string_check_utf8() {
- _has_bits_[0] |= 0x00001000u;
-}
-inline void FileOptions::clear_has_java_string_check_utf8() {
- _has_bits_[0] &= ~0x00001000u;
-}
inline void FileOptions::clear_java_string_check_utf8() {
java_string_check_utf8_ = false;
- clear_has_java_string_check_utf8();
+ _has_bits_[0] &= ~0x00001000u;
}
inline bool FileOptions::java_string_check_utf8() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_string_check_utf8)
return java_string_check_utf8_;
}
inline void FileOptions::set_java_string_check_utf8(bool value) {
- set_has_java_string_check_utf8();
+ _has_bits_[0] |= 0x00001000u;
java_string_check_utf8_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_string_check_utf8)
}
@@ -9258,15 +8973,9 @@ inline void FileOptions::set_java_string_check_utf8(bool value) {
inline bool FileOptions::has_optimize_for() const {
return (_has_bits_[0] & 0x00080000u) != 0;
}
-inline void FileOptions::set_has_optimize_for() {
- _has_bits_[0] |= 0x00080000u;
-}
-inline void FileOptions::clear_has_optimize_for() {
- _has_bits_[0] &= ~0x00080000u;
-}
inline void FileOptions::clear_optimize_for() {
optimize_for_ = 1;
- clear_has_optimize_for();
+ _has_bits_[0] &= ~0x00080000u;
}
inline ::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.optimize_for)
@@ -9274,7 +8983,7 @@ inline ::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for()
}
inline void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) {
assert(::google::protobuf::FileOptions_OptimizeMode_IsValid(value));
- set_has_optimize_for();
+ _has_bits_[0] |= 0x00080000u;
optimize_for_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.optimize_for)
}
@@ -9283,28 +8992,22 @@ inline void FileOptions::set_optimize_for(::google::protobuf::FileOptions_Optimi
inline bool FileOptions::has_go_package() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void FileOptions::set_has_go_package() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void FileOptions::clear_has_go_package() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void FileOptions::clear_go_package() {
go_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_go_package();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& FileOptions::go_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package)
return go_package_.Get();
}
inline void FileOptions::set_go_package(const ::std::string& value) {
- set_has_go_package();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
go_package_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.go_package)
@@ -9312,20 +9015,20 @@ inline void FileOptions::set_go_package(::std::string&& value) {
#endif
inline void FileOptions::set_go_package(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_go_package();
+ _has_bits_[0] |= 0x00000004u;
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) {
- set_has_go_package();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.go_package)
return go_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9334,14 +9037,14 @@ inline ::std::string* FileOptions::release_go_package() {
if (!has_go_package()) {
return NULL;
}
- clear_has_go_package();
+ _has_bits_[0] &= ~0x00000004u;
return go_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_go_package(::std::string* go_package) {
if (go_package != NULL) {
- set_has_go_package();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_go_package();
+ _has_bits_[0] &= ~0x00000004u;
}
go_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), go_package,
GetArenaNoVirtual());
@@ -9350,7 +9053,7 @@ inline void FileOptions::set_allocated_go_package(::std::string* 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();
+ _has_bits_[0] &= ~0x00000004u;
return go_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9358,9 +9061,9 @@ 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();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_go_package();
+ _has_bits_[0] &= ~0x00000004u;
}
go_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
go_package, GetArenaNoVirtual());
@@ -9371,22 +9074,16 @@ inline void FileOptions::unsafe_arena_set_allocated_go_package(
inline bool FileOptions::has_cc_generic_services() const {
return (_has_bits_[0] & 0x00002000u) != 0;
}
-inline void FileOptions::set_has_cc_generic_services() {
- _has_bits_[0] |= 0x00002000u;
-}
-inline void FileOptions::clear_has_cc_generic_services() {
- _has_bits_[0] &= ~0x00002000u;
-}
inline void FileOptions::clear_cc_generic_services() {
cc_generic_services_ = false;
- clear_has_cc_generic_services();
+ _has_bits_[0] &= ~0x00002000u;
}
inline bool FileOptions::cc_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_generic_services)
return cc_generic_services_;
}
inline void FileOptions::set_cc_generic_services(bool value) {
- set_has_cc_generic_services();
+ _has_bits_[0] |= 0x00002000u;
cc_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_generic_services)
}
@@ -9395,22 +9092,16 @@ inline void FileOptions::set_cc_generic_services(bool value) {
inline bool FileOptions::has_java_generic_services() const {
return (_has_bits_[0] & 0x00004000u) != 0;
}
-inline void FileOptions::set_has_java_generic_services() {
- _has_bits_[0] |= 0x00004000u;
-}
-inline void FileOptions::clear_has_java_generic_services() {
- _has_bits_[0] &= ~0x00004000u;
-}
inline void FileOptions::clear_java_generic_services() {
java_generic_services_ = false;
- clear_has_java_generic_services();
+ _has_bits_[0] &= ~0x00004000u;
}
inline bool FileOptions::java_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generic_services)
return java_generic_services_;
}
inline void FileOptions::set_java_generic_services(bool value) {
- set_has_java_generic_services();
+ _has_bits_[0] |= 0x00004000u;
java_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generic_services)
}
@@ -9419,22 +9110,16 @@ inline void FileOptions::set_java_generic_services(bool value) {
inline bool FileOptions::has_py_generic_services() const {
return (_has_bits_[0] & 0x00008000u) != 0;
}
-inline void FileOptions::set_has_py_generic_services() {
- _has_bits_[0] |= 0x00008000u;
-}
-inline void FileOptions::clear_has_py_generic_services() {
- _has_bits_[0] &= ~0x00008000u;
-}
inline void FileOptions::clear_py_generic_services() {
py_generic_services_ = false;
- clear_has_py_generic_services();
+ _has_bits_[0] &= ~0x00008000u;
}
inline bool FileOptions::py_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.py_generic_services)
return py_generic_services_;
}
inline void FileOptions::set_py_generic_services(bool value) {
- set_has_py_generic_services();
+ _has_bits_[0] |= 0x00008000u;
py_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.py_generic_services)
}
@@ -9443,22 +9128,16 @@ inline void FileOptions::set_py_generic_services(bool value) {
inline bool FileOptions::has_php_generic_services() const {
return (_has_bits_[0] & 0x00010000u) != 0;
}
-inline void FileOptions::set_has_php_generic_services() {
- _has_bits_[0] |= 0x00010000u;
-}
-inline void FileOptions::clear_has_php_generic_services() {
- _has_bits_[0] &= ~0x00010000u;
-}
inline void FileOptions::clear_php_generic_services() {
php_generic_services_ = false;
- clear_has_php_generic_services();
+ _has_bits_[0] &= ~0x00010000u;
}
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();
+ _has_bits_[0] |= 0x00010000u;
php_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_generic_services)
}
@@ -9467,22 +9146,16 @@ inline void FileOptions::set_php_generic_services(bool value) {
inline bool FileOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00020000u) != 0;
}
-inline void FileOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00020000u;
-}
-inline void FileOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00020000u;
-}
inline void FileOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00020000u;
}
inline bool FileOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.deprecated)
return deprecated_;
}
inline void FileOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00020000u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.deprecated)
}
@@ -9491,22 +9164,16 @@ inline void FileOptions::set_deprecated(bool value) {
inline bool FileOptions::has_cc_enable_arenas() const {
return (_has_bits_[0] & 0x00040000u) != 0;
}
-inline void FileOptions::set_has_cc_enable_arenas() {
- _has_bits_[0] |= 0x00040000u;
-}
-inline void FileOptions::clear_has_cc_enable_arenas() {
- _has_bits_[0] &= ~0x00040000u;
-}
inline void FileOptions::clear_cc_enable_arenas() {
cc_enable_arenas_ = false;
- clear_has_cc_enable_arenas();
+ _has_bits_[0] &= ~0x00040000u;
}
inline bool FileOptions::cc_enable_arenas() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_enable_arenas)
return cc_enable_arenas_;
}
inline void FileOptions::set_cc_enable_arenas(bool value) {
- set_has_cc_enable_arenas();
+ _has_bits_[0] |= 0x00040000u;
cc_enable_arenas_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_enable_arenas)
}
@@ -9515,28 +9182,22 @@ inline void FileOptions::set_cc_enable_arenas(bool value) {
inline bool FileOptions::has_objc_class_prefix() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void FileOptions::set_has_objc_class_prefix() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void FileOptions::clear_has_objc_class_prefix() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void FileOptions::clear_objc_class_prefix() {
objc_class_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_objc_class_prefix();
+ _has_bits_[0] &= ~0x00000008u;
}
inline const ::std::string& FileOptions::objc_class_prefix() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix)
return objc_class_prefix_.Get();
}
inline void FileOptions::set_objc_class_prefix(const ::std::string& value) {
- set_has_objc_class_prefix();
+ _has_bits_[0] |= 0x00000008u;
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();
+ _has_bits_[0] |= 0x00000008u;
objc_class_prefix_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.objc_class_prefix)
@@ -9544,20 +9205,20 @@ inline void FileOptions::set_objc_class_prefix(::std::string&& value) {
#endif
inline void FileOptions::set_objc_class_prefix(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_objc_class_prefix();
+ _has_bits_[0] |= 0x00000008u;
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) {
- set_has_objc_class_prefix();
+ _has_bits_[0] |= 0x00000008u;
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();
+ _has_bits_[0] |= 0x00000008u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.objc_class_prefix)
return objc_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9566,14 +9227,14 @@ inline ::std::string* FileOptions::release_objc_class_prefix() {
if (!has_objc_class_prefix()) {
return NULL;
}
- clear_has_objc_class_prefix();
+ _has_bits_[0] &= ~0x00000008u;
return objc_class_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) {
if (objc_class_prefix != NULL) {
- set_has_objc_class_prefix();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_objc_class_prefix();
+ _has_bits_[0] &= ~0x00000008u;
}
objc_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), objc_class_prefix,
GetArenaNoVirtual());
@@ -9582,7 +9243,7 @@ inline void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_cla
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();
+ _has_bits_[0] &= ~0x00000008u;
return objc_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9590,9 +9251,9 @@ 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();
+ _has_bits_[0] |= 0x00000008u;
} else {
- clear_has_objc_class_prefix();
+ _has_bits_[0] &= ~0x00000008u;
}
objc_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
objc_class_prefix, GetArenaNoVirtual());
@@ -9603,28 +9264,22 @@ inline void FileOptions::unsafe_arena_set_allocated_objc_class_prefix(
inline bool FileOptions::has_csharp_namespace() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void FileOptions::set_has_csharp_namespace() {
- _has_bits_[0] |= 0x00000010u;
-}
-inline void FileOptions::clear_has_csharp_namespace() {
- _has_bits_[0] &= ~0x00000010u;
-}
inline void FileOptions::clear_csharp_namespace() {
csharp_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_csharp_namespace();
+ _has_bits_[0] &= ~0x00000010u;
}
inline const ::std::string& FileOptions::csharp_namespace() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace)
return csharp_namespace_.Get();
}
inline void FileOptions::set_csharp_namespace(const ::std::string& value) {
- set_has_csharp_namespace();
+ _has_bits_[0] |= 0x00000010u;
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();
+ _has_bits_[0] |= 0x00000010u;
csharp_namespace_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.csharp_namespace)
@@ -9632,20 +9287,20 @@ inline void FileOptions::set_csharp_namespace(::std::string&& value) {
#endif
inline void FileOptions::set_csharp_namespace(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_csharp_namespace();
+ _has_bits_[0] |= 0x00000010u;
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) {
- set_has_csharp_namespace();
+ _has_bits_[0] |= 0x00000010u;
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();
+ _has_bits_[0] |= 0x00000010u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.csharp_namespace)
return csharp_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9654,14 +9309,14 @@ inline ::std::string* FileOptions::release_csharp_namespace() {
if (!has_csharp_namespace()) {
return NULL;
}
- clear_has_csharp_namespace();
+ _has_bits_[0] &= ~0x00000010u;
return csharp_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
if (csharp_namespace != NULL) {
- set_has_csharp_namespace();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_csharp_namespace();
+ _has_bits_[0] &= ~0x00000010u;
}
csharp_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), csharp_namespace,
GetArenaNoVirtual());
@@ -9670,7 +9325,7 @@ inline void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_na
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();
+ _has_bits_[0] &= ~0x00000010u;
return csharp_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9678,9 +9333,9 @@ 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();
+ _has_bits_[0] |= 0x00000010u;
} else {
- clear_has_csharp_namespace();
+ _has_bits_[0] &= ~0x00000010u;
}
csharp_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
csharp_namespace, GetArenaNoVirtual());
@@ -9691,28 +9346,22 @@ inline void FileOptions::unsafe_arena_set_allocated_csharp_namespace(
inline bool FileOptions::has_swift_prefix() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
-inline void FileOptions::set_has_swift_prefix() {
- _has_bits_[0] |= 0x00000020u;
-}
-inline void FileOptions::clear_has_swift_prefix() {
- _has_bits_[0] &= ~0x00000020u;
-}
inline void FileOptions::clear_swift_prefix() {
swift_prefix_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_swift_prefix();
+ _has_bits_[0] &= ~0x00000020u;
}
inline const ::std::string& FileOptions::swift_prefix() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.swift_prefix)
return swift_prefix_.Get();
}
inline void FileOptions::set_swift_prefix(const ::std::string& value) {
- set_has_swift_prefix();
+ _has_bits_[0] |= 0x00000020u;
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();
+ _has_bits_[0] |= 0x00000020u;
swift_prefix_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.swift_prefix)
@@ -9720,20 +9369,20 @@ inline void FileOptions::set_swift_prefix(::std::string&& value) {
#endif
inline void FileOptions::set_swift_prefix(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_swift_prefix();
+ _has_bits_[0] |= 0x00000020u;
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) {
- set_has_swift_prefix();
+ _has_bits_[0] |= 0x00000020u;
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();
+ _has_bits_[0] |= 0x00000020u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.swift_prefix)
return swift_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9742,14 +9391,14 @@ inline ::std::string* FileOptions::release_swift_prefix() {
if (!has_swift_prefix()) {
return NULL;
}
- clear_has_swift_prefix();
+ _has_bits_[0] &= ~0x00000020u;
return swift_prefix_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_swift_prefix(::std::string* swift_prefix) {
if (swift_prefix != NULL) {
- set_has_swift_prefix();
+ _has_bits_[0] |= 0x00000020u;
} else {
- clear_has_swift_prefix();
+ _has_bits_[0] &= ~0x00000020u;
}
swift_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), swift_prefix,
GetArenaNoVirtual());
@@ -9758,7 +9407,7 @@ inline void FileOptions::set_allocated_swift_prefix(::std::string* 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();
+ _has_bits_[0] &= ~0x00000020u;
return swift_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9766,9 +9415,9 @@ 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();
+ _has_bits_[0] |= 0x00000020u;
} else {
- clear_has_swift_prefix();
+ _has_bits_[0] &= ~0x00000020u;
}
swift_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
swift_prefix, GetArenaNoVirtual());
@@ -9779,28 +9428,22 @@ inline void FileOptions::unsafe_arena_set_allocated_swift_prefix(
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();
+ _has_bits_[0] &= ~0x00000040u;
}
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();
+ _has_bits_[0] |= 0x00000040u;
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();
+ _has_bits_[0] |= 0x00000040u;
php_class_prefix_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_class_prefix)
@@ -9808,20 +9451,20 @@ inline void FileOptions::set_php_class_prefix(::std::string&& value) {
#endif
inline void FileOptions::set_php_class_prefix(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_php_class_prefix();
+ _has_bits_[0] |= 0x00000040u;
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();
+ _has_bits_[0] |= 0x00000040u;
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();
+ _has_bits_[0] |= 0x00000040u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_class_prefix)
return php_class_prefix_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9830,14 +9473,14 @@ inline ::std::string* FileOptions::release_php_class_prefix() {
if (!has_php_class_prefix()) {
return NULL;
}
- clear_has_php_class_prefix();
+ _has_bits_[0] &= ~0x00000040u;
return php_class_prefix_.ReleaseNonDefault(&::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();
+ _has_bits_[0] |= 0x00000040u;
} else {
- clear_has_php_class_prefix();
+ _has_bits_[0] &= ~0x00000040u;
}
php_class_prefix_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_class_prefix,
GetArenaNoVirtual());
@@ -9846,7 +9489,7 @@ inline void FileOptions::set_allocated_php_class_prefix(::std::string* php_class
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();
+ _has_bits_[0] &= ~0x00000040u;
return php_class_prefix_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9854,9 +9497,9 @@ 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();
+ _has_bits_[0] |= 0x00000040u;
} else {
- clear_has_php_class_prefix();
+ _has_bits_[0] &= ~0x00000040u;
}
php_class_prefix_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
php_class_prefix, GetArenaNoVirtual());
@@ -9867,28 +9510,22 @@ inline void FileOptions::unsafe_arena_set_allocated_php_class_prefix(
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();
+ _has_bits_[0] &= ~0x00000080u;
}
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();
+ _has_bits_[0] |= 0x00000080u;
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();
+ _has_bits_[0] |= 0x00000080u;
php_namespace_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_namespace)
@@ -9896,20 +9533,20 @@ inline void FileOptions::set_php_namespace(::std::string&& value) {
#endif
inline void FileOptions::set_php_namespace(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_php_namespace();
+ _has_bits_[0] |= 0x00000080u;
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();
+ _has_bits_[0] |= 0x00000080u;
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();
+ _has_bits_[0] |= 0x00000080u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_namespace)
return php_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -9918,14 +9555,14 @@ inline ::std::string* FileOptions::release_php_namespace() {
if (!has_php_namespace()) {
return NULL;
}
- clear_has_php_namespace();
+ _has_bits_[0] &= ~0x00000080u;
return php_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespace) {
if (php_namespace != NULL) {
- set_has_php_namespace();
+ _has_bits_[0] |= 0x00000080u;
} else {
- clear_has_php_namespace();
+ _has_bits_[0] &= ~0x00000080u;
}
php_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_namespace,
GetArenaNoVirtual());
@@ -9934,7 +9571,7 @@ inline void FileOptions::set_allocated_php_namespace(::std::string* php_namespac
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();
+ _has_bits_[0] &= ~0x00000080u;
return php_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -9942,9 +9579,9 @@ 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();
+ _has_bits_[0] |= 0x00000080u;
} else {
- clear_has_php_namespace();
+ _has_bits_[0] &= ~0x00000080u;
}
php_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
php_namespace, GetArenaNoVirtual());
@@ -9955,28 +9592,22 @@ inline void FileOptions::unsafe_arena_set_allocated_php_namespace(
inline bool FileOptions::has_php_metadata_namespace() const {
return (_has_bits_[0] & 0x00000100u) != 0;
}
-inline void FileOptions::set_has_php_metadata_namespace() {
- _has_bits_[0] |= 0x00000100u;
-}
-inline void FileOptions::clear_has_php_metadata_namespace() {
- _has_bits_[0] &= ~0x00000100u;
-}
inline void FileOptions::clear_php_metadata_namespace() {
php_metadata_namespace_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_php_metadata_namespace();
+ _has_bits_[0] &= ~0x00000100u;
}
inline const ::std::string& FileOptions::php_metadata_namespace() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_metadata_namespace)
return php_metadata_namespace_.Get();
}
inline void FileOptions::set_php_metadata_namespace(const ::std::string& value) {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_metadata_namespace)
}
#if LANG_CXX11
inline void FileOptions::set_php_metadata_namespace(::std::string&& value) {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.php_metadata_namespace)
@@ -9984,20 +9615,20 @@ inline void FileOptions::set_php_metadata_namespace(::std::string&& value) {
#endif
inline void FileOptions::set_php_metadata_namespace(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
php_metadata_namespace_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.php_metadata_namespace)
}
inline void FileOptions::set_php_metadata_namespace(const char* value,
size_t size) {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
php_metadata_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_metadata_namespace)
}
inline ::std::string* FileOptions::mutable_php_metadata_namespace() {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.php_metadata_namespace)
return php_metadata_namespace_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -10006,14 +9637,14 @@ inline ::std::string* FileOptions::release_php_metadata_namespace() {
if (!has_php_metadata_namespace()) {
return NULL;
}
- clear_has_php_metadata_namespace();
+ _has_bits_[0] &= ~0x00000100u;
return php_metadata_namespace_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_php_metadata_namespace(::std::string* php_metadata_namespace) {
if (php_metadata_namespace != NULL) {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
} else {
- clear_has_php_metadata_namespace();
+ _has_bits_[0] &= ~0x00000100u;
}
php_metadata_namespace_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), php_metadata_namespace,
GetArenaNoVirtual());
@@ -10022,7 +9653,7 @@ inline void FileOptions::set_allocated_php_metadata_namespace(::std::string* php
inline ::std::string* FileOptions::unsafe_arena_release_php_metadata_namespace() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.php_metadata_namespace)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- clear_has_php_metadata_namespace();
+ _has_bits_[0] &= ~0x00000100u;
return php_metadata_namespace_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -10030,9 +9661,9 @@ inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace(
::std::string* php_metadata_namespace) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (php_metadata_namespace != NULL) {
- set_has_php_metadata_namespace();
+ _has_bits_[0] |= 0x00000100u;
} else {
- clear_has_php_metadata_namespace();
+ _has_bits_[0] &= ~0x00000100u;
}
php_metadata_namespace_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
php_metadata_namespace, GetArenaNoVirtual());
@@ -10043,28 +9674,22 @@ inline void FileOptions::unsafe_arena_set_allocated_php_metadata_namespace(
inline bool FileOptions::has_ruby_package() const {
return (_has_bits_[0] & 0x00000200u) != 0;
}
-inline void FileOptions::set_has_ruby_package() {
- _has_bits_[0] |= 0x00000200u;
-}
-inline void FileOptions::clear_has_ruby_package() {
- _has_bits_[0] &= ~0x00000200u;
-}
inline void FileOptions::clear_ruby_package() {
ruby_package_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_ruby_package();
+ _has_bits_[0] &= ~0x00000200u;
}
inline const ::std::string& FileOptions::ruby_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.ruby_package)
return ruby_package_.Get();
}
inline void FileOptions::set_ruby_package(const ::std::string& value) {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.ruby_package)
}
#if LANG_CXX11
inline void FileOptions::set_ruby_package(::std::string&& value) {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
ruby_package_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.FileOptions.ruby_package)
@@ -10072,20 +9697,20 @@ inline void FileOptions::set_ruby_package(::std::string&& value) {
#endif
inline void FileOptions::set_ruby_package(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.ruby_package)
}
inline void FileOptions::set_ruby_package(const char* value,
size_t size) {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
ruby_package_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.ruby_package)
}
inline ::std::string* FileOptions::mutable_ruby_package() {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.ruby_package)
return ruby_package_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -10094,14 +9719,14 @@ inline ::std::string* FileOptions::release_ruby_package() {
if (!has_ruby_package()) {
return NULL;
}
- clear_has_ruby_package();
+ _has_bits_[0] &= ~0x00000200u;
return ruby_package_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void FileOptions::set_allocated_ruby_package(::std::string* ruby_package) {
if (ruby_package != NULL) {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
} else {
- clear_has_ruby_package();
+ _has_bits_[0] &= ~0x00000200u;
}
ruby_package_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ruby_package,
GetArenaNoVirtual());
@@ -10110,7 +9735,7 @@ inline void FileOptions::set_allocated_ruby_package(::std::string* ruby_package)
inline ::std::string* FileOptions::unsafe_arena_release_ruby_package() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.FileOptions.ruby_package)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
- clear_has_ruby_package();
+ _has_bits_[0] &= ~0x00000200u;
return ruby_package_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -10118,9 +9743,9 @@ inline void FileOptions::unsafe_arena_set_allocated_ruby_package(
::std::string* ruby_package) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (ruby_package != NULL) {
- set_has_ruby_package();
+ _has_bits_[0] |= 0x00000200u;
} else {
- clear_has_ruby_package();
+ _has_bits_[0] &= ~0x00000200u;
}
ruby_package_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
ruby_package, GetArenaNoVirtual());
@@ -10165,22 +9790,16 @@ FileOptions::uninterpreted_option() const {
inline bool MessageOptions::has_message_set_wire_format() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void MessageOptions::set_has_message_set_wire_format() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void MessageOptions::clear_has_message_set_wire_format() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void MessageOptions::clear_message_set_wire_format() {
message_set_wire_format_ = false;
- clear_has_message_set_wire_format();
+ _has_bits_[0] &= ~0x00000001u;
}
inline bool MessageOptions::message_set_wire_format() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.message_set_wire_format)
return message_set_wire_format_;
}
inline void MessageOptions::set_message_set_wire_format(bool value) {
- set_has_message_set_wire_format();
+ _has_bits_[0] |= 0x00000001u;
message_set_wire_format_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.message_set_wire_format)
}
@@ -10189,22 +9808,16 @@ inline void MessageOptions::set_message_set_wire_format(bool value) {
inline bool MessageOptions::has_no_standard_descriptor_accessor() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void MessageOptions::set_has_no_standard_descriptor_accessor() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void MessageOptions::clear_has_no_standard_descriptor_accessor() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void MessageOptions::clear_no_standard_descriptor_accessor() {
no_standard_descriptor_accessor_ = false;
- clear_has_no_standard_descriptor_accessor();
+ _has_bits_[0] &= ~0x00000002u;
}
inline bool MessageOptions::no_standard_descriptor_accessor() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
return no_standard_descriptor_accessor_;
}
inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) {
- set_has_no_standard_descriptor_accessor();
+ _has_bits_[0] |= 0x00000002u;
no_standard_descriptor_accessor_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
}
@@ -10213,22 +9826,16 @@ inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) {
inline bool MessageOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void MessageOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void MessageOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void MessageOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000004u;
}
inline bool MessageOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.deprecated)
return deprecated_;
}
inline void MessageOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000004u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.deprecated)
}
@@ -10237,22 +9844,16 @@ inline void MessageOptions::set_deprecated(bool value) {
inline bool MessageOptions::has_map_entry() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void MessageOptions::set_has_map_entry() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void MessageOptions::clear_has_map_entry() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void MessageOptions::clear_map_entry() {
map_entry_ = false;
- clear_has_map_entry();
+ _has_bits_[0] &= ~0x00000008u;
}
inline bool MessageOptions::map_entry() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.map_entry)
return map_entry_;
}
inline void MessageOptions::set_map_entry(bool value) {
- set_has_map_entry();
+ _has_bits_[0] |= 0x00000008u;
map_entry_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.map_entry)
}
@@ -10295,15 +9896,9 @@ MessageOptions::uninterpreted_option() const {
inline bool FieldOptions::has_ctype() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void FieldOptions::set_has_ctype() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void FieldOptions::clear_has_ctype() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void FieldOptions::clear_ctype() {
ctype_ = 0;
- clear_has_ctype();
+ _has_bits_[0] &= ~0x00000001u;
}
inline ::google::protobuf::FieldOptions_CType FieldOptions::ctype() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.ctype)
@@ -10311,7 +9906,7 @@ inline ::google::protobuf::FieldOptions_CType FieldOptions::ctype() const {
}
inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) {
assert(::google::protobuf::FieldOptions_CType_IsValid(value));
- set_has_ctype();
+ _has_bits_[0] |= 0x00000001u;
ctype_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.ctype)
}
@@ -10320,22 +9915,16 @@ inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value
inline bool FieldOptions::has_packed() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void FieldOptions::set_has_packed() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void FieldOptions::clear_has_packed() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void FieldOptions::clear_packed() {
packed_ = false;
- clear_has_packed();
+ _has_bits_[0] &= ~0x00000002u;
}
inline bool FieldOptions::packed() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.packed)
return packed_;
}
inline void FieldOptions::set_packed(bool value) {
- set_has_packed();
+ _has_bits_[0] |= 0x00000002u;
packed_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.packed)
}
@@ -10344,15 +9933,9 @@ inline void FieldOptions::set_packed(bool value) {
inline bool FieldOptions::has_jstype() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
-inline void FieldOptions::set_has_jstype() {
- _has_bits_[0] |= 0x00000020u;
-}
-inline void FieldOptions::clear_has_jstype() {
- _has_bits_[0] &= ~0x00000020u;
-}
inline void FieldOptions::clear_jstype() {
jstype_ = 0;
- clear_has_jstype();
+ _has_bits_[0] &= ~0x00000020u;
}
inline ::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.jstype)
@@ -10360,7 +9943,7 @@ inline ::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const {
}
inline void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType value) {
assert(::google::protobuf::FieldOptions_JSType_IsValid(value));
- set_has_jstype();
+ _has_bits_[0] |= 0x00000020u;
jstype_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.jstype)
}
@@ -10369,22 +9952,16 @@ inline void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType val
inline bool FieldOptions::has_lazy() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void FieldOptions::set_has_lazy() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void FieldOptions::clear_has_lazy() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void FieldOptions::clear_lazy() {
lazy_ = false;
- clear_has_lazy();
+ _has_bits_[0] &= ~0x00000004u;
}
inline bool FieldOptions::lazy() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.lazy)
return lazy_;
}
inline void FieldOptions::set_lazy(bool value) {
- set_has_lazy();
+ _has_bits_[0] |= 0x00000004u;
lazy_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.lazy)
}
@@ -10393,22 +9970,16 @@ inline void FieldOptions::set_lazy(bool value) {
inline bool FieldOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void FieldOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void FieldOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void FieldOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000008u;
}
inline bool FieldOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.deprecated)
return deprecated_;
}
inline void FieldOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000008u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.deprecated)
}
@@ -10417,22 +9988,16 @@ inline void FieldOptions::set_deprecated(bool value) {
inline bool FieldOptions::has_weak() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void FieldOptions::set_has_weak() {
- _has_bits_[0] |= 0x00000010u;
-}
-inline void FieldOptions::clear_has_weak() {
- _has_bits_[0] &= ~0x00000010u;
-}
inline void FieldOptions::clear_weak() {
weak_ = false;
- clear_has_weak();
+ _has_bits_[0] &= ~0x00000010u;
}
inline bool FieldOptions::weak() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.weak)
return weak_;
}
inline void FieldOptions::set_weak(bool value) {
- set_has_weak();
+ _has_bits_[0] |= 0x00000010u;
weak_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.weak)
}
@@ -10509,22 +10074,16 @@ OneofOptions::uninterpreted_option() const {
inline bool EnumOptions::has_allow_alias() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void EnumOptions::set_has_allow_alias() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void EnumOptions::clear_has_allow_alias() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void EnumOptions::clear_allow_alias() {
allow_alias_ = false;
- clear_has_allow_alias();
+ _has_bits_[0] &= ~0x00000001u;
}
inline bool EnumOptions::allow_alias() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.allow_alias)
return allow_alias_;
}
inline void EnumOptions::set_allow_alias(bool value) {
- set_has_allow_alias();
+ _has_bits_[0] |= 0x00000001u;
allow_alias_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.allow_alias)
}
@@ -10533,22 +10092,16 @@ inline void EnumOptions::set_allow_alias(bool value) {
inline bool EnumOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void EnumOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void EnumOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void EnumOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000002u;
}
inline bool EnumOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.deprecated)
return deprecated_;
}
inline void EnumOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000002u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.deprecated)
}
@@ -10591,22 +10144,16 @@ EnumOptions::uninterpreted_option() const {
inline bool EnumValueOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void EnumValueOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void EnumValueOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void EnumValueOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000001u;
}
inline bool EnumValueOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.deprecated)
return deprecated_;
}
inline void EnumValueOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000001u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueOptions.deprecated)
}
@@ -10649,22 +10196,16 @@ EnumValueOptions::uninterpreted_option() const {
inline bool ServiceOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void ServiceOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void ServiceOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void ServiceOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000001u;
}
inline bool ServiceOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.deprecated)
return deprecated_;
}
inline void ServiceOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000001u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.ServiceOptions.deprecated)
}
@@ -10707,22 +10248,16 @@ ServiceOptions::uninterpreted_option() const {
inline bool MethodOptions::has_deprecated() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void MethodOptions::set_has_deprecated() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void MethodOptions::clear_has_deprecated() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void MethodOptions::clear_deprecated() {
deprecated_ = false;
- clear_has_deprecated();
+ _has_bits_[0] &= ~0x00000001u;
}
inline bool MethodOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.deprecated)
return deprecated_;
}
inline void MethodOptions::set_deprecated(bool value) {
- set_has_deprecated();
+ _has_bits_[0] |= 0x00000001u;
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.deprecated)
}
@@ -10731,15 +10266,9 @@ inline void MethodOptions::set_deprecated(bool value) {
inline bool MethodOptions::has_idempotency_level() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void MethodOptions::set_has_idempotency_level() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void MethodOptions::clear_has_idempotency_level() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void MethodOptions::clear_idempotency_level() {
idempotency_level_ = 0;
- clear_has_idempotency_level();
+ _has_bits_[0] &= ~0x00000002u;
}
inline ::google::protobuf::MethodOptions_IdempotencyLevel MethodOptions::idempotency_level() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.idempotency_level)
@@ -10747,7 +10276,7 @@ inline ::google::protobuf::MethodOptions_IdempotencyLevel MethodOptions::idempot
}
inline void MethodOptions::set_idempotency_level(::google::protobuf::MethodOptions_IdempotencyLevel value) {
assert(::google::protobuf::MethodOptions_IdempotencyLevel_IsValid(value));
- set_has_idempotency_level();
+ _has_bits_[0] |= 0x00000002u;
idempotency_level_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.idempotency_level)
}
@@ -10790,28 +10319,22 @@ MethodOptions::uninterpreted_option() const {
inline bool UninterpretedOption_NamePart::has_name_part() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void UninterpretedOption_NamePart::set_has_name_part() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void UninterpretedOption_NamePart::clear_has_name_part() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void UninterpretedOption_NamePart::clear_name_part() {
name_part_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_name_part();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& UninterpretedOption_NamePart::name_part() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part)
return name_part_.Get();
}
inline void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) {
- set_has_name_part();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
name_part_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.NamePart.name_part)
@@ -10819,20 +10342,20 @@ inline void UninterpretedOption_NamePart::set_name_part(::std::string&& value) {
#endif
inline void UninterpretedOption_NamePart::set_name_part(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_name_part();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_name_part();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.NamePart.name_part)
return name_part_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -10841,14 +10364,14 @@ inline ::std::string* UninterpretedOption_NamePart::release_name_part() {
if (!has_name_part()) {
return NULL;
}
- clear_has_name_part();
+ _has_bits_[0] &= ~0x00000001u;
return name_part_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) {
if (name_part != NULL) {
- set_has_name_part();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name_part();
+ _has_bits_[0] &= ~0x00000001u;
}
name_part_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name_part,
GetArenaNoVirtual());
@@ -10857,7 +10380,7 @@ inline void UninterpretedOption_NamePart::set_allocated_name_part(::std::string*
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();
+ _has_bits_[0] &= ~0x00000001u;
return name_part_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -10865,9 +10388,9 @@ 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();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_name_part();
+ _has_bits_[0] &= ~0x00000001u;
}
name_part_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name_part, GetArenaNoVirtual());
@@ -10878,22 +10401,16 @@ inline void UninterpretedOption_NamePart::unsafe_arena_set_allocated_name_part(
inline bool UninterpretedOption_NamePart::has_is_extension() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void UninterpretedOption_NamePart::set_has_is_extension() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void UninterpretedOption_NamePart::clear_has_is_extension() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void UninterpretedOption_NamePart::clear_is_extension() {
is_extension_ = false;
- clear_has_is_extension();
+ _has_bits_[0] &= ~0x00000002u;
}
inline bool UninterpretedOption_NamePart::is_extension() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.is_extension)
return is_extension_;
}
inline void UninterpretedOption_NamePart::set_is_extension(bool value) {
- set_has_is_extension();
+ _has_bits_[0] |= 0x00000002u;
is_extension_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.is_extension)
}
@@ -10936,28 +10453,22 @@ UninterpretedOption::name() const {
inline bool UninterpretedOption::has_identifier_value() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void UninterpretedOption::set_has_identifier_value() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void UninterpretedOption::clear_has_identifier_value() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void UninterpretedOption::clear_identifier_value() {
identifier_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_identifier_value();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& UninterpretedOption::identifier_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value)
return identifier_value_.Get();
}
inline void UninterpretedOption::set_identifier_value(const ::std::string& value) {
- set_has_identifier_value();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
identifier_value_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.identifier_value)
@@ -10965,20 +10476,20 @@ inline void UninterpretedOption::set_identifier_value(::std::string&& value) {
#endif
inline void UninterpretedOption::set_identifier_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_identifier_value();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_identifier_value();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.identifier_value)
return identifier_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -10987,14 +10498,14 @@ inline ::std::string* UninterpretedOption::release_identifier_value() {
if (!has_identifier_value()) {
return NULL;
}
- clear_has_identifier_value();
+ _has_bits_[0] &= ~0x00000001u;
return identifier_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
if (identifier_value != NULL) {
- set_has_identifier_value();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_identifier_value();
+ _has_bits_[0] &= ~0x00000001u;
}
identifier_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), identifier_value,
GetArenaNoVirtual());
@@ -11003,7 +10514,7 @@ inline void UninterpretedOption::set_allocated_identifier_value(::std::string* i
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();
+ _has_bits_[0] &= ~0x00000001u;
return identifier_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11011,9 +10522,9 @@ 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();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_identifier_value();
+ _has_bits_[0] &= ~0x00000001u;
}
identifier_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
identifier_value, GetArenaNoVirtual());
@@ -11024,22 +10535,16 @@ inline void UninterpretedOption::unsafe_arena_set_allocated_identifier_value(
inline bool UninterpretedOption::has_positive_int_value() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
-inline void UninterpretedOption::set_has_positive_int_value() {
- _has_bits_[0] |= 0x00000008u;
-}
-inline void UninterpretedOption::clear_has_positive_int_value() {
- _has_bits_[0] &= ~0x00000008u;
-}
inline void UninterpretedOption::clear_positive_int_value() {
- positive_int_value_ = GOOGLE_ULONGLONG(0);
- clear_has_positive_int_value();
+ positive_int_value_ = PROTOBUF_ULONGLONG(0);
+ _has_bits_[0] &= ~0x00000008u;
}
inline ::google::protobuf::uint64 UninterpretedOption::positive_int_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.positive_int_value)
return positive_int_value_;
}
inline void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) {
- set_has_positive_int_value();
+ _has_bits_[0] |= 0x00000008u;
positive_int_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.positive_int_value)
}
@@ -11048,22 +10553,16 @@ inline void UninterpretedOption::set_positive_int_value(::google::protobuf::uint
inline bool UninterpretedOption::has_negative_int_value() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
-inline void UninterpretedOption::set_has_negative_int_value() {
- _has_bits_[0] |= 0x00000010u;
-}
-inline void UninterpretedOption::clear_has_negative_int_value() {
- _has_bits_[0] &= ~0x00000010u;
-}
inline void UninterpretedOption::clear_negative_int_value() {
- negative_int_value_ = GOOGLE_LONGLONG(0);
- clear_has_negative_int_value();
+ negative_int_value_ = PROTOBUF_LONGLONG(0);
+ _has_bits_[0] &= ~0x00000010u;
}
inline ::google::protobuf::int64 UninterpretedOption::negative_int_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.negative_int_value)
return negative_int_value_;
}
inline void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) {
- set_has_negative_int_value();
+ _has_bits_[0] |= 0x00000010u;
negative_int_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.negative_int_value)
}
@@ -11072,22 +10571,16 @@ inline void UninterpretedOption::set_negative_int_value(::google::protobuf::int6
inline bool UninterpretedOption::has_double_value() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
-inline void UninterpretedOption::set_has_double_value() {
- _has_bits_[0] |= 0x00000020u;
-}
-inline void UninterpretedOption::clear_has_double_value() {
- _has_bits_[0] &= ~0x00000020u;
-}
inline void UninterpretedOption::clear_double_value() {
double_value_ = 0;
- clear_has_double_value();
+ _has_bits_[0] &= ~0x00000020u;
}
inline double UninterpretedOption::double_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.double_value)
return double_value_;
}
inline void UninterpretedOption::set_double_value(double value) {
- set_has_double_value();
+ _has_bits_[0] |= 0x00000020u;
double_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.double_value)
}
@@ -11096,28 +10589,22 @@ inline void UninterpretedOption::set_double_value(double value) {
inline bool UninterpretedOption::has_string_value() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void UninterpretedOption::set_has_string_value() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void UninterpretedOption::clear_has_string_value() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void UninterpretedOption::clear_string_value() {
string_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_string_value();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& UninterpretedOption::string_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value)
return string_value_.Get();
}
inline void UninterpretedOption::set_string_value(const ::std::string& value) {
- set_has_string_value();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
string_value_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.string_value)
@@ -11125,20 +10612,20 @@ inline void UninterpretedOption::set_string_value(::std::string&& value) {
#endif
inline void UninterpretedOption::set_string_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_string_value();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_string_value();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.string_value)
return string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -11147,14 +10634,14 @@ inline ::std::string* UninterpretedOption::release_string_value() {
if (!has_string_value()) {
return NULL;
}
- clear_has_string_value();
+ _has_bits_[0] &= ~0x00000002u;
return string_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
if (string_value != NULL) {
- set_has_string_value();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_string_value();
+ _has_bits_[0] &= ~0x00000002u;
}
string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
GetArenaNoVirtual());
@@ -11163,7 +10650,7 @@ inline void UninterpretedOption::set_allocated_string_value(::std::string* strin
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();
+ _has_bits_[0] &= ~0x00000002u;
return string_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11171,9 +10658,9 @@ 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();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_string_value();
+ _has_bits_[0] &= ~0x00000002u;
}
string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
string_value, GetArenaNoVirtual());
@@ -11184,28 +10671,22 @@ inline void UninterpretedOption::unsafe_arena_set_allocated_string_value(
inline bool UninterpretedOption::has_aggregate_value() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void UninterpretedOption::set_has_aggregate_value() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void UninterpretedOption::clear_has_aggregate_value() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void UninterpretedOption::clear_aggregate_value() {
aggregate_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_aggregate_value();
+ _has_bits_[0] &= ~0x00000004u;
}
inline const ::std::string& UninterpretedOption::aggregate_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value)
return aggregate_value_.Get();
}
inline void UninterpretedOption::set_aggregate_value(const ::std::string& value) {
- set_has_aggregate_value();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
aggregate_value_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.UninterpretedOption.aggregate_value)
@@ -11213,20 +10694,20 @@ inline void UninterpretedOption::set_aggregate_value(::std::string&& value) {
#endif
inline void UninterpretedOption::set_aggregate_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_aggregate_value();
+ _has_bits_[0] |= 0x00000004u;
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) {
- set_has_aggregate_value();
+ _has_bits_[0] |= 0x00000004u;
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();
+ _has_bits_[0] |= 0x00000004u;
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.aggregate_value)
return aggregate_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -11235,14 +10716,14 @@ inline ::std::string* UninterpretedOption::release_aggregate_value() {
if (!has_aggregate_value()) {
return NULL;
}
- clear_has_aggregate_value();
+ _has_bits_[0] &= ~0x00000004u;
return aggregate_value_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
if (aggregate_value != NULL) {
- set_has_aggregate_value();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_aggregate_value();
+ _has_bits_[0] &= ~0x00000004u;
}
aggregate_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), aggregate_value,
GetArenaNoVirtual());
@@ -11251,7 +10732,7 @@ inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* ag
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();
+ _has_bits_[0] &= ~0x00000004u;
return aggregate_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11259,9 +10740,9 @@ 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();
+ _has_bits_[0] |= 0x00000004u;
} else {
- clear_has_aggregate_value();
+ _has_bits_[0] &= ~0x00000004u;
}
aggregate_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
aggregate_value, GetArenaNoVirtual());
@@ -11336,28 +10817,22 @@ SourceCodeInfo_Location::mutable_span() {
inline bool SourceCodeInfo_Location::has_leading_comments() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void SourceCodeInfo_Location::set_has_leading_comments() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void SourceCodeInfo_Location::clear_has_leading_comments() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void SourceCodeInfo_Location::clear_leading_comments() {
leading_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_leading_comments();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& SourceCodeInfo_Location::leading_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments)
return leading_comments_.Get();
}
inline void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) {
- set_has_leading_comments();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
leading_comments_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.leading_comments)
@@ -11365,20 +10840,20 @@ inline void SourceCodeInfo_Location::set_leading_comments(::std::string&& value)
#endif
inline void SourceCodeInfo_Location::set_leading_comments(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_leading_comments();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_leading_comments();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_comments)
return leading_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -11387,14 +10862,14 @@ inline ::std::string* SourceCodeInfo_Location::release_leading_comments() {
if (!has_leading_comments()) {
return NULL;
}
- clear_has_leading_comments();
+ _has_bits_[0] &= ~0x00000001u;
return leading_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) {
if (leading_comments != NULL) {
- set_has_leading_comments();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_leading_comments();
+ _has_bits_[0] &= ~0x00000001u;
}
leading_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), leading_comments,
GetArenaNoVirtual());
@@ -11403,7 +10878,7 @@ inline void SourceCodeInfo_Location::set_allocated_leading_comments(::std::strin
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();
+ _has_bits_[0] &= ~0x00000001u;
return leading_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11411,9 +10886,9 @@ 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();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_leading_comments();
+ _has_bits_[0] &= ~0x00000001u;
}
leading_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
leading_comments, GetArenaNoVirtual());
@@ -11424,28 +10899,22 @@ inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_leading_comments
inline bool SourceCodeInfo_Location::has_trailing_comments() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void SourceCodeInfo_Location::set_has_trailing_comments() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void SourceCodeInfo_Location::clear_has_trailing_comments() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void SourceCodeInfo_Location::clear_trailing_comments() {
trailing_comments_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_trailing_comments();
+ _has_bits_[0] &= ~0x00000002u;
}
inline const ::std::string& SourceCodeInfo_Location::trailing_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments)
return trailing_comments_.Get();
}
inline void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) {
- set_has_trailing_comments();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
trailing_comments_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.SourceCodeInfo.Location.trailing_comments)
@@ -11453,20 +10922,20 @@ inline void SourceCodeInfo_Location::set_trailing_comments(::std::string&& value
#endif
inline void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_trailing_comments();
+ _has_bits_[0] |= 0x00000002u;
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) {
- set_has_trailing_comments();
+ _has_bits_[0] |= 0x00000002u;
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();
+ _has_bits_[0] |= 0x00000002u;
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.trailing_comments)
return trailing_comments_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -11475,14 +10944,14 @@ inline ::std::string* SourceCodeInfo_Location::release_trailing_comments() {
if (!has_trailing_comments()) {
return NULL;
}
- clear_has_trailing_comments();
+ _has_bits_[0] &= ~0x00000002u;
return trailing_comments_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) {
if (trailing_comments != NULL) {
- set_has_trailing_comments();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_trailing_comments();
+ _has_bits_[0] &= ~0x00000002u;
}
trailing_comments_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), trailing_comments,
GetArenaNoVirtual());
@@ -11491,7 +10960,7 @@ inline void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::stri
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();
+ _has_bits_[0] &= ~0x00000002u;
return trailing_comments_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11499,9 +10968,9 @@ inline void SourceCodeInfo_Location::unsafe_arena_set_allocated_trailing_comment
::std::string* trailing_comments) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (trailing_comments != NULL) {
- set_has_trailing_comments();
+ _has_bits_[0] |= 0x00000002u;
} else {
- clear_has_trailing_comments();
+ _has_bits_[0] &= ~0x00000002u;
}
trailing_comments_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
trailing_comments, GetArenaNoVirtual());
@@ -11566,12 +11035,12 @@ inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* v
leading_detached_comments_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline 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_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::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_;
@@ -11649,28 +11118,22 @@ GeneratedCodeInfo_Annotation::mutable_path() {
inline bool GeneratedCodeInfo_Annotation::has_source_file() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
-inline void GeneratedCodeInfo_Annotation::set_has_source_file() {
- _has_bits_[0] |= 0x00000001u;
-}
-inline void GeneratedCodeInfo_Annotation::clear_has_source_file() {
- _has_bits_[0] &= ~0x00000001u;
-}
inline void GeneratedCodeInfo_Annotation::clear_source_file() {
source_file_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- clear_has_source_file();
+ _has_bits_[0] &= ~0x00000001u;
}
inline const ::std::string& GeneratedCodeInfo_Annotation::source_file() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
return source_file_.Get();
}
inline void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) {
- set_has_source_file();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
source_file_.Set(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
@@ -11678,20 +11141,20 @@ inline void GeneratedCodeInfo_Annotation::set_source_file(::std::string&& value)
#endif
inline void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
GOOGLE_DCHECK(value != NULL);
- set_has_source_file();
+ _has_bits_[0] |= 0x00000001u;
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) {
- set_has_source_file();
+ _has_bits_[0] |= 0x00000001u;
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();
+ _has_bits_[0] |= 0x00000001u;
// @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
return source_file_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
@@ -11700,14 +11163,14 @@ inline ::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
if (!has_source_file()) {
return NULL;
}
- clear_has_source_file();
+ _has_bits_[0] &= ~0x00000001u;
return source_file_.ReleaseNonDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) {
if (source_file != NULL) {
- set_has_source_file();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_source_file();
+ _has_bits_[0] &= ~0x00000001u;
}
source_file_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), source_file,
GetArenaNoVirtual());
@@ -11716,7 +11179,7 @@ inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::strin
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();
+ _has_bits_[0] &= ~0x00000001u;
return source_file_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
@@ -11724,9 +11187,9 @@ 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();
+ _has_bits_[0] |= 0x00000001u;
} else {
- clear_has_source_file();
+ _has_bits_[0] &= ~0x00000001u;
}
source_file_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
source_file, GetArenaNoVirtual());
@@ -11737,22 +11200,16 @@ inline void GeneratedCodeInfo_Annotation::unsafe_arena_set_allocated_source_file
inline bool GeneratedCodeInfo_Annotation::has_begin() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
-inline void GeneratedCodeInfo_Annotation::set_has_begin() {
- _has_bits_[0] |= 0x00000002u;
-}
-inline void GeneratedCodeInfo_Annotation::clear_has_begin() {
- _has_bits_[0] &= ~0x00000002u;
-}
inline void GeneratedCodeInfo_Annotation::clear_begin() {
begin_ = 0;
- clear_has_begin();
+ _has_bits_[0] &= ~0x00000002u;
}
inline ::google::protobuf::int32 GeneratedCodeInfo_Annotation::begin() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.begin)
return begin_;
}
inline void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 value) {
- set_has_begin();
+ _has_bits_[0] |= 0x00000002u;
begin_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.begin)
}
@@ -11761,22 +11218,16 @@ inline void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 va
inline bool GeneratedCodeInfo_Annotation::has_end() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
-inline void GeneratedCodeInfo_Annotation::set_has_end() {
- _has_bits_[0] |= 0x00000004u;
-}
-inline void GeneratedCodeInfo_Annotation::clear_has_end() {
- _has_bits_[0] &= ~0x00000004u;
-}
inline void GeneratedCodeInfo_Annotation::clear_end() {
end_ = 0;
- clear_has_end();
+ _has_bits_[0] &= ~0x00000004u;
}
inline ::google::protobuf::int32 GeneratedCodeInfo_Annotation::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.end)
return end_;
}
inline void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 value) {
- set_has_end();
+ _has_bits_[0] |= 0x00000004u;
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.end)
}
@@ -11915,4 +11366,5 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::MethodOption
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fdescriptor_2eproto
diff --git a/src/google/protobuf/descriptor_database.cc b/src/google/protobuf/descriptor_database.cc
index ba85ef13..1f5ba480 100644
--- a/src/google/protobuf/descriptor_database.cc
+++ b/src/google/protobuf/descriptor_database.cc
@@ -214,6 +214,17 @@ bool SimpleDescriptorDatabase::DescriptorIndex<Value>::FindAllExtensionNumbers(
}
template <typename Value>
+void SimpleDescriptorDatabase::DescriptorIndex<Value>::FindAllFileNames(
+ std::vector<string>* output) {
+ output->resize(by_name_.size());
+ int i = 0;
+ for (const auto& kv : by_name_) {
+ (*output)[i] = kv.first;
+ i++;
+ }
+}
+
+template <typename Value>
typename std::map<string, Value>::iterator
SimpleDescriptorDatabase::DescriptorIndex<Value>::FindLastLessOrEqual(
const string& name) {
@@ -293,6 +304,11 @@ bool SimpleDescriptorDatabase::FindAllExtensionNumbers(
}
+bool SimpleDescriptorDatabase::FindAllFileNames(std::vector<string>* output) {
+ index_.FindAllFileNames(output);
+ return true;
+}
+
bool SimpleDescriptorDatabase::MaybeCopy(const FileDescriptorProto* file,
FileDescriptorProto* output) {
if (file == NULL) return false;
diff --git a/src/google/protobuf/descriptor_database.h b/src/google/protobuf/descriptor_database.h
index d61f2a6a..48892af1 100644
--- a/src/google/protobuf/descriptor_database.h
+++ b/src/google/protobuf/descriptor_database.h
@@ -44,6 +44,12 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#define PROTOBUF_EXPORT
+#endif
+
namespace google {
namespace protobuf {
@@ -62,27 +68,27 @@ class MergedDescriptorDatabase;
// calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool
// can be created which wraps a DescriptorDatabase and only builds particular
// descriptors when they are needed.
-class LIBPROTOBUF_EXPORT DescriptorDatabase {
+class PROTOBUF_EXPORT DescriptorDatabase {
public:
inline DescriptorDatabase() {}
virtual ~DescriptorDatabase();
// Find a file by file name. Fills in in *output and returns true if found.
// Otherwise, returns false, leaving the contents of *output undefined.
- virtual bool FindFileByName(const string& filename,
+ virtual bool FindFileByName(const std::string& filename,
FileDescriptorProto* output) = 0;
// Find the file that declares the given fully-qualified symbol name.
// If found, fills in *output and returns true, otherwise returns false
// and leaves *output undefined.
- virtual bool FindFileContainingSymbol(const string& symbol_name,
+ virtual bool FindFileContainingSymbol(const std::string& symbol_name,
FileDescriptorProto* output) = 0;
// Find the file which defines an extension extending the given message type
// with the given field number. If found, fills in *output and returns true,
// otherwise returns false and leaves *output undefined. containing_type
// must be a fully-qualified type name.
- virtual bool FindFileContainingExtension(const string& containing_type,
+ virtual bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
FileDescriptorProto* output) = 0;
@@ -96,7 +102,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase {
//
// This method has a default implementation that always returns
// false.
- virtual bool FindAllExtensionNumbers(const string& /* extendee_type */,
+ virtual bool FindAllExtensionNumbers(const std::string& /* extendee_type */,
std::vector<int>* /* output */) {
return false;
}
@@ -110,7 +116,7 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase {
//
// This method has a default implementation that always returns
// false.
- virtual bool FindAllFileNames(std::vector<string>* output) {
+ virtual bool FindAllFileNames(std::vector<std::string>* output) {
return false;
}
@@ -139,10 +145,10 @@ class LIBPROTOBUF_EXPORT DescriptorDatabase {
// FileDescriptor::CopyTo()) will always use fully-qualified names for all
// types. You only need to worry if you are constructing FileDescriptorProtos
// yourself, or are calling compiler::Parser directly.
-class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
+class PROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
public:
SimpleDescriptorDatabase();
- ~SimpleDescriptorDatabase();
+ ~SimpleDescriptorDatabase() override;
// Adds the FileDescriptorProto to the database, making a copy. The object
// can be deleted after Add() returns. Returns false if the file conflicted
@@ -154,15 +160,17 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
bool AddAndOwn(const FileDescriptorProto* file);
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
- bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileByName(const std::string& filename,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingSymbol(const std::string& symbol_name,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
- FileDescriptorProto* output);
- bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ FileDescriptorProto* output) override;
+ bool FindAllExtensionNumbers(const std::string& extendee_type,
+ std::vector<int>* output) override;
+
+ bool FindAllFileNames(std::vector<std::string>* output) override;
private:
// So that it can use DescriptorIndex.
@@ -177,22 +185,23 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
// to the index.
bool AddFile(const FileDescriptorProto& file,
Value value);
- bool AddSymbol(const string& name, Value value);
+ bool AddSymbol(const std::string& name, Value value);
bool AddNestedExtensions(const DescriptorProto& message_type,
Value value);
bool AddExtension(const FieldDescriptorProto& field,
Value value);
- Value FindFile(const string& filename);
- Value FindSymbol(const string& name);
- Value FindExtension(const string& containing_type, int field_number);
- bool FindAllExtensionNumbers(const string& containing_type,
+ Value FindFile(const std::string& filename);
+ Value FindSymbol(const std::string& name);
+ Value FindExtension(const std::string& containing_type, int field_number);
+ bool FindAllExtensionNumbers(const std::string& containing_type,
std::vector<int>* output);
+ void FindAllFileNames(std::vector<std::string>* output);
private:
- std::map<string, Value> by_name_;
- std::map<string, Value> by_symbol_;
- std::map<std::pair<string, int>, Value> by_extension_;
+ std::map<std::string, Value> by_name_;
+ std::map<std::string, Value> by_symbol_;
+ std::map<std::pair<std::string, int>, Value> by_extension_;
// Invariant: The by_symbol_ map does not contain any symbols which are
// prefixes of other symbols in the map. For example, "foo.bar" is a
@@ -247,17 +256,17 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
// Find the last entry in the by_symbol_ map whose key is less than or
// equal to the given name.
- typename std::map<string, Value>::iterator FindLastLessOrEqual(
- const string& name);
+ typename std::map<std::string, Value>::iterator FindLastLessOrEqual(
+ const std::string& name);
// True if either the arguments are equal or super_symbol identifies a
// parent symbol of sub_symbol (e.g. "foo.bar" is a parent of
// "foo.bar.baz", but not a parent of "foo.barbaz").
- bool IsSubSymbol(const string& sub_symbol, const string& super_symbol);
+ bool IsSubSymbol(const std::string& sub_symbol, const std::string& super_symbol);
// Returns true if and only if all characters in the name are alphanumerics,
// underscores, or periods.
- bool ValidateSymbolName(const string& name);
+ bool ValidateSymbolName(const std::string& name);
};
@@ -277,10 +286,10 @@ class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase {
//
// The same caveats regarding FindFileContainingExtension() apply as with
// SimpleDescriptorDatabase.
-class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
+class PROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
public:
EncodedDescriptorDatabase();
- ~EncodedDescriptorDatabase();
+ ~EncodedDescriptorDatabase() override;
// Adds the FileDescriptorProto to the database. The descriptor is provided
// in encoded form. The database does not make a copy of the bytes, nor
@@ -295,19 +304,19 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
bool AddCopy(const void* encoded_file_descriptor, int size);
// Like FindFileContainingSymbol but returns only the name of the file.
- bool FindNameOfFileContainingSymbol(const string& symbol_name,
- string* output);
+ bool FindNameOfFileContainingSymbol(const std::string& symbol_name,
+ std::string* output);
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
- bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileByName(const std::string& filename,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingSymbol(const std::string& symbol_name,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
- FileDescriptorProto* output);
- bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ FileDescriptorProto* output) override;
+ bool FindAllExtensionNumbers(const std::string& extendee_type,
+ std::vector<int>* output) override;
private:
SimpleDescriptorDatabase::DescriptorIndex<std::pair<const void*, int> >
@@ -323,21 +332,21 @@ class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase {
};
// A DescriptorDatabase that fetches files from a given pool.
-class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase {
+class PROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase {
public:
explicit DescriptorPoolDatabase(const DescriptorPool& pool);
- ~DescriptorPoolDatabase();
+ ~DescriptorPoolDatabase() override;
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
- bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileByName(const std::string& filename,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingSymbol(const std::string& symbol_name,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
- FileDescriptorProto* output);
- bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ FileDescriptorProto* output) override;
+ bool FindAllExtensionNumbers(const std::string& extendee_type,
+ std::vector<int>* output) override;
private:
const DescriptorPool& pool_;
@@ -346,7 +355,7 @@ class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase {
// A DescriptorDatabase that wraps two or more others. It first searches the
// first database and, if that fails, tries the second, and so on.
-class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase {
+class PROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase {
public:
// Merge just two databases. The sources remain property of the caller.
MergedDescriptorDatabase(DescriptorDatabase* source1,
@@ -356,20 +365,20 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase {
// DescriptorDatabases need to stick around.
explicit MergedDescriptorDatabase(
const std::vector<DescriptorDatabase*>& sources);
- ~MergedDescriptorDatabase();
+ ~MergedDescriptorDatabase() override;
// implements DescriptorDatabase -----------------------------------
- bool FindFileByName(const string& filename,
- FileDescriptorProto* output);
- bool FindFileContainingSymbol(const string& symbol_name,
- FileDescriptorProto* output);
- bool FindFileContainingExtension(const string& containing_type,
+ bool FindFileByName(const std::string& filename,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingSymbol(const std::string& symbol_name,
+ FileDescriptorProto* output) override;
+ bool FindFileContainingExtension(const std::string& containing_type,
int field_number,
- FileDescriptorProto* output);
+ FileDescriptorProto* output) override;
// Merges the results of calling all databases. Returns true iff any
// of the databases returned true.
- bool FindAllExtensionNumbers(const string& extendee_type,
- std::vector<int>* output);
+ bool FindAllExtensionNumbers(const std::string& extendee_type,
+ std::vector<int>* output) override;
private:
@@ -378,6 +387,8 @@ class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase {
};
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__
diff --git a/src/google/protobuf/descriptor_database_unittest.cc b/src/google/protobuf/descriptor_database_unittest.cc
index 083ef8f2..7d3f17ca 100644
--- a/src/google/protobuf/descriptor_database_unittest.cc
+++ b/src/google/protobuf/descriptor_database_unittest.cc
@@ -44,6 +44,7 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <gmock/gmock.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
@@ -77,7 +78,7 @@ static void ExpectContainsType(const FileDescriptorProto& proto,
// three nearly-identical sets of tests, we use parameterized tests to apply
// the same code to all three.
-// The parameterized test runs against a DescriptarDatabaseTestCase. We have
+// The parameterized test runs against a DescriptorDatabaseTestCase. We have
// implementations for each of the three classes we want to test.
class DescriptorDatabaseTestCase {
public:
@@ -519,6 +520,21 @@ TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) {
EXPECT_FALSE(db.FindNameOfFileContainingSymbol("baz.Baz", &filename));
}
+TEST(SimpleDescriptorDatabaseExtraTest, FindAllFileNames) {
+ FileDescriptorProto f;
+ f.set_name("foo.proto");
+ f.set_package("foo");
+ f.add_message_type()->set_name("Foo");
+
+ SimpleDescriptorDatabase db;
+ db.Add(f);
+
+ // Test!
+ std::vector<string> all_files;
+ db.FindAllFileNames(&all_files);
+ EXPECT_THAT(all_files, testing::ElementsAre("foo.proto"));
+}
+
// ===================================================================
class MergedDescriptorDatabaseTest : public testing::Test {
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc
index 54da095a..e48e440f 100644
--- a/src/google/protobuf/descriptor_unittest.cc
+++ b/src/google/protobuf/descriptor_unittest.cc
@@ -57,10 +57,13 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stringprintf.h>
+#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -512,7 +515,7 @@ void ExtractDebugString(
debug_strings->push_back(std::make_pair(file->name(), file->DebugString()));
}
-class SimpleErrorCollector : public google::protobuf::io::ErrorCollector {
+class SimpleErrorCollector : public io::ErrorCollector {
public:
// implements ErrorCollector ---------------------------------------
void AddError(int line, int column, const string& message) {
@@ -542,10 +545,10 @@ TEST_F(FileDescriptorTest, DebugStringRoundTrip) {
for (int i = 0; i < debug_strings.size(); ++i) {
const string& name = debug_strings[i].first;
const string& content = debug_strings[i].second;
- google::protobuf::io::ArrayInputStream input_stream(content.data(), content.size());
+ io::ArrayInputStream input_stream(content.data(), content.size());
SimpleErrorCollector error_collector;
- google::protobuf::io::Tokenizer tokenizer(&input_stream, &error_collector);
- google::protobuf::compiler::Parser parser;
+ io::Tokenizer tokenizer(&input_stream, &error_collector);
+ compiler::Parser parser;
parser.RecordErrorsTo(&error_collector);
FileDescriptorProto proto;
ASSERT_TRUE(parser.Parse(&tokenizer, &proto))
@@ -2506,11 +2509,11 @@ TEST_F(MiscTest, DefaultValues) {
ASSERT_TRUE(message->field(9)->has_default_value());
ASSERT_TRUE(message->field(10)->has_default_value());
- EXPECT_EQ(-1 , message->field(0)->default_value_int32 ());
- EXPECT_EQ(-GOOGLE_ULONGLONG(1000000000000),
- message->field(1)->default_value_int64 ());
- EXPECT_EQ(42 , message->field(2)->default_value_uint32());
- EXPECT_EQ(GOOGLE_ULONGLONG(2000000000000),
+ EXPECT_EQ(-1, message->field(0)->default_value_int32());
+ EXPECT_EQ(-PROTOBUF_ULONGLONG(1000000000000),
+ message->field(1)->default_value_int64());
+ EXPECT_EQ(42, message->field(2)->default_value_uint32());
+ EXPECT_EQ(PROTOBUF_ULONGLONG(2000000000000),
message->field(3)->default_value_uint64());
EXPECT_EQ(4.5 , message->field(4)->default_value_float ());
EXPECT_EQ(10e100 , message->field(5)->default_value_double());
@@ -2925,11 +2928,11 @@ TEST(CustomOptions, OptionLocations) {
file->FindServiceByName("TestServiceWithCustomOptions");
const MethodDescriptor* method = service->FindMethodByName("Foo");
- EXPECT_EQ(GOOGLE_LONGLONG(9876543210),
+ EXPECT_EQ(PROTOBUF_LONGLONG(9876543210),
file->options().GetExtension(protobuf_unittest::file_opt1));
EXPECT_EQ(-56,
message->options().GetExtension(protobuf_unittest::message_opt1));
- EXPECT_EQ(GOOGLE_LONGLONG(8765432109),
+ EXPECT_EQ(PROTOBUF_LONGLONG(8765432109),
field->options().GetExtension(protobuf_unittest::field_opt1));
EXPECT_EQ(42, // Check that we get the default for an option we don't set.
field->options().GetExtension(protobuf_unittest::field_opt2));
@@ -2940,7 +2943,7 @@ TEST(CustomOptions, OptionLocations) {
EXPECT_EQ(123,
enm->value(1)->options().GetExtension(
protobuf_unittest::enum_value_opt1));
- EXPECT_EQ(GOOGLE_LONGLONG(-9876543210),
+ EXPECT_EQ(PROTOBUF_LONGLONG(-9876543210),
service->options().GetExtension(protobuf_unittest::service_opt1));
EXPECT_EQ(protobuf_unittest::METHODOPT1_VAL2,
method->options().GetExtension(protobuf_unittest::method_opt1));
@@ -3407,7 +3410,7 @@ TEST(CustomOptions, UnusedImportWarning) {
// Verifies that proto files can correctly be parsed, even if the
// custom options defined in the file are incompatible with those
// compiled in the binary. See http://b/19276250.
-TEST(CustomOptions, OptionsWithRequiredEnums) {
+TEST(CustomOptions, OptionsWithIncompatibleDescriptors) {
DescriptorPool pool;
FileDescriptorProto file_proto;
@@ -3446,38 +3449,12 @@ TEST(CustomOptions, OptionsWithRequiredEnums) {
" name_part: 'required_enum_opt' "
" is_extension: true "
" } "
- " aggregate_value: 'value: NEW_VALUE' "
+ " aggregate_value: 'value: NEW_VALUE'"
"}",
test_message_type->mutable_options()));
- // Add the file descriptor to the pool.
- ASSERT_TRUE(pool.BuildFile(file_proto) != NULL);
-
- // Find the test message.
- const Descriptor* test_message = pool.FindMessageTypeByName(
- "protobuf_unittest.TestMessageWithRequiredEnumOption");
- ASSERT_TRUE(test_message != NULL);
-
- const MessageOptions& options = test_message->options();
- // Extract the "required_enum_opt" option. Since the binary does not
- // know that the extension was updated, this will still return an
- // OldOptionType message.
- ASSERT_TRUE(
- options.HasExtension(protobuf_unittest::required_enum_opt));
- const protobuf_unittest::OldOptionType& old_enum_opt =
- options.GetExtension(protobuf_unittest::required_enum_opt);
-
- // Confirm that the required enum field is missing.
- EXPECT_FALSE(old_enum_opt.IsInitialized());
- EXPECT_FALSE(old_enum_opt.has_value());
-
- string buf;
- // Verify that the required enum field does show up when the option
- // is re-parsed as a NewOptionType message;
- protobuf_unittest::NewOptionType new_enum_opt;
- EXPECT_TRUE(old_enum_opt.AppendPartialToString(&buf));
- EXPECT_TRUE(new_enum_opt.ParseFromString(buf));
- EXPECT_EQ(protobuf_unittest::NewOptionType::NEW_VALUE, new_enum_opt.value());
+ // Adding the file descriptor to the pool should fail.
+ EXPECT_TRUE(pool.BuildFile(file_proto) == NULL);
}
// Test that FileDescriptor::DebugString() formats custom options correctly.
@@ -5156,7 +5133,9 @@ TEST_F(ValidationErrorTest, UnknownOption) {
" is_extension: false } "
" positive_int_value: 1 } }",
- "qux.proto: qux.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown.\n");
+ "qux.proto: qux.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown. Ensure "
+ "that your proto definition file imports the proto which defines the "
+ "option.\n");
}
TEST_F(ValidationErrorTest, CustomOptionConflictingFieldNumber) {
@@ -5429,6 +5408,26 @@ TEST_F(ValidationErrorTest, StringOptionValueIsNotString) {
"string option \"foo\".\n");
}
+TEST_F(ValidationErrorTest, JsonNameOptionOnExtensions) {
+ BuildFileWithErrors(
+ "name: \"foo.proto\" "
+ "package: \"foo\" "
+ "message_type {"
+ " name: \"Foo\""
+ " extension_range { start: 10 end: 20 }"
+ "}"
+ "extension {"
+ " name: \"value\""
+ " number: 10"
+ " label: LABEL_OPTIONAL"
+ " type: TYPE_INT32"
+ " extendee: \"foo.Foo\""
+ " json_name: \"myName\""
+ "}",
+ "foo.proto: foo.value: OPTION_NAME: option json_name is not allowed on "
+ "extension fields.\n");
+}
+
TEST_F(ValidationErrorTest, DuplicateExtensionFieldNumber) {
BuildDescriptorMessagesInTestPool();
@@ -6814,8 +6813,8 @@ class ExponentialErrorDatabase : public DescriptorDatabase {
name.substr(name.size()- end_size, end_size) != end_with) {
return;
}
- safe_strto32(name.substr(begin_size, name.size() - end_size - begin_size),
- file_num);
+ safe_strto32(
+ name.substr(begin_size, name.size() - end_size - begin_size), file_num);
}
bool PopulateFile(int file_num, FileDescriptorProto* output) {
@@ -6916,83 +6915,82 @@ class SingletonSourceTree : public compiler::SourceTree {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SingletonSourceTree);
};
-const char *const kSourceLocationTestInput =
- "syntax = \"proto2\";\n"
- "option java_package = \"com.foo.bar\";\n"
- "option (test_file_opt) = \"foobar\";\n"
- "message A {\n"
- " option (test_msg_opt) = \"foobar\";\n"
- " optional int32 a = 1 [deprecated = true];\n"
- " message B {\n"
- " required double b = 1 [(test_field_opt) = \"foobar\"];\n"
- " }\n"
- " oneof c {\n"
- " option (test_oneof_opt) = \"foobar\";\n"
- " string d = 2;\n"
- " string e = 3;\n"
- " string f = 4;\n"
- " }\n"
- "}\n"
- "enum Indecision {\n"
- " option (test_enum_opt) = 21;\n"
- " option (test_enum_opt) = 42;\n"
- " option (test_enum_opt) = 63;\n"
- " YES = 1 [(test_enumval_opt).a = 100];\n"
- " NO = 2 [(test_enumval_opt) = {a:200}];\n"
- " MAYBE = 3;\n"
- "}\n"
- "service S {\n"
- " option (test_svc_opt) = {a:100};\n"
- " option (test_svc_opt) = {a:200};\n"
- " option (test_svc_opt) = {a:300};\n"
- " rpc Method(A) returns (A.B);\n"
- // Put an empty line here to make the source location range match.
- "\n"
- " rpc OtherMethod(A) returns (A) {\n"
- " option deprecated = true;\n"
- " option (test_method_opt) = \"foobar\";\n"
- " }\n"
- "}\n"
- "message MessageWithExtensions {\n"
- " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n"
- "}\n"
- "extend MessageWithExtensions {\n"
- " repeated int32 int32_extension = 1001 [packed=true];\n"
- "}\n"
- "message C {\n"
- " extend MessageWithExtensions {\n"
- " optional C message_extension = 1002;\n"
- " }\n"
- "}\n"
- "import \"google/protobuf/descriptor.proto\";\n"
- "extend google.protobuf.FileOptions {\n"
- " optional string test_file_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.MessageOptions {\n"
- " optional string test_msg_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.FieldOptions {\n"
- " optional string test_field_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.EnumOptions {\n"
- " repeated int32 test_enum_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.EnumValueOptions {\n"
- " optional A test_enumval_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.ServiceOptions {\n"
- " repeated A test_svc_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.MethodOptions {\n"
- " optional string test_method_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.OneofOptions {\n"
- " optional string test_oneof_opt = 10101;\n"
- "}\n"
- "extend google.protobuf.ExtensionRangeOptions {\n"
- " optional string test_ext_opt = 10101;\n"
- "}\n"
- ;
+const char* const kSourceLocationTestInput =
+ "syntax = \"proto2\";\n"
+ "option java_package = \"com.foo.bar\";\n"
+ "option (test_file_opt) = \"foobar\";\n"
+ "message A {\n"
+ " option (test_msg_opt) = \"foobar\";\n"
+ " optional int32 a = 1 [deprecated = true];\n"
+ " message B {\n"
+ " required double b = 1 [(test_field_opt) = \"foobar\"];\n"
+ " }\n"
+ " oneof c {\n"
+ " option (test_oneof_opt) = \"foobar\";\n"
+ " string d = 2;\n"
+ " string e = 3;\n"
+ " string f = 4;\n"
+ " }\n"
+ "}\n"
+ "enum Indecision {\n"
+ " option (test_enum_opt) = 21;\n"
+ " option (test_enum_opt) = 42;\n"
+ " option (test_enum_opt) = 63;\n"
+ " YES = 1 [(test_enumval_opt).a = 100];\n"
+ " NO = 2 [(test_enumval_opt) = {a:200}];\n"
+ " MAYBE = 3;\n"
+ "}\n"
+ "service S {\n"
+ " option (test_svc_opt) = {a:100};\n"
+ " option (test_svc_opt) = {a:200};\n"
+ " option (test_svc_opt) = {a:300};\n"
+ " rpc Method(A) returns (A.B);\n"
+ // Put an empty line here to make the source location range match.
+ "\n"
+ " rpc OtherMethod(A) returns (A) {\n"
+ " option deprecated = true;\n"
+ " option (test_method_opt) = \"foobar\";\n"
+ " }\n"
+ "}\n"
+ "message MessageWithExtensions {\n"
+ " extensions 1000 to 2000, 2001 to max [(test_ext_opt) = \"foobar\"];\n"
+ "}\n"
+ "extend MessageWithExtensions {\n"
+ " repeated int32 int32_extension = 1001 [packed=true];\n"
+ "}\n"
+ "message C {\n"
+ " extend MessageWithExtensions {\n"
+ " optional C message_extension = 1002;\n"
+ " }\n"
+ "}\n"
+ "import \"google/protobuf/descriptor.proto\";\n"
+ "extend google.protobuf.FileOptions {\n"
+ " optional string test_file_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.MessageOptions {\n"
+ " optional string test_msg_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.FieldOptions {\n"
+ " optional string test_field_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.EnumOptions {\n"
+ " repeated int32 test_enum_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.EnumValueOptions {\n"
+ " optional A test_enumval_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.ServiceOptions {\n"
+ " repeated A test_svc_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.MethodOptions {\n"
+ " optional string test_method_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.OneofOptions {\n"
+ " optional string test_oneof_opt = 10101;\n"
+ "}\n"
+ "extend google.protobuf.ExtensionRangeOptions {\n"
+ " optional string test_ext_opt = 10101;\n"
+ "}\n";
class SourceLocationTest : public testing::Test {
public:
@@ -7020,9 +7018,9 @@ class SourceLocationTest : public testing::Test {
FileDescriptorProto file_proto_;
AbortingErrorCollector collector_;
SingletonSourceTree source_tree_;
- SimpleDescriptorDatabase simple_db_; // contains descriptor.proto
- compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto
- MergedDescriptorDatabase merged_db_; // combines above two dbs
+ SimpleDescriptorDatabase simple_db_; // contains descriptor.proto
+ compiler::SourceTreeDescriptorDatabase source_tree_db_; // loads test.proto
+ MergedDescriptorDatabase merged_db_; // combines above two dbs
protected:
DescriptorPool pool_;
@@ -7030,7 +7028,7 @@ class SourceLocationTest : public testing::Test {
// tag number of all custom options in above test file
static const int kCustomOptionFieldNumber = 10101;
// tag number of field "a" in message type "A" in above test file
- static const int kA_aFieldNumber = 1;
+ static const int kAFieldNumber = 1;
};
// TODO(adonovan): implement support for option fields and for
@@ -7039,7 +7037,7 @@ class SourceLocationTest : public testing::Test {
TEST_F(SourceLocationTest, GetSourceLocation) {
SourceLocation loc;
- const FileDescriptor *file_desc =
+ const FileDescriptor* file_desc =
GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
const Descriptor *a_desc = file_desc->FindMessageTypeByName("A");
@@ -7071,7 +7069,7 @@ TEST_F(SourceLocationTest, GetSourceLocation) {
TEST_F(SourceLocationTest, ExtensionSourceLocation) {
SourceLocation loc;
- const FileDescriptor *file_desc =
+ const FileDescriptor* file_desc =
GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
const FieldDescriptor *int32_extension_desc =
@@ -7088,7 +7086,6 @@ TEST_F(SourceLocationTest, ExtensionSourceLocation) {
EXPECT_TRUE(message_extension_desc->GetSourceLocation(&loc));
EXPECT_EQ("44:5-44:41", PrintSourceLocation(loc));
}
-
TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// This one's a doozy. It checks every kind of option, including
// extension range options.
@@ -7099,16 +7096,15 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
SourceLocation loc;
- const FileDescriptor *file_desc =
+ const FileDescriptor* file_desc =
GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
// File options
{
- int path[] = {FileDescriptorProto::kOptionsFieldNumber,
- FileOptions::kJavaPackageFieldNumber};
+ int path[] = {FileDescriptorProto::kOptionsFieldNumber,
+ FileOptions::kJavaPackageFieldNumber};
int unint[] = {FileDescriptorProto::kOptionsFieldNumber,
- FileOptions::kUninterpretedOptionFieldNumber,
- 0};
+ FileOptions::kUninterpretedOptionFieldNumber, 0};
std::vector<int> vpath(path, path + 2);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
@@ -7118,11 +7114,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {FileDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kOptionsFieldNumber,
- FileOptions::kUninterpretedOptionFieldNumber,
- 1};
+ FileOptions::kUninterpretedOptionFieldNumber, 1};
std::vector<int> vpath(path, path + 2);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("3:1-3:35", PrintSourceLocation(loc));
@@ -7133,15 +7128,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Message option
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0,
+ DescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
+ int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber, 0,
DescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
- int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 0,
- DescriptorProto::kOptionsFieldNumber,
- MessageOptions::kUninterpretedOptionFieldNumber,
- 0};
+ MessageOptions::kUninterpretedOptionFieldNumber, 0};
std::vector<int> vpath(path, path + 4);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("5:3-5:36", PrintSourceLocation(loc));
@@ -7152,12 +7144,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Field option
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 0,
- DescriptorProto::kFieldFieldNumber,
- 0,
- FieldDescriptorProto::kOptionsFieldNumber,
- FieldOptions::kDeprecatedFieldNumber};
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 0,
+ DescriptorProto::kFieldFieldNumber,
+ 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kDeprecatedFieldNumber};
int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
0,
DescriptorProto::kFieldFieldNumber,
@@ -7175,14 +7167,11 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Nested message option
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 0,
- DescriptorProto::kNestedTypeFieldNumber,
- 0,
- DescriptorProto::kFieldFieldNumber,
- 0,
- FieldDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {
+ FileDescriptorProto::kMessageTypeFieldNumber, 0,
+ DescriptorProto::kNestedTypeFieldNumber, 0,
+ DescriptorProto::kFieldFieldNumber, 0,
+ FieldDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
0,
DescriptorProto::kNestedTypeFieldNumber,
@@ -7202,12 +7191,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// One-of option
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 0,
- DescriptorProto::kOneofDeclFieldNumber,
- 0,
- OneofDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {
+ FileDescriptorProto::kMessageTypeFieldNumber, 0,
+ DescriptorProto::kOneofDeclFieldNumber, 0,
+ OneofDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
0,
DescriptorProto::kOneofDeclFieldNumber,
@@ -7225,16 +7212,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Enum option, repeated options
{
- int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 0};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
EnumDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 0};
- int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
- EnumDescriptorProto::kOptionsFieldNumber,
- EnumOptions::kUninterpretedOptionFieldNumber,
- 0};
+ EnumOptions::kUninterpretedOptionFieldNumber, 0};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("18:3-18:31", PrintSourceLocation(loc));
@@ -7243,16 +7226,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 1};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
EnumDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 1};
- int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
- EnumDescriptorProto::kOptionsFieldNumber,
- EnumOptions::kUninterpretedOptionFieldNumber,
- 1};
+ EnumOptions::kUninterpretedOptionFieldNumber, 1};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("19:3-19:31", PrintSourceLocation(loc));
@@ -7261,16 +7240,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
- EnumDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 2};
- int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
+ EnumDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 2};
+ int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber, 0,
EnumDescriptorProto::kOptionsFieldNumber,
- OneofOptions::kUninterpretedOptionFieldNumber,
- 2};
+ OneofOptions::kUninterpretedOptionFieldNumber, 2};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("20:3-20:31", PrintSourceLocation(loc));
@@ -7282,13 +7257,13 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Enum value options
{
// option w/ message type that directly sets field
- int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
- EnumDescriptorProto::kValueFieldNumber,
- 0,
- EnumValueDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- kA_aFieldNumber};
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kValueFieldNumber,
+ 0,
+ EnumValueDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber,
+ kAFieldNumber};
int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
0,
EnumDescriptorProto::kValueFieldNumber,
@@ -7304,12 +7279,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
- 0,
- EnumDescriptorProto::kValueFieldNumber,
- 1,
- EnumValueDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {FileDescriptorProto::kEnumTypeFieldNumber,
+ 0,
+ EnumDescriptorProto::kValueFieldNumber,
+ 1,
+ EnumValueDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kEnumTypeFieldNumber,
0,
EnumDescriptorProto::kValueFieldNumber,
@@ -7327,16 +7302,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Service option, repeated options
{
- int path[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kServiceFieldNumber, 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 0};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0,
ServiceDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 0};
- int unint[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
- ServiceDescriptorProto::kOptionsFieldNumber,
- ServiceOptions::kUninterpretedOptionFieldNumber,
- 0};
+ ServiceOptions::kUninterpretedOptionFieldNumber, 0};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("26:3-26:35", PrintSourceLocation(loc));
@@ -7345,16 +7316,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kServiceFieldNumber, 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 1};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0,
ServiceDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 1};
- int unint[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
- ServiceDescriptorProto::kOptionsFieldNumber,
- ServiceOptions::kUninterpretedOptionFieldNumber,
- 1};
+ ServiceOptions::kUninterpretedOptionFieldNumber, 1};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("27:3-27:35", PrintSourceLocation(loc));
@@ -7363,16 +7330,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
- ServiceDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber,
- 2};
- int unint[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kServiceFieldNumber, 0,
+ ServiceDescriptorProto::kOptionsFieldNumber,
+ kCustomOptionFieldNumber, 2};
+ int unint[] = {FileDescriptorProto::kServiceFieldNumber, 0,
ServiceDescriptorProto::kOptionsFieldNumber,
- ServiceOptions::kUninterpretedOptionFieldNumber,
- 2};
+ ServiceOptions::kUninterpretedOptionFieldNumber, 2};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("28:3-28:35", PrintSourceLocation(loc));
@@ -7383,12 +7346,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Method options
{
- int path[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
- ServiceDescriptorProto::kMethodFieldNumber,
- 1,
- MethodDescriptorProto::kOptionsFieldNumber,
- MethodOptions::kDeprecatedFieldNumber};
+ int path[] = {FileDescriptorProto::kServiceFieldNumber,
+ 0,
+ ServiceDescriptorProto::kMethodFieldNumber,
+ 1,
+ MethodDescriptorProto::kOptionsFieldNumber,
+ MethodOptions::kDeprecatedFieldNumber};
int unint[] = {FileDescriptorProto::kServiceFieldNumber,
0,
ServiceDescriptorProto::kMethodFieldNumber,
@@ -7404,12 +7367,10 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kServiceFieldNumber,
- 0,
- ServiceDescriptorProto::kMethodFieldNumber,
- 1,
- MethodDescriptorProto::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {
+ FileDescriptorProto::kServiceFieldNumber, 0,
+ ServiceDescriptorProto::kMethodFieldNumber, 1,
+ MethodDescriptorProto::kOptionsFieldNumber, kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kServiceFieldNumber,
0,
ServiceDescriptorProto::kMethodFieldNumber,
@@ -7427,22 +7388,20 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Extension range options
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 1,
- DescriptorProto::kExtensionRangeFieldNumber,
- 0,
- DescriptorProto_ExtensionRange::kOptionsFieldNumber};
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber, 1,
+ DescriptorProto::kExtensionRangeFieldNumber, 0,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber};
std::vector<int> vpath(path, path + 5);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("37:40-37:67", PrintSourceLocation(loc));
}
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 1,
- DescriptorProto::kExtensionRangeFieldNumber,
- 0,
- DescriptorProto_ExtensionRange::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 1,
+ DescriptorProto::kExtensionRangeFieldNumber,
+ 0,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
1,
DescriptorProto::kExtensionRangeFieldNumber,
@@ -7458,12 +7417,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
EXPECT_FALSE(file_desc->GetSourceLocation(vunint, &loc));
}
{
- int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
- 1,
- DescriptorProto::kExtensionRangeFieldNumber,
- 1,
- DescriptorProto_ExtensionRange::kOptionsFieldNumber,
- kCustomOptionFieldNumber};
+ int path[] = {FileDescriptorProto::kMessageTypeFieldNumber,
+ 1,
+ DescriptorProto::kExtensionRangeFieldNumber,
+ 1,
+ DescriptorProto_ExtensionRange::kOptionsFieldNumber,
+ kCustomOptionFieldNumber};
int unint[] = {FileDescriptorProto::kMessageTypeFieldNumber,
1,
DescriptorProto::kExtensionRangeFieldNumber,
@@ -7481,15 +7440,12 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
// Field option on extension
{
- int path[] = {FileDescriptorProto::kExtensionFieldNumber,
- 0,
+ int path[] = {FileDescriptorProto::kExtensionFieldNumber, 0,
+ FieldDescriptorProto::kOptionsFieldNumber,
+ FieldOptions::kPackedFieldNumber};
+ int unint[] = {FileDescriptorProto::kExtensionFieldNumber, 0,
FieldDescriptorProto::kOptionsFieldNumber,
- FieldOptions::kPackedFieldNumber};
- int unint[] = {FileDescriptorProto::kExtensionFieldNumber,
- 0,
- FieldDescriptorProto::kOptionsFieldNumber,
- FieldOptions::kUninterpretedOptionFieldNumber,
- 0};
+ FieldOptions::kUninterpretedOptionFieldNumber, 0};
std::vector<int> vpath(path, path + 4);
EXPECT_TRUE(file_desc->GetSourceLocation(vpath, &loc));
EXPECT_EQ("40:42-40:53", PrintSourceLocation(loc));
@@ -7503,7 +7459,7 @@ TEST_F(SourceLocationTest, InterpretedOptionSourceLocation) {
TEST_F(SourceLocationTest, GetSourceLocation_MissingSourceCodeInfo) {
SourceLocation loc;
- const FileDescriptor *file_desc =
+ const FileDescriptor* file_desc =
GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
FileDescriptorProto proto;
@@ -7521,7 +7477,7 @@ TEST_F(SourceLocationTest, GetSourceLocation_MissingSourceCodeInfo) {
TEST_F(SourceLocationTest, GetSourceLocation_BogusSourceCodeInfo) {
SourceLocation loc;
- const FileDescriptor *file_desc =
+ const FileDescriptor* file_desc =
GOOGLE_CHECK_NOTNULL(pool_.FindFileByName("/test/test.proto"));
FileDescriptorProto proto;
@@ -7890,7 +7846,7 @@ TEST_F(LazilyBuildDependenciesTest, GeneratedFile) {
// 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 =
+ const MessageOptions& options =
protobuf_unittest::lazy_imports::MessageCustomOption::descriptor()
->options();
protobuf_unittest::lazy_imports::LazyEnum custom_option_value =
@@ -7902,7 +7858,7 @@ TEST_F(LazilyBuildDependenciesTest, GeneratedFile) {
"google/protobuf/unittest_lazy_dependencies_enum.proto"));
EXPECT_EQ(custom_option_value, protobuf_unittest::lazy_imports::LAZY_ENUM_1);
- const google::protobuf::MessageOptions& options2 =
+ const MessageOptions& options2 =
protobuf_unittest::lazy_imports::MessageCustomOption2::descriptor()
->options();
custom_option_value =
diff --git a/src/google/protobuf/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc
index 437a04e7..55b9ecd3 100644
--- a/src/google/protobuf/drop_unknown_fields_test.cc
+++ b/src/google/protobuf/drop_unknown_fields_test.cc
@@ -35,35 +35,13 @@
#include <google/protobuf/message_lite.h>
#include <gtest/gtest.h>
-namespace google {
using unittest_drop_unknown_fields::Foo;
using unittest_drop_unknown_fields::FooWithExtraFields;
+namespace google {
namespace protobuf {
-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);
- 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_TRUE(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 be lost.
- EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value());
-}
-
-TEST(DropUnknownFieldsTest, GeneratedMessageDefaultPreserve) {
- ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true);
+TEST(DropUnknownFieldsTest, GeneratedMessage) {
FooWithExtraFields foo_with_extra_fields;
foo_with_extra_fields.set_int32_value(1);
foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX);
@@ -83,36 +61,14 @@ TEST(DropUnknownFieldsTest, GeneratedMessageDefaultPreserve) {
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);
- foo_with_extra_fields.set_extra_int32_value(2);
-
- google::protobuf::DynamicMessageFactory factory;
- std::unique_ptr<google::protobuf::Message> foo(
- factory.GetPrototype(Foo::descriptor())->New());
- ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString()));
- EXPECT_TRUE(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 be lost.
- EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value());
-}
-
-TEST(DropUnknownFieldsTest, DynamicMessageDefaultPreserve) {
- internal::SetProto3PreserveUnknownsDefault(true);
+TEST(DropUnknownFieldsTest, DynamicMessage) {
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;
- std::unique_ptr<google::protobuf::Message> foo(
- factory.GetPrototype(Foo::descriptor())->New());
+ DynamicMessageFactory factory;
+ std::unique_ptr<Message> foo(factory.GetPrototype(Foo::descriptor())->New());
ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString()));
EXPECT_FALSE(foo->GetReflection()->GetUnknownFields(*foo).empty());
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc
index ddc063db..02602d28 100644
--- a/src/google/protobuf/duration.pb.cc
+++ b/src/google/protobuf/duration.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class DurationDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Duration>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Duration> _instance;
} _Duration_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fduration_2eproto {
-static void InitDefaultsDuration() {
+static void InitDefaultsDuration_google_2fprotobuf_2fduration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,25 +35,27 @@ static void InitDefaultsDuration() {
::google::protobuf::Duration::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Duration_google_2fprotobuf_2fduration_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDuration_google_2fprotobuf_2fduration_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Duration.base);
+void InitDefaults_google_2fprotobuf_2fduration_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Duration_google_2fprotobuf_2fduration_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fduration_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Duration, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Duration, seconds_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Duration, nanos_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Duration)},
};
@@ -66,51 +63,33 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Duration_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/duration.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fduration_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fduration_2eproto, "google/protobuf/duration.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fduration_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fduration_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto, file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fduration_2eproto,
+ "\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"
+ "rationProtoP\001Z*github.com/golang/protobu"
+ "f/ptypes/duration\370\001\001\242\002\003GPB\252\002\036Google.Prot"
+ "obuf.WellKnownTypesb\006proto3"
+,
+ "google/protobuf/duration.proto", &assign_descriptors_table_google_2fprotobuf_2fduration_2eproto, 227,
+};
-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"
- "rationProtoP\001Z*github.com/golang/protobu"
- "f/ptypes/duration\370\001\001\242\002\003GPB\252\002\036Google.Prot"
- "obuf.WellKnownTypesb\006proto3"
+void AddDescriptors_google_2fprotobuf_2fduration_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 227);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/duration.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fduration_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fduration_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto = []() { AddDescriptors_google_2fprotobuf_2fduration_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -118,6 +97,10 @@ namespace protobuf {
void Duration::InitAsDefaultInstance() {
}
+class Duration::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Duration::kSecondsFieldNumber;
const int Duration::kNanosFieldNumber;
@@ -125,15 +108,12 @@ const int Duration::kNanosFieldNumber;
Duration::Duration()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Duration)
}
Duration::Duration(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Duration)
@@ -167,18 +147,13 @@ void Duration::ArenaDtor(void* object) {
Duration* _this = reinterpret_cast< Duration* >(object);
(void)_this;
}
-void Duration::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Duration::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Duration::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Duration::descriptor() {
- ::protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Duration& Duration::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fduration_2eproto::scc_info_Duration.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Duration_google_2fprotobuf_2fduration_2eproto.base);
return *internal_default_instance();
}
@@ -195,9 +170,66 @@ void Duration::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Duration::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Duration*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // int64 seconds = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int64 value = val;
+ msg->set_seconds(value);
+ break;
+ }
+ // int32 nanos = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_nanos(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Duration::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Duration)
for (;;) {
@@ -207,8 +239,7 @@ bool Duration::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 seconds = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -221,8 +252,7 @@ bool Duration::MergePartialFromCodedStream(
// int32 nanos = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -252,6 +282,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Duration::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -269,9 +300,9 @@ void Duration::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Duration)
}
@@ -293,9 +324,9 @@ void Duration::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Duration)
return target;
@@ -305,11 +336,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
total_size += 1 +
@@ -333,7 +368,7 @@ void Duration::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Duration)
GOOGLE_DCHECK_NE(&from, this);
const Duration* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Duration>(
+ ::google::protobuf::DynamicCastToGenerated<Duration>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Duration)
@@ -398,14 +433,14 @@ void Duration::UnsafeArenaSwap(Duration* other) {
}
void Duration::InternalSwap(Duration* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
swap(seconds_, other->seconds_);
swap(nanos_, other->nanos_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Duration::GetMetadata() const {
- protobuf_google_2fprotobuf_2fduration_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fduration_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fduration_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fduration_2eproto[kIndexInFileMessages];
}
@@ -414,10 +449,11 @@ void Duration::InternalSwap(Duration* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Duration* Arena::CreateMaybeMessage< ::google::protobuf::Duration >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Duration >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index 19241ebc..78d94665 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,30 +32,28 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fduration_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fduration_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fduration_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fduration_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fduration_2eproto();
namespace google {
namespace protobuf {
class Duration;
class DurationDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*);
+PROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Duration* Arena::CreateMaybeMessage<::google::protobuf::Duration>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -62,7 +61,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ {
+class PROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ {
public:
Duration();
virtual ~Duration();
@@ -94,7 +93,9 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Duration& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -128,8 +129,13 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -175,6 +181,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
// @@protoc_insertion_point(class_scope:google.protobuf.Duration)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -183,7 +190,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fduration_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fduration_2eproto;
};
// ===================================================================
@@ -198,7 +205,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
// int64 seconds = 1;
inline void Duration::clear_seconds() {
- seconds_ = GOOGLE_LONGLONG(0);
+ seconds_ = PROTOBUF_LONGLONG(0);
}
inline ::google::protobuf::int64 Duration::seconds() const {
// @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds)
@@ -235,4 +242,5 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto
diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc
index ceedf500..6e4338f4 100644
--- a/src/google/protobuf/dynamic_message.cc
+++ b/src/google/protobuf/dynamic_message.cc
@@ -63,16 +63,16 @@
// I don't have the book on me right now so I'm not sure.
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <memory>
+#include <unordered_map>
-#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/hash.h>
-#include <google/protobuf/dynamic_message.h>
-#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/generated_message_reflection.h>
+#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/map_field.h>
@@ -258,14 +258,14 @@ class DynamicMessage : public Message {
// implements Message ----------------------------------------------
- Message* New() const;
- Message* New(::google::protobuf::Arena* arena) const;
- ::google::protobuf::Arena* GetArena() const { return arena_; }
+ Message* New() const override;
+ Message* New(Arena* arena) const override;
+ Arena* GetArena() const override { return arena_; }
- int GetCachedSize() const;
- void SetCachedSize(int size) const;
+ int GetCachedSize() const override;
+ void SetCachedSize(int size) const override;
- Metadata GetMetadata() const;
+ Metadata GetMetadata() const override;
// We actually allocate more memory than sizeof(*this) when this
// class's memory is allocated via the global operator new. Thus, we need to
@@ -279,7 +279,7 @@ class DynamicMessage : public Message {
#endif // !_MSC_VER
private:
- DynamicMessage(const TypeInfo* type_info, ::google::protobuf::Arena* arena);
+ DynamicMessage(const TypeInfo* type_info, Arena* arena);
void SharedCtor(bool lock_factory);
@@ -299,8 +299,7 @@ class DynamicMessage : public Message {
const TypeInfo* type_info_;
Arena* const arena_;
- // TODO(kenton): Make this an atomic<int> when C++ supports it.
- mutable int cached_byte_size_;
+ mutable std::atomic<int> cached_byte_size_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage);
};
@@ -309,8 +308,7 @@ DynamicMessage::DynamicMessage(const TypeInfo* type_info)
SharedCtor(true);
}
-DynamicMessage::DynamicMessage(const TypeInfo* type_info,
- ::google::protobuf::Arena* arena)
+DynamicMessage::DynamicMessage(const TypeInfo* type_info, Arena* arena)
: type_info_(type_info), arena_(arena), cached_byte_size_(0) {
SharedCtor(true);
}
@@ -579,7 +577,7 @@ void DynamicMessage::CrossLinkPrototypes() {
Message* DynamicMessage::New() const { return New(NULL); }
-Message* DynamicMessage::New(::google::protobuf::Arena* arena) const {
+Message* DynamicMessage::New(Arena* arena) const {
if (arena != NULL) {
void* new_base = Arena::CreateArray<char>(arena, type_info_->size);
memset(new_base, 0, type_info_->size);
@@ -592,16 +590,11 @@ Message* DynamicMessage::New(::google::protobuf::Arena* arena) const {
}
int DynamicMessage::GetCachedSize() const {
- return cached_byte_size_;
+ return cached_byte_size_.load(std::memory_order_relaxed);
}
void DynamicMessage::SetCachedSize(int size) const {
- // This is theoretically not thread-compatible, but in practice it works
- // because if multiple threads write this simultaneously, they will be
- // writing the exact same value.
- GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- cached_byte_size_ = size;
- GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ cached_byte_size_.store(size, std::memory_order_relaxed);
}
Metadata DynamicMessage::GetMetadata() const {
@@ -614,7 +607,8 @@ Metadata DynamicMessage::GetMetadata() const {
// ===================================================================
struct DynamicMessageFactory::PrototypeMap {
- typedef hash_map<const Descriptor*, const DynamicMessage::TypeInfo*> Map;
+ typedef std::unordered_map<const Descriptor*, const DynamicMessage::TypeInfo*>
+ Map;
Map map_;
};
diff --git a/src/google/protobuf/dynamic_message.h b/src/google/protobuf/dynamic_message.h
index d84cc8af..1ea6f66f 100644
--- a/src/google/protobuf/dynamic_message.h
+++ b/src/google/protobuf/dynamic_message.h
@@ -43,9 +43,15 @@
#include <vector>
#include <google/protobuf/message.h>
+#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/mutex.h>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -71,7 +77,7 @@ class DescriptorPool; // descriptor.h
// encapsulates this "cache". All DynamicMessages of the same type created
// from the same factory will share the same support data. Any Descriptors
// used with a particular factory must outlive the factory.
-class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
+class PROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
public:
// Construct a DynamicMessageFactory that will search for extensions in
// the DescriptorPool in which the extendee is defined.
@@ -115,20 +121,20 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
// outlive the DynamicMessageFactory.
//
// The method is thread-safe.
- const Message* GetPrototype(const Descriptor* type);
+ const Message* GetPrototype(const Descriptor* type) override;
private:
const DescriptorPool* pool_;
bool delegate_to_generated_factory_;
- // This struct just contains a hash_map. We can't #include <google/protobuf/stubs/hash.h> from
+ // This struct just contains a hash_map. We can't #include <hash_map> from
// this header due to hacks needed for hash_map portability in the open source
// release. Namely, stubs/hash.h, which defines hash_map portably, is not a
// public header (for good reason), but dynamic_message.h is, and public
// headers may only #include other public headers.
struct PrototypeMap;
std::unique_ptr<PrototypeMap> prototypes_;
- mutable Mutex prototypes_mutex_;
+ mutable internal::WrappedMutex prototypes_mutex_;
friend class DynamicMessage;
const Message* GetPrototypeNoLock(const Descriptor* type);
@@ -147,7 +153,7 @@ class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
};
// Helper for computing a sorted list of map entries via reflection.
-class LIBPROTOBUF_EXPORT DynamicMapSorter {
+class PROTOBUF_EXPORT DynamicMapSorter {
public:
static std::vector<const Message*> Sort(const Message& message,
int map_size,
@@ -178,7 +184,7 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter {
}
private:
- class LIBPROTOBUF_EXPORT MapEntryMessageComparator {
+ class PROTOBUF_EXPORT MapEntryMessageComparator {
public:
explicit MapEntryMessageComparator(const Descriptor* descriptor)
: field_(descriptor->field(0)) {}
@@ -212,8 +218,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter {
return first < second;
}
case FieldDescriptor::CPPTYPE_STRING: {
- string first = reflection->GetString(*a, field_);
- string second = reflection->GetString(*b, field_);
+ std::string first = reflection->GetString(*a, field_);
+ std::string second = reflection->GetString(*b, field_);
return first < second;
}
default:
@@ -228,6 +234,8 @@ class LIBPROTOBUF_EXPORT DynamicMapSorter {
};
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index 9b53c546..9d0f9ae0 100644
--- a/src/google/protobuf/empty.pb.cc
+++ b/src/google/protobuf/empty.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class EmptyDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Empty>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Empty> _instance;
} _Empty_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fempty_2eproto {
-static void InitDefaultsEmpty() {
+static void InitDefaultsEmpty_google_2fprotobuf_2fempty_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,23 +35,25 @@ static void InitDefaultsEmpty() {
::google::protobuf::Empty::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Empty_google_2fprotobuf_2fempty_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEmpty_google_2fprotobuf_2fempty_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Empty.base);
+void InitDefaults_google_2fprotobuf_2fempty_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Empty_google_2fprotobuf_2fempty_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fempty_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Empty, _internal_metadata_),
+ PROTOBUF_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) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Empty)},
};
@@ -64,50 +61,32 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Empty_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/empty.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fempty_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fempty_2eproto, "google/protobuf/empty.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fempty_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fempty_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto, file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fempty_2eproto,
+ "\n\033google/protobuf/empty.proto\022\017google.pr"
+ "otobuf\"\007\n\005EmptyBv\n\023com.google.protobufB\n"
+ "EmptyProtoP\001Z\'github.com/golang/protobuf"
+ "/ptypes/empty\370\001\001\242\002\003GPB\252\002\036Google.Protobuf"
+ ".WellKnownTypesb\006proto3"
+,
+ "google/protobuf/empty.proto", &assign_descriptors_table_google_2fprotobuf_2fempty_2eproto, 183,
+};
-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"
- "/ptypes/empty\370\001\001\242\002\003GPB\252\002\036Google.Protobuf"
- ".WellKnownTypesb\006proto3"
+void AddDescriptors_google_2fprotobuf_2fempty_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 183);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/empty.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fempty_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fempty_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto = []() { AddDescriptors_google_2fprotobuf_2fempty_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -115,20 +94,21 @@ namespace protobuf {
void Empty::InitAsDefaultInstance() {
}
+class Empty::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Empty::Empty()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Empty)
}
Empty::Empty(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Empty)
@@ -156,18 +136,13 @@ void Empty::ArenaDtor(void* object) {
Empty* _this = reinterpret_cast< Empty* >(object);
(void)_this;
}
-void Empty::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Empty::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Empty::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Empty::descriptor() {
- ::protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Empty& Empty::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fempty_2eproto::scc_info_Empty.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Empty_google_2fprotobuf_2fempty_2eproto.base);
return *internal_default_instance();
}
@@ -181,9 +156,46 @@ void Empty::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Empty::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Empty*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Empty::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Empty)
for (;;) {
@@ -205,6 +217,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Empty::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -212,9 +225,9 @@ void Empty::SerializeWithCachedSizes(
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Empty)
}
@@ -226,9 +239,9 @@ void Empty::SerializeWithCachedSizes(
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Empty)
return target;
@@ -238,11 +251,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
@@ -252,7 +269,7 @@ void Empty::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Empty)
GOOGLE_DCHECK_NE(&from, this);
const Empty* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Empty>(
+ ::google::protobuf::DynamicCastToGenerated<Empty>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Empty)
@@ -315,8 +332,8 @@ void Empty::InternalSwap(Empty* other) {
}
::google::protobuf::Metadata Empty::GetMetadata() const {
- protobuf_google_2fprotobuf_2fempty_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fempty_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fempty_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fempty_2eproto[kIndexInFileMessages];
}
@@ -325,10 +342,11 @@ void Empty::InternalSwap(Empty* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Empty* Arena::CreateMaybeMessage< ::google::protobuf::Empty >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Empty >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 4d651080..39b944b1 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,30 +32,28 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fempty_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fempty_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fempty_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fempty_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fempty_2eproto();
namespace google {
namespace protobuf {
class Empty;
class EmptyDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*);
+PROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Empty* Arena::CreateMaybeMessage<::google::protobuf::Empty>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -62,7 +61,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ {
+class PROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ {
public:
Empty();
virtual ~Empty();
@@ -94,7 +93,9 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Empty& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -128,8 +129,13 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -163,13 +169,14 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(class_scope:google.protobuf.Empty)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fempty_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fempty_2eproto;
};
// ===================================================================
@@ -193,4 +200,5 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc
index cb205c4f..6629ec04 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -32,16 +32,25 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-#include <google/protobuf/stubs/hash.h>
+#include <google/protobuf/extension_set.h>
+
#include <tuple>
+#include <unordered_map>
#include <utility>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/extension_set.h>
-#include <google/protobuf/message_lite.h>
#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/wire_format_lite_inl.h>
+#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/stubs/map_util.h>
+#include <google/protobuf/stubs/hash.h>
+
+#include <google/protobuf/port_def.inc>
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
namespace google {
namespace protobuf {
@@ -77,8 +86,16 @@ inline bool is_packable(WireFormatLite::WireType type) {
}
// Registry stuff.
-typedef hash_map<std::pair<const MessageLite*, int>,
- ExtensionInfo> ExtensionRegistry;
+struct ExtensionHasher {
+ std::size_t operator()(const std::pair<const MessageLite*, int>& p) const {
+ return std::hash<const MessageLite*>{}(p.first) ^
+ std::hash<int>{}(p.second);
+ }
+};
+
+typedef std::unordered_map<std::pair<const MessageLite*, int>, ExtensionInfo,
+ ExtensionHasher>
+ ExtensionRegistry;
static const ExtensionRegistry* global_registry = nullptr;
@@ -89,7 +106,7 @@ void Register(const MessageLite* containing_type,
static auto local_static_registry = OnShutdownDelete(new ExtensionRegistry);
global_registry = local_static_registry;
if (!InsertIfNotPresent(local_static_registry,
- std::make_pair(containing_type, number), info)) {
+ std::make_pair(containing_type, number), info)) {
GOOGLE_LOG(FATAL) << "Multiple extension registrations for type \""
<< containing_type->GetTypeName()
<< "\", field number " << number << ".";
@@ -99,8 +116,9 @@ void Register(const MessageLite* containing_type,
const ExtensionInfo* FindRegisteredExtension(
const MessageLite* containing_type, int number) {
return global_registry == nullptr
- ? nullptr
- : FindOrNull(*global_registry, std::make_pair(containing_type, number));
+ ? nullptr
+ : FindOrNull(*global_registry,
+ std::make_pair(containing_type, number));
}
} // namespace
@@ -168,34 +186,50 @@ void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type,
// ===================================================================
// Constructors and basic methods.
-ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena)
+ExtensionSet::ExtensionSet(Arena* arena)
: arena_(arena),
flat_capacity_(0),
flat_size_(0),
- map_{flat_capacity_ == 0 ? NULL
- : ::google::protobuf::Arena::CreateArray<KeyValue>(
- arena_, flat_capacity_)} {}
+ map_{flat_capacity_ == 0
+ ? NULL
+ : Arena::CreateArray<KeyValue>(arena_, flat_capacity_)} {}
ExtensionSet::ExtensionSet()
: arena_(NULL),
flat_capacity_(0),
flat_size_(0),
- map_{flat_capacity_ == 0 ? NULL
- : ::google::protobuf::Arena::CreateArray<KeyValue>(
- arena_, flat_capacity_)} {}
+ map_{flat_capacity_ == 0
+ ? NULL
+ : Arena::CreateArray<KeyValue>(arena_, flat_capacity_)} {}
ExtensionSet::~ExtensionSet() {
// Deletes all allocated extensions.
if (arena_ == NULL) {
ForEach([](int /* number */, Extension& ext) { ext.Free(); });
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
delete map_.large;
} else {
- delete[] map_.flat;
+ DeleteFlatMap(map_.flat, flat_capacity_);
}
}
}
+void ExtensionSet::DeleteFlatMap(
+ const ExtensionSet::KeyValue* flat, uint16 flat_capacity) {
+#ifdef __cpp_sized_deallocation
+ // Arena::CreateArray already requires a trivially destructible type, but
+ // ensure this constraint is not violated in the future.
+ static_assert(std::is_trivially_destructible<KeyValue>::value,
+ "CreateArray requires a trivially destructible type");
+ // A const-cast is needed, but this is safe as we are about to deallocate the
+ // array.
+ ::operator delete[](
+ const_cast<ExtensionSet::KeyValue*>(flat), sizeof(*flat) * flat_capacity);
+#else // !__cpp_sized_deallocation
+ delete[] flat;
+#endif // !__cpp_sized_deallocation
+}
+
// Defined in extension_set_heavy.cc.
// void ExtensionSet::AppendToList(const Descriptor* containing_type,
// const DescriptorPool* pool,
@@ -594,7 +628,7 @@ void ExtensionSet::SetAllocatedMessage(int number, FieldType type,
ClearExtension(number);
return;
}
- ::google::protobuf::Arena* message_arena = message->GetArena();
+ Arena* message_arena = message->GetArena();
Extension* extension;
if (MaybeNewExtension(number, descriptor, &extension)) {
extension->type = type;
@@ -746,10 +780,9 @@ MessageLite* ExtensionSet::AddMessage(int number, FieldType type,
// RepeatedPtrField<MessageLite> does not know how to Add() since it cannot
// allocate an abstract object, so we have to be tricky.
- MessageLite* result =
- reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
- extension->repeated_message_value)
- ->AddFromCleared<GenericTypeHandler<MessageLite> >();
+ MessageLite* result = reinterpret_cast<internal::RepeatedPtrFieldBase*>(
+ extension->repeated_message_value)
+ ->AddFromCleared<GenericTypeHandler<MessageLite>>();
if (result == NULL) {
result = prototype.New(arena_);
extension->repeated_message_value->AddAllocated(result);
@@ -879,8 +912,8 @@ size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) {
} // namespace
void ExtensionSet::MergeFrom(const ExtensionSet& other) {
- if (GOOGLE_PREDICT_TRUE(!is_large())) {
- if (GOOGLE_PREDICT_TRUE(!other.is_large())) {
+ if (PROTOBUF_PREDICT_TRUE(!is_large())) {
+ if (PROTOBUF_PREDICT_TRUE(!other.is_large())) {
GrowCapacity(SizeOfUnion(flat_begin(), flat_end(), other.flat_begin(),
other.flat_end()));
} else {
@@ -945,9 +978,9 @@ void ExtensionSet::InternalExtensionMergeFrom(
for (int i = 0; i < other_repeated_message->size(); i++) {
const MessageLite& other_message = other_repeated_message->Get(i);
MessageLite* target =
- reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ reinterpret_cast<internal::RepeatedPtrFieldBase*>(
extension->repeated_message_value)
- ->AddFromCleared<GenericTypeHandler<MessageLite> >();
+ ->AddFromCleared<GenericTypeHandler<MessageLite>>();
if (target == NULL) {
target = other_message.New(arena_);
extension->repeated_message_value->AddAllocated(target);
@@ -1108,7 +1141,7 @@ void ExtensionSet::SwapExtension(ExtensionSet* other,
bool ExtensionSet::IsInitialized() const {
// Extensions are never required. However, we need to check that all
// embedded messages are initialized.
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
for (const auto& kv : *map_.large) {
if (!kv.second.IsInitialized()) return false;
}
@@ -1167,6 +1200,212 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
}
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+std::pair<const char*, bool> ExtensionSet::ParseField(
+ uint64 tag, ParseClosure parent, const char* begin, const char* end,
+ const MessageLite* containing_type,
+ internal::InternalMetadataWithArenaLite* metadata,
+ internal::ParseContext* ctx) {
+ GeneratedExtensionFinder finder(containing_type);
+ int number = tag >> 3;
+ bool was_packed_on_wire;
+ ExtensionInfo extension;
+ if (!FindExtensionInfoFromFieldNumber(tag & 7, number, &finder, &extension,
+ &was_packed_on_wire)) {
+ return UnknownFieldParse(tag, parent, begin, end,
+ metadata->mutable_unknown_fields(), ctx);
+ }
+ auto ptr = begin;
+ ParseClosure child;
+ int depth;
+ if (was_packed_on_wire) {
+ switch (extension.type) {
+#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE) \
+ case WireFormatLite::TYPE_##UPPERCASE: \
+ child = { \
+ internal::Packed##CPP_CAMELCASE##Parser, \
+ MutableRawRepeatedField(number, extension.type, extension.is_packed, \
+ extension.descriptor)}; \
+ goto length_delim
+ HANDLE_TYPE(INT32, Int32);
+ HANDLE_TYPE(INT64, Int64);
+ HANDLE_TYPE(UINT32, UInt32);
+ HANDLE_TYPE(UINT64, UInt64);
+ HANDLE_TYPE(SINT32, SInt32);
+ HANDLE_TYPE(SINT64, SInt64);
+ HANDLE_TYPE(FIXED32, Fixed32);
+ HANDLE_TYPE(FIXED64, Fixed64);
+ HANDLE_TYPE(SFIXED32, SFixed32);
+ HANDLE_TYPE(SFIXED64, SFixed64);
+ HANDLE_TYPE(FLOAT, Float);
+ HANDLE_TYPE(DOUBLE, Double);
+ HANDLE_TYPE(BOOL, Bool);
+#undef HANDLE_TYPE
+
+ case WireFormatLite::TYPE_ENUM:
+ ctx->extra_parse_data().SetEnumValidatorArg(
+ extension.enum_validity_check.func,
+ extension.enum_validity_check.arg,
+ metadata->mutable_unknown_fields(), tag >> 3);
+ child = {
+ internal::PackedValidEnumParserLiteArg,
+ MutableRawRepeatedField(number, extension.type, extension.is_packed,
+ extension.descriptor)};
+ goto length_delim;
+ case WireFormatLite::TYPE_STRING:
+ case WireFormatLite::TYPE_BYTES:
+ case WireFormatLite::TYPE_GROUP:
+ case WireFormatLite::TYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed.";
+ break;
+ }
+ } else {
+ switch (extension.type) {
+#define HANDLE_VARINT_TYPE(UPPERCASE, CPP_CAMELCASE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ uint64 value; \
+ ptr = Varint::Parse64(ptr, &value); \
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_VARINT_TYPE(INT32, Int32);
+ HANDLE_VARINT_TYPE(INT64, Int64);
+ HANDLE_VARINT_TYPE(UINT32, UInt32);
+ HANDLE_VARINT_TYPE(UINT64, UInt64);
+#undef HANDLE_VARINT_TYPE
+#define HANDLE_SVARINT_TYPE(UPPERCASE, CPP_CAMELCASE, SIZE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ uint64 val; \
+ ptr = Varint::Parse64(ptr, &val); \
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \
+ auto value = WireFormatLite::ZigZagDecode##SIZE(val); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_SVARINT_TYPE(SINT32, Int32, 32);
+ HANDLE_SVARINT_TYPE(SINT64, Int64, 64);
+#undef HANDLE_SVARINT_TYPE
+#define HANDLE_FIXED_TYPE(UPPERCASE, CPP_CAMELCASE, CPPTYPE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ CPPTYPE value; \
+ std::memcpy(&value, ptr, sizeof(CPPTYPE)); \
+ ptr += sizeof(CPPTYPE); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_FIXED_TYPE(FIXED32, UInt32, uint32);
+ HANDLE_FIXED_TYPE(FIXED64, UInt64, uint64);
+ HANDLE_FIXED_TYPE(SFIXED32, Int32, int32);
+ HANDLE_FIXED_TYPE(SFIXED64, Int64, int64);
+ HANDLE_FIXED_TYPE(FLOAT, Float, float);
+ HANDLE_FIXED_TYPE(DOUBLE, Double, double);
+ HANDLE_FIXED_TYPE(BOOL, Bool, bool);
+#undef HANDLE_FIXED_TYPE
+
+ case WireFormatLite::TYPE_ENUM: {
+ uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ int value = val;
+
+ if (!extension.enum_validity_check.func(
+ extension.enum_validity_check.arg, value)) {
+ WriteVarint(number, val, metadata->mutable_unknown_fields());
+ } else if (extension.is_repeated) {
+ AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value,
+ extension.descriptor);
+ } else {
+ SetEnum(number, WireFormatLite::TYPE_ENUM, value,
+ extension.descriptor);
+ }
+ break;
+ }
+
+ case WireFormatLite::TYPE_BYTES:
+ case WireFormatLite::TYPE_STRING: {
+ string* value = extension.is_repeated
+ ? AddString(number, WireFormatLite::TYPE_STRING,
+ extension.descriptor)
+ : MutableString(number, WireFormatLite::TYPE_STRING,
+ extension.descriptor);
+ child = {StringParser, value};
+ goto length_delim;
+ }
+
+ case WireFormatLite::TYPE_GROUP: {
+ MessageLite* value =
+ extension.is_repeated
+ ? AddMessage(number, WireFormatLite::TYPE_GROUP,
+ *extension.message_prototype, extension.descriptor)
+ : MutableMessage(number, WireFormatLite::TYPE_GROUP,
+ *extension.message_prototype,
+ extension.descriptor);
+ child = {value->_ParseFunc(), value};
+ bool ok = ctx->PrepareGroup(tag, &depth);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = child(ptr, end, ctx);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ if (ctx->GroupContinues(depth)) goto group_continues;
+ break;
+ }
+
+ case WireFormatLite::TYPE_MESSAGE: {
+ MessageLite* value =
+ extension.is_repeated
+ ? AddMessage(number, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype, extension.descriptor)
+ : MutableMessage(number, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype,
+ extension.descriptor);
+ child = {value->_ParseFunc(), value};
+ goto length_delim;
+ }
+ }
+ }
+
+ return std::make_pair(ptr, false);
+
+length_delim:
+ uint32 size;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ if (size > end - ptr) goto len_delim_till_end;
+ {
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange(child, ptr, newend);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = newend;
+ }
+ return std::make_pair(ptr, false);
+len_delim_till_end:
+ return std::make_pair(ctx->StoreAndTailCall(ptr, end, parent, child, size),
+ true);
+
+group_continues:
+ ctx->StoreGroup(parent, child, depth);
+ return std::make_pair(ptr, true);
+}
+#endif
+
bool ExtensionSet::ParseFieldWithExtensionInfo(
int number, bool was_packed_on_wire, const ExtensionInfo& extension,
io::CodedInputStream* input,
@@ -1342,20 +1581,65 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
return ParseField(tag, input, &finder, &skipper);
}
-// Defined in extension_set_heavy.cc.
-// bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
-// const MessageLite* containing_type,
-// UnknownFieldSet* unknown_fields)
+bool ExtensionSet::ParseMessageSetLite(io::CodedInputStream* input,
+ ExtensionFinder* extension_finder,
+ FieldSkipper* field_skipper) {
+ while (true) {
+ const uint32 tag = input->ReadTag();
+ switch (tag) {
+ case 0:
+ return true;
+ case WireFormatLite::kMessageSetItemStartTag:
+ if (!ParseMessageSetItemLite(input, extension_finder, field_skipper)) {
+ return false;
+ }
+ break;
+ default:
+ if (!ParseField(tag, input, extension_finder, field_skipper)) {
+ return false;
+ }
+ break;
+ }
+ }
+}
-// Defined in extension_set_heavy.cc.
-// bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
-// const MessageLite* containing_type,
-// UnknownFieldSet* unknown_fields);
+bool ExtensionSet::ParseMessageSetItemLite(io::CodedInputStream* input,
+ ExtensionFinder* extension_finder,
+ FieldSkipper* field_skipper) {
+ struct MSLite {
+ bool ParseField(int type_id, io::CodedInputStream* input) {
+ return me->ParseField(
+ WireFormatLite::WIRETYPE_LENGTH_DELIMITED + 8 * type_id, input,
+ extension_finder, field_skipper);
+ }
+
+ bool SkipField(uint32 tag, io::CodedInputStream* input) {
+ return field_skipper->SkipField(input, tag);
+ }
+
+ ExtensionSet* me;
+ ExtensionFinder* extension_finder;
+ FieldSkipper* field_skipper;
+ };
+
+ return ParseMessageSetItemImpl(input,
+ MSLite{this, extension_finder, field_skipper});
+}
+
+bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
+ const MessageLite* containing_type,
+ string* unknown_fields) {
+ io::StringOutputStream zcis(unknown_fields);
+ io::CodedOutputStream output(&zcis);
+ CodedOutputStreamFieldSkipper skipper(&output);
+ GeneratedExtensionFinder finder(containing_type);
+ return ParseMessageSetLite(input, &finder, &skipper);
+}
void ExtensionSet::SerializeWithCachedSizes(
int start_field_number, int end_field_number,
io::CodedOutputStream* output) const {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
const auto& end = map_.large->end();
for (auto it = map_.large->lower_bound(start_field_number);
it != end && it->first < end_field_number; ++it) {
@@ -1785,7 +2069,7 @@ bool ExtensionSet::Extension::IsInitialized() const {
void ExtensionSet::LazyMessageExtension::UnusedKeyMethod() {}
const ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) const {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
return FindOrNullInLargeMap(key);
}
const KeyValue* end = flat_end();
@@ -1808,7 +2092,7 @@ const ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(
}
ExtensionSet::Extension* ExtensionSet::FindOrNull(int key) {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
return FindOrNullInLargeMap(key);
}
KeyValue* end = flat_end();
@@ -1830,7 +2114,7 @@ ExtensionSet::Extension* ExtensionSet::FindOrNullInLargeMap(int key) {
}
std::pair<ExtensionSet::Extension*, bool> ExtensionSet::Insert(int key) {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
auto maybe = map_.large->insert({key, Extension()});
return {&maybe.first->second, maybe.second};
}
@@ -1852,13 +2136,15 @@ std::pair<ExtensionSet::Extension*, bool> ExtensionSet::Insert(int key) {
}
void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
return; // LargeMap does not have a "reserve" method.
}
if (flat_capacity_ >= minimum_new_capacity) {
return;
}
+ const auto old_flat_capacity = flat_capacity_;
+
do {
flat_capacity_ = flat_capacity_ == 0 ? 1 : flat_capacity_ * 4;
} while (flat_capacity_ < minimum_new_capacity);
@@ -1867,24 +2153,26 @@ void ExtensionSet::GrowCapacity(size_t minimum_new_capacity) {
const KeyValue* end = flat_end();
if (flat_capacity_ > kMaximumFlatCapacity) {
// Switch to LargeMap
- map_.large = ::google::protobuf::Arena::Create<LargeMap>(arena_);
+ map_.large = Arena::Create<LargeMap>(arena_);
LargeMap::iterator hint = map_.large->begin();
for (const KeyValue* it = begin; it != end; ++it) {
hint = map_.large->insert(hint, {it->first, it->second});
}
flat_size_ = 0;
} else {
- map_.flat = ::google::protobuf::Arena::CreateArray<KeyValue>(arena_, flat_capacity_);
+ map_.flat = Arena::CreateArray<KeyValue>(arena_, flat_capacity_);
std::copy(begin, end, map_.flat);
}
- if (arena_ == NULL) delete[] begin;
+ if (arena_ == nullptr) {
+ DeleteFlatMap(begin, old_flat_capacity);
+ }
}
// static
constexpr uint16 ExtensionSet::kMaximumFlatCapacity;
void ExtensionSet::Erase(int key) {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
map_.large->erase(key);
return;
}
@@ -1911,6 +2199,82 @@ RepeatedStringTypeTraits::GetDefaultRepeatedField() {
return instance;
}
+void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes(
+ int number,
+ io::CodedOutputStream* output) const {
+ if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
+ // Not a valid MessageSet extension, but serialize it the normal way.
+ SerializeFieldWithCachedSizes(number, output);
+ return;
+ }
+
+ if (is_cleared) return;
+
+ // Start group.
+ output->WriteTag(WireFormatLite::kMessageSetItemStartTag);
+
+ // Write type ID.
+ WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber,
+ number,
+ output);
+ // Write message.
+ if (is_lazy) {
+ lazymessage_value->WriteMessage(
+ WireFormatLite::kMessageSetMessageNumber, output);
+ } else {
+ WireFormatLite::WriteMessageMaybeToArray(
+ WireFormatLite::kMessageSetMessageNumber,
+ *message_value,
+ output);
+ }
+
+ // End group.
+ output->WriteTag(WireFormatLite::kMessageSetItemEndTag);
+}
+
+size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
+ if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
+ // Not a valid MessageSet extension, but compute the byte size for it the
+ // normal way.
+ return ByteSize(number);
+ }
+
+ if (is_cleared) return 0;
+
+ size_t our_size = WireFormatLite::kMessageSetItemTagsSize;
+
+ // type_id
+ our_size += io::CodedOutputStream::VarintSize32(number);
+
+ // message
+ size_t message_size = 0;
+ if (is_lazy) {
+ message_size = lazymessage_value->ByteSizeLong();
+ } else {
+ message_size = message_value->ByteSizeLong();
+ }
+
+ our_size += io::CodedOutputStream::VarintSize32(message_size);
+ our_size += message_size;
+
+ return our_size;
+}
+
+void ExtensionSet::SerializeMessageSetWithCachedSizes(
+ io::CodedOutputStream* output) const {
+ ForEach([output](int number, const Extension& ext) {
+ ext.SerializeMessageSetItemWithCachedSizes(number, output);
+ });
+}
+
+size_t ExtensionSet::MessageSetByteSize() const {
+ size_t total_size = 0;
+ ForEach([&total_size](int number, const Extension& ext) {
+ total_size += ext.MessageSetItemByteSize(number);
+ });
+ return total_size;
+}
+
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h
index a1535baa..b31c8c4f 100644
--- a/src/google/protobuf/extension_set.h
+++ b/src/google/protobuf/extension_set.h
@@ -47,32 +47,47 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/repeated_field.h>
+#include <google/protobuf/wire_format_lite.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+namespace google {
namespace protobuf {
- class Arena;
- class Descriptor; // descriptor.h
- class FieldDescriptor; // descriptor.h
- class DescriptorPool; // descriptor.h
- class MessageLite; // message_lite.h
- class Message; // message.h
- class MessageFactory; // message.h
- class UnknownFieldSet; // unknown_field_set.h
- namespace io {
- class CodedInputStream; // coded_stream.h
- class CodedOutputStream; // coded_stream.h
- }
- namespace internal {
- class FieldSkipper; // wire_format_lite.h
- }
+class Arena;
+class Descriptor; // descriptor.h
+class FieldDescriptor; // descriptor.h
+class DescriptorPool; // descriptor.h
+class MessageLite; // message_lite.h
+class Message; // message.h
+class MessageFactory; // message.h
+class UnknownFieldSet; // unknown_field_set.h
+namespace io {
+class CodedInputStream; // coded_stream.h
+class CodedOutputStream; // coded_stream.h
+} // namespace io
+namespace internal {
+class FieldSkipper; // wire_format_lite.h
}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace internal {
+class InternalMetadataWithArenaLite;
+class InternalMetadataWithArena;
+
// Used to store values of type WireFormatLite::FieldType without having to
// #include wire_format_lite.h. Also, ensures that we use only one byte to
// store these values, which is important to keep the layout of
@@ -92,7 +107,9 @@ typedef bool EnumValidityFuncWithArg(const void* arg, int number);
struct ExtensionInfo {
inline ExtensionInfo() {}
inline ExtensionInfo(FieldType type_param, bool isrepeated, bool ispacked)
- : type(type_param), is_repeated(isrepeated), is_packed(ispacked),
+ : type(type_param),
+ is_repeated(isrepeated),
+ is_packed(ispacked),
descriptor(NULL) {}
FieldType type;
@@ -117,7 +134,7 @@ struct ExtensionInfo {
// Abstract interface for an object which looks up extension definitions. Used
// when parsing.
-class LIBPROTOBUF_EXPORT ExtensionFinder {
+class PROTOBUF_EXPORT ExtensionFinder {
public:
virtual ~ExtensionFinder();
@@ -127,14 +144,14 @@ class LIBPROTOBUF_EXPORT ExtensionFinder {
// Implementation of ExtensionFinder which finds extensions defined in .proto
// files which have been compiled into the binary.
-class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder {
+class PROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder {
public:
GeneratedExtensionFinder(const MessageLite* containing_type)
: containing_type_(containing_type) {}
virtual ~GeneratedExtensionFinder() {}
// Returns true and fills in *output if found, otherwise returns false.
- virtual bool Find(int number, ExtensionInfo* output);
+ bool Find(int number, ExtensionInfo* output) override;
private:
const MessageLite* containing_type_;
@@ -157,10 +174,10 @@ class MessageSetFieldSkipper;
// ExtensionSet. When parsing, if a tag number is encountered which is
// inside one of the message type's extension ranges, the tag is passed
// off to the ExtensionSet for parsing. Etc.
-class LIBPROTOBUF_EXPORT ExtensionSet {
+class PROTOBUF_EXPORT ExtensionSet {
public:
ExtensionSet();
- explicit ExtensionSet(::google::protobuf::Arena* arena);
+ explicit ExtensionSet(Arena* arena);
~ExtensionSet();
// These are called at startup by protocol-compiler-generated code to
@@ -168,9 +185,9 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// to look up extensions for parsed field numbers. Note that dynamic parsing
// does not use ParseField(); only protocol-compiler-generated parsing
// methods do.
- static void RegisterExtension(const MessageLite* containing_type,
- int number, FieldType type,
- bool is_repeated, bool is_packed);
+ static void RegisterExtension(const MessageLite* containing_type, int number,
+ FieldType type, bool is_repeated,
+ bool is_packed);
static void RegisterEnumExtension(const MessageLite* containing_type,
int number, FieldType type,
bool is_repeated, bool is_packed,
@@ -219,22 +236,22 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// - Strings provide Mutable() in addition to Set() accessors.
bool Has(int number) const;
- int ExtensionSize(int number) const; // Size of a repeated extension.
- int NumExtensions() const; // The number of extensions
+ int ExtensionSize(int number) const; // Size of a repeated extension.
+ int NumExtensions() const; // The number of extensions
FieldType ExtensionType(int number) const;
void ClearExtension(int number);
// singular fields -------------------------------------------------
- int32 GetInt32 (int number, int32 default_value) const;
- int64 GetInt64 (int number, int64 default_value) const;
+ int32 GetInt32(int number, int32 default_value) const;
+ int64 GetInt64(int number, int64 default_value) const;
uint32 GetUInt32(int number, uint32 default_value) const;
uint64 GetUInt64(int number, uint64 default_value) const;
- float GetFloat (int number, float default_value) const;
+ float GetFloat(int number, float default_value) const;
double GetDouble(int number, double default_value) const;
- bool GetBool (int number, bool default_value) const;
- int GetEnum (int number, int default_value) const;
- const string & GetString (int number, const string& default_value) const;
+ bool GetBool(int number, bool default_value) const;
+ int GetEnum(int number, int default_value) const;
+ const std::string& GetString(int number, const std::string& default_value) const;
const MessageLite& GetMessage(int number,
const MessageLite& default_value) const;
const MessageLite& GetMessage(int number, const Descriptor* message_type,
@@ -244,16 +261,16 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// the extension lives in the same pool as the descriptor for the containing
// type.
#define desc const FieldDescriptor* descriptor // avoid line wrapping
- void SetInt32 (int number, FieldType type, int32 value, desc);
- void SetInt64 (int number, FieldType type, int64 value, desc);
+ void SetInt32(int number, FieldType type, int32 value, desc);
+ void SetInt64(int number, FieldType type, int64 value, desc);
void SetUInt32(int number, FieldType type, uint32 value, desc);
void SetUInt64(int number, FieldType type, uint64 value, desc);
- void SetFloat (int number, FieldType type, float value, desc);
+ void SetFloat(int number, FieldType type, float value, desc);
void SetDouble(int number, FieldType type, double value, desc);
- void SetBool (int number, FieldType type, bool value, desc);
- void SetEnum (int number, FieldType type, int value, desc);
- void SetString(int number, FieldType type, const string& value, desc);
- string * MutableString (int number, FieldType type, desc);
+ void SetBool(int number, FieldType type, bool value, desc);
+ void SetEnum(int number, FieldType type, int value, desc);
+ void SetString(int number, FieldType type, const std::string& value, desc);
+ std::string* MutableString(int number, FieldType type, desc);
MessageLite* MutableMessage(int number, FieldType type,
const MessageLite& prototype, desc);
MessageLite* MutableMessage(const FieldDescriptor* decsriptor,
@@ -268,15 +285,15 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
const FieldDescriptor* descriptor,
MessageLite* message);
MessageLite* ReleaseMessage(int number, const MessageLite& prototype);
- MessageLite* UnsafeArenaReleaseMessage(
- int number, const MessageLite& prototype);
+ MessageLite* UnsafeArenaReleaseMessage(int number,
+ const MessageLite& prototype);
MessageLite* ReleaseMessage(const FieldDescriptor* descriptor,
MessageFactory* factory);
MessageLite* UnsafeArenaReleaseMessage(const FieldDescriptor* descriptor,
MessageFactory* factory);
#undef desc
- ::google::protobuf::Arena* GetArenaNoVirtual() const { return arena_; }
+ Arena* GetArenaNoVirtual() const { return arena_; }
// repeated fields -------------------------------------------------
@@ -287,8 +304,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Fetches a mutable version of a RepeatedField extension by number,
// instantiating one if none exists. Similar to above, user should not use
// this directly; it underlies MutableRepeatedExtension().
- void* MutableRawRepeatedField(int number, FieldType field_type,
- bool packed, const FieldDescriptor* desc);
+ void* MutableRawRepeatedField(int number, FieldType field_type, bool packed,
+ const FieldDescriptor* desc);
// This is an overload of MutableRawRepeatedField to maintain compatibility
// with old code using a previous API. This version of
@@ -296,40 +313,40 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// (E.g.: borg/clients/internal/proto1/proto2_reflection.cc.)
void* MutableRawRepeatedField(int number);
- int32 GetRepeatedInt32 (int number, int index) const;
- int64 GetRepeatedInt64 (int number, int index) const;
+ int32 GetRepeatedInt32(int number, int index) const;
+ int64 GetRepeatedInt64(int number, int index) const;
uint32 GetRepeatedUInt32(int number, int index) const;
uint64 GetRepeatedUInt64(int number, int index) const;
- float GetRepeatedFloat (int number, int index) const;
+ float GetRepeatedFloat(int number, int index) const;
double GetRepeatedDouble(int number, int index) const;
- bool GetRepeatedBool (int number, int index) const;
- int GetRepeatedEnum (int number, int index) const;
- const string & GetRepeatedString (int number, int index) const;
+ bool GetRepeatedBool(int number, int index) const;
+ int GetRepeatedEnum(int number, int index) const;
+ const std::string& GetRepeatedString(int number, int index) const;
const MessageLite& GetRepeatedMessage(int number, int index) const;
- void SetRepeatedInt32 (int number, int index, int32 value);
- void SetRepeatedInt64 (int number, int index, int64 value);
+ void SetRepeatedInt32(int number, int index, int32 value);
+ void SetRepeatedInt64(int number, int index, int64 value);
void SetRepeatedUInt32(int number, int index, uint32 value);
void SetRepeatedUInt64(int number, int index, uint64 value);
- void SetRepeatedFloat (int number, int index, float value);
+ void SetRepeatedFloat(int number, int index, float value);
void SetRepeatedDouble(int number, int index, double value);
- void SetRepeatedBool (int number, int index, bool value);
- void SetRepeatedEnum (int number, int index, int value);
- void SetRepeatedString(int number, int index, const string& value);
- string * MutableRepeatedString (int number, int index);
+ void SetRepeatedBool(int number, int index, bool value);
+ void SetRepeatedEnum(int number, int index, int value);
+ void SetRepeatedString(int number, int index, const std::string& value);
+ std::string* MutableRepeatedString(int number, int index);
MessageLite* MutableRepeatedMessage(int number, int index);
#define desc const FieldDescriptor* descriptor // avoid line wrapping
- void AddInt32 (int number, FieldType type, bool packed, int32 value, desc);
- void AddInt64 (int number, FieldType type, bool packed, int64 value, desc);
+ void AddInt32(int number, FieldType type, bool packed, int32 value, desc);
+ void AddInt64(int number, FieldType type, bool packed, int64 value, desc);
void AddUInt32(int number, FieldType type, bool packed, uint32 value, desc);
void AddUInt64(int number, FieldType type, bool packed, uint64 value, desc);
- void AddFloat (int number, FieldType type, bool packed, float value, desc);
+ void AddFloat(int number, FieldType type, bool packed, float value, desc);
void AddDouble(int number, FieldType type, bool packed, double value, desc);
- void AddBool (int number, FieldType type, bool packed, bool value, desc);
- void AddEnum (int number, FieldType type, bool packed, int value, desc);
- void AddString(int number, FieldType type, const string& value, desc);
- string * AddString (int number, FieldType type, desc);
+ void AddBool(int number, FieldType type, bool packed, bool value, desc);
+ void AddEnum(int number, FieldType type, bool packed, int value, desc);
+ void AddString(int number, FieldType type, const std::string& value, desc);
+ std::string* AddString(int number, FieldType type, desc);
MessageLite* AddMessage(int number, FieldType type,
const MessageLite& prototype, desc);
MessageLite* AddMessage(const FieldDescriptor* descriptor,
@@ -378,8 +395,31 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
const MessageLite* containing_type,
io::CodedOutputStream* unknown_fields);
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ // Lite parser
+ std::pair<const char*, bool> ParseField(
+ uint64 tag, ParseClosure parent, const char* begin, const char* end,
+ const MessageLite* containing_type,
+ internal::InternalMetadataWithArenaLite* metadata,
+ internal::ParseContext* ctx);
+ // Full parser
+ std::pair<const char*, bool> ParseField(
+ uint64 tag, ParseClosure parent, const char* begin, const char* end,
+ const Message* containing_type,
+ internal::InternalMetadataWithArena* metadata,
+ internal::ParseContext* ctx);
+ const char* ParseMessageSetItem(ParseClosure parent, const char* begin,
+ const char* end,
+ const Message* containing_type,
+ internal::InternalMetadataWithArena* metadata,
+ internal::ParseContext* ctx);
+#endif
+
// Parse an entire message in MessageSet format. Such messages have no
// fields, only extensions.
+ bool ParseMessageSetLite(io::CodedInputStream* input,
+ ExtensionFinder* extension_finder,
+ FieldSkipper* field_skipper);
bool ParseMessageSet(io::CodedInputStream* input,
ExtensionFinder* extension_finder,
MessageSetFieldSkipper* field_skipper);
@@ -387,7 +427,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Specific versions for lite or full messages (constructs the appropriate
// FieldSkipper automatically).
bool ParseMessageSet(io::CodedInputStream* input,
- const MessageLite* containing_type);
+ const MessageLite* containing_type,
+ std::string* unknown_fields);
bool ParseMessageSet(io::CodedInputStream* input,
const Message* containing_type,
UnknownFieldSet* unknown_fields);
@@ -396,8 +437,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// [start_field_number, end_field_number)
// to the output stream, using the cached sizes computed when ByteSize() was
// last called. Note that the range bounds are inclusive-exclusive.
- void SerializeWithCachedSizes(int start_field_number,
- int end_field_number,
+ void SerializeWithCachedSizes(int start_field_number, int end_field_number,
io::CodedOutputStream* output) const;
// Same as SerializeWithCachedSizes, but without any bounds checking.
@@ -446,29 +486,26 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
int SpaceUsedExcludingSelf() const;
private:
-
// Interface of a lazily parsed singular message extension.
- class LIBPROTOBUF_EXPORT LazyMessageExtension {
+ class PROTOBUF_EXPORT LazyMessageExtension {
public:
LazyMessageExtension() {}
virtual ~LazyMessageExtension() {}
- virtual LazyMessageExtension* New(::google::protobuf::Arena* arena) const = 0;
+ virtual LazyMessageExtension* New(Arena* arena) const = 0;
virtual const MessageLite& GetMessage(
const MessageLite& prototype) const = 0;
virtual MessageLite* MutableMessage(const MessageLite& prototype) = 0;
- virtual void SetAllocatedMessage(MessageLite *message) = 0;
- virtual void UnsafeArenaSetAllocatedMessage(MessageLite *message) = 0;
+ virtual void SetAllocatedMessage(MessageLite* message) = 0;
+ virtual void UnsafeArenaSetAllocatedMessage(MessageLite* message) = 0;
virtual MessageLite* ReleaseMessage(const MessageLite& prototype) = 0;
virtual MessageLite* UnsafeArenaReleaseMessage(
const MessageLite& prototype) = 0;
virtual bool IsInitialized() const = 0;
- PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead")
- virtual int ByteSize() const {
- return internal::ToIntSize(ByteSizeLong());
- }
+ PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
+ virtual int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); }
virtual size_t ByteSizeLong() const = 0;
virtual size_t SpaceUsedLong() const = 0;
@@ -496,27 +533,27 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// The order of these fields packs Extension into 24 bytes when using 8
// byte alignment. Consider this when adding or removing fields here.
union {
- int32 int32_value;
- int64 int64_value;
- uint32 uint32_value;
- uint64 uint64_value;
- float float_value;
- double double_value;
- bool bool_value;
- int enum_value;
- string* string_value;
- MessageLite* message_value;
+ int32 int32_value;
+ int64 int64_value;
+ uint32 uint32_value;
+ uint64 uint64_value;
+ float float_value;
+ double double_value;
+ bool bool_value;
+ int enum_value;
+ std::string* string_value;
+ MessageLite* message_value;
LazyMessageExtension* lazymessage_value;
- RepeatedField <int32 >* repeated_int32_value;
- RepeatedField <int64 >* repeated_int64_value;
- RepeatedField <uint32 >* repeated_uint32_value;
- RepeatedField <uint64 >* repeated_uint64_value;
- RepeatedField <float >* repeated_float_value;
- RepeatedField <double >* repeated_double_value;
- RepeatedField <bool >* repeated_bool_value;
- RepeatedField <int >* repeated_enum_value;
- RepeatedPtrField<string >* repeated_string_value;
+ RepeatedField<int32>* repeated_int32_value;
+ RepeatedField<int64>* repeated_int64_value;
+ RepeatedField<uint32>* repeated_uint32_value;
+ RepeatedField<uint64>* repeated_uint64_value;
+ RepeatedField<float>* repeated_float_value;
+ RepeatedField<double>* repeated_double_value;
+ RepeatedField<bool>* repeated_bool_value;
+ RepeatedField<int>* repeated_enum_value;
+ RepeatedPtrField<std::string>* repeated_string_value;
RepeatedPtrField<MessageLite>* repeated_message_value;
};
@@ -552,20 +589,15 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
const FieldDescriptor* descriptor;
// Some helper methods for operations on a single Extension.
- void SerializeFieldWithCachedSizes(
- int number,
- io::CodedOutputStream* output) const;
- uint8* InternalSerializeFieldWithCachedSizesToArray(
- int number,
- bool deterministic,
- uint8* target) const;
+ void SerializeFieldWithCachedSizes(int number,
+ io::CodedOutputStream* output) const;
+ uint8* InternalSerializeFieldWithCachedSizesToArray(int number,
+ bool deterministic,
+ uint8* target) const;
void SerializeMessageSetItemWithCachedSizes(
- int number,
- io::CodedOutputStream* output) const;
+ int number, io::CodedOutputStream* output) const;
uint8* InternalSerializeMessageSetItemWithCachedSizesToArray(
- int number,
- bool deterministic,
- uint8* target) const;
+ int number, bool deterministic, uint8* target) const;
size_t ByteSize(int number) const;
size_t MessageSetItemByteSize(int number) const;
void Clear();
@@ -625,7 +657,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
void Erase(int key);
size_t Size() const {
- return GOOGLE_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_;
+ return PROTOBUF_PREDICT_FALSE(is_large()) ? map_.large->size() : flat_size_;
}
// Similar to std::for_each.
@@ -641,7 +673,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Applies a functor to the <int, Extension&> pairs in sorted order.
template <typename KeyValueFunctor>
KeyValueFunctor ForEach(KeyValueFunctor func) {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
}
return ForEach(flat_begin(), flat_end(), std::move(func));
@@ -650,7 +682,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Applies a functor to the <int, const Extension&> pairs in sorted order.
template <typename KeyValueFunctor>
KeyValueFunctor ForEach(KeyValueFunctor func) const {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
return ForEach(map_.large->begin(), map_.large->end(), std::move(func));
}
return ForEach(flat_begin(), flat_end(), std::move(func));
@@ -659,6 +691,13 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Merges existing Extension from other_extension
void InternalExtensionMergeFrom(int number, const Extension& other_extension);
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ bool FindExtension(int wire_type, uint32 field,
+ const Message* containing_type,
+ const internal::ParseContext* ctx,
+ ExtensionInfo* extension, bool* was_packed_on_wire);
+#endif
+
// Returns true and fills field_number and extension if extension is found.
// Note to support packed repeated field compatibility, it also fills whether
// the tag on wire is packed, which can be different from
@@ -680,8 +719,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// positioned immediately after the wire tag. This method is called in
// ParseField() after field number and was_packed_on_wire is extracted from
// the wire tag and ExtensionInfo is found by the field number.
- bool ParseFieldWithExtensionInfo(int field_number,
- bool was_packed_on_wire,
+ bool ParseFieldWithExtensionInfo(int field_number, bool was_packed_on_wire,
const ExtensionInfo& extension,
io::CodedInputStream* input,
FieldSkipper* field_skipper);
@@ -704,6 +742,11 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
// Parse a single MessageSet item -- called just after the item group start
// tag has been read.
+ bool ParseMessageSetItemLite(io::CodedInputStream* input,
+ ExtensionFinder* extension_finder,
+ FieldSkipper* field_skipper);
+ // Parse a single MessageSet item -- called just after the item group start
+ // tag has been read.
bool ParseMessageSetItem(io::CodedInputStream* input,
ExtensionFinder* extension_finder,
MessageSetFieldSkipper* field_skipper);
@@ -735,7 +778,7 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
return map_.flat + flat_size_;
}
- ::google::protobuf::Arena* arena_;
+ Arena* arena_;
// Manual memory-management:
// map_.flat is an allocated array of flat_capacity_ elements.
@@ -750,21 +793,59 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
LargeMap* large;
} map_;
+ static void DeleteFlatMap(const KeyValue* flat, uint16 flat_capacity);
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet);
};
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+template <typename Msg, typename Metadata>
+const char* ParseMessageSet(const char* begin, const char* end, Msg* msg,
+ ExtensionSet* ext, Metadata* metadata,
+ internal::ParseContext* ctx) {
+ auto ptr = begin;
+ int depth;
+ (void)depth;
+ while (ptr < end) {
+ uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (tag == WireFormatLite::kMessageSetItemStartTag) {
+ bool ok = ctx->PrepareGroup(tag, &depth);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ctx->extra_parse_data().payload.clear();
+ ptr = Msg::InternalParseMessageSetItem(ptr, end, msg, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ if (ctx->GroupContinues(depth)) goto group_continues;
+ } else {
+ auto res =
+ ext->ParseField(tag, {Msg::_InternalParse, msg}, ptr, end,
+ Msg::internal_default_instance(), metadata, ctx);
+ ptr = res.first;
+ if (res.second) break;
+ }
+ }
+ return ptr;
+group_continues:
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({Msg::_InternalParse, msg},
+ {Msg::InternalParseMessageSetItem, msg}, depth);
+ return ptr;
+}
+#endif
+
// These are just for convenience...
inline void ExtensionSet::SetString(int number, FieldType type,
- const string& value,
+ const std::string& value,
const FieldDescriptor* descriptor) {
MutableString(number, type, descriptor)->assign(value);
}
inline void ExtensionSet::SetRepeatedString(int number, int index,
- const string& value) {
+ const std::string& value) {
MutableRepeatedString(number, index)->assign(value);
}
inline void ExtensionSet::AddString(int number, FieldType type,
- const string& value,
+ const std::string& value,
const FieldDescriptor* descriptor) {
AddString(number, type, descriptor)->assign(value);
}
@@ -841,8 +922,8 @@ class PrimitiveTypeTraits {
static inline ConstType Get(int number, const ExtensionSet& set,
ConstType default_value);
- static inline void Set(int number, FieldType field_type,
- ConstType value, ExtensionSet* set);
+ 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,
@@ -861,14 +942,15 @@ class RepeatedPrimitiveTypeTraits {
static inline Type Get(int number, const ExtensionSet& set, int index);
static inline void Set(int number, int index, Type value, ExtensionSet* set);
- static inline void Add(int number, FieldType field_type,
- bool is_packed, Type value, ExtensionSet* set);
+ static inline void Add(int number, FieldType field_type, bool is_packed,
+ Type value, ExtensionSet* set);
- static inline const RepeatedField<ConstType>&
- GetRepeated(int number, const ExtensionSet& set);
- static inline RepeatedField<Type>*
- MutableRepeated(int number, FieldType field_type,
- bool is_packed, ExtensionSet* set);
+ static inline const RepeatedField<ConstType>& GetRepeated(
+ int number, const ExtensionSet& set);
+ static inline RepeatedField<Type>* MutableRepeated(int number,
+ FieldType field_type,
+ bool is_packed,
+ ExtensionSet* set);
static const RepeatedFieldType* GetDefaultRepeatedField();
template <typename ExtendeeT>
@@ -878,11 +960,10 @@ class RepeatedPrimitiveTypeTraits {
}
};
-LIBPROTOBUF_EXPORT extern ProtobufOnceType repeated_primitive_generic_type_traits_once_init_;
-
-class LIBPROTOBUF_EXPORT RepeatedPrimitiveDefaults {
+class PROTOBUF_EXPORT RepeatedPrimitiveDefaults {
private:
- template<typename Type> friend class RepeatedPrimitiveTypeTraits;
+ template <typename Type>
+ friend class RepeatedPrimitiveTypeTraits;
static const RepeatedPrimitiveDefaults* default_instance();
RepeatedField<int32> default_repeated_field_int32_;
RepeatedField<int64> default_repeated_field_int64_;
@@ -893,57 +974,62 @@ class LIBPROTOBUF_EXPORT RepeatedPrimitiveDefaults {
RepeatedField<bool> default_repeated_field_bool_;
};
-#define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD) \
-template<> inline TYPE PrimitiveTypeTraits<TYPE>::Get( \
- int number, const ExtensionSet& set, TYPE default_value) { \
- return set.Get##METHOD(number, default_value); \
-} \
-template<> inline void PrimitiveTypeTraits<TYPE>::Set( \
- int number, FieldType field_type, TYPE value, ExtensionSet* set) { \
- set->Set##METHOD(number, field_type, value, NULL); \
-} \
- \
-template<> inline TYPE RepeatedPrimitiveTypeTraits<TYPE>::Get( \
- int number, const ExtensionSet& set, int index) { \
- return set.GetRepeated##METHOD(number, index); \
-} \
-template<> inline void RepeatedPrimitiveTypeTraits<TYPE>::Set( \
- int number, int index, TYPE value, ExtensionSet* set) { \
- set->SetRepeated##METHOD(number, index, value); \
-} \
-template<> inline void RepeatedPrimitiveTypeTraits<TYPE>::Add( \
- int number, FieldType field_type, bool is_packed, \
- TYPE value, ExtensionSet* set) { \
- set->Add##METHOD(number, field_type, is_packed, value, NULL); \
-} \
-template<> inline const RepeatedField<TYPE>* \
- RepeatedPrimitiveTypeTraits<TYPE>::GetDefaultRepeatedField() { \
- return &RepeatedPrimitiveDefaults::default_instance() \
- ->default_repeated_field_##TYPE##_; \
-} \
-template<> inline const RepeatedField<TYPE>& \
- RepeatedPrimitiveTypeTraits<TYPE>::GetRepeated(int number, \
- const ExtensionSet& set) { \
- return *reinterpret_cast<const RepeatedField<TYPE>*>( \
- set.GetRawRepeatedField( \
- number, GetDefaultRepeatedField())); \
-} \
-template<> inline RepeatedField<TYPE>* \
- RepeatedPrimitiveTypeTraits<TYPE>::MutableRepeated(int number, \
- FieldType field_type, \
- bool is_packed, \
- ExtensionSet* set) { \
- return reinterpret_cast<RepeatedField<TYPE>*>( \
- set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); \
-}
+#define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD) \
+ template <> \
+ inline TYPE PrimitiveTypeTraits<TYPE>::Get( \
+ int number, const ExtensionSet& set, TYPE default_value) { \
+ return set.Get##METHOD(number, default_value); \
+ } \
+ template <> \
+ inline void PrimitiveTypeTraits<TYPE>::Set(int number, FieldType field_type, \
+ TYPE value, ExtensionSet* set) { \
+ set->Set##METHOD(number, field_type, value, NULL); \
+ } \
+ \
+ template <> \
+ inline TYPE RepeatedPrimitiveTypeTraits<TYPE>::Get( \
+ int number, const ExtensionSet& set, int index) { \
+ return set.GetRepeated##METHOD(number, index); \
+ } \
+ template <> \
+ inline void RepeatedPrimitiveTypeTraits<TYPE>::Set( \
+ int number, int index, TYPE value, ExtensionSet* set) { \
+ set->SetRepeated##METHOD(number, index, value); \
+ } \
+ template <> \
+ inline void RepeatedPrimitiveTypeTraits<TYPE>::Add( \
+ int number, FieldType field_type, bool is_packed, TYPE value, \
+ ExtensionSet* set) { \
+ set->Add##METHOD(number, field_type, is_packed, value, NULL); \
+ } \
+ template <> \
+ inline const RepeatedField<TYPE>* \
+ RepeatedPrimitiveTypeTraits<TYPE>::GetDefaultRepeatedField() { \
+ return &RepeatedPrimitiveDefaults::default_instance() \
+ ->default_repeated_field_##TYPE##_; \
+ } \
+ template <> \
+ inline const RepeatedField<TYPE>& \
+ RepeatedPrimitiveTypeTraits<TYPE>::GetRepeated(int number, \
+ const ExtensionSet& set) { \
+ return *reinterpret_cast<const RepeatedField<TYPE>*>( \
+ set.GetRawRepeatedField(number, GetDefaultRepeatedField())); \
+ } \
+ template <> \
+ inline RepeatedField<TYPE>* \
+ RepeatedPrimitiveTypeTraits<TYPE>::MutableRepeated( \
+ int number, FieldType field_type, bool is_packed, ExtensionSet* set) { \
+ return reinterpret_cast<RepeatedField<TYPE>*>( \
+ set->MutableRawRepeatedField(number, field_type, is_packed, NULL)); \
+ }
-PROTOBUF_DEFINE_PRIMITIVE_TYPE( int32, Int32)
-PROTOBUF_DEFINE_PRIMITIVE_TYPE( int64, Int64)
+PROTOBUF_DEFINE_PRIMITIVE_TYPE(int32, Int32)
+PROTOBUF_DEFINE_PRIMITIVE_TYPE(int64, Int64)
PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32, UInt32)
PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64, UInt64)
-PROTOBUF_DEFINE_PRIMITIVE_TYPE( float, Float)
+PROTOBUF_DEFINE_PRIMITIVE_TYPE(float, Float)
PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double)
-PROTOBUF_DEFINE_PRIMITIVE_TYPE( bool, Bool)
+PROTOBUF_DEFINE_PRIMITIVE_TYPE(bool, Bool)
#undef PROTOBUF_DEFINE_PRIMITIVE_TYPE
@@ -951,21 +1037,21 @@ PROTOBUF_DEFINE_PRIMITIVE_TYPE( bool, Bool)
// StringTypeTraits
// Strings support both Set() and Mutable().
-class LIBPROTOBUF_EXPORT StringTypeTraits {
+class PROTOBUF_EXPORT StringTypeTraits {
public:
- typedef const string& ConstType;
- typedef string* MutableType;
+ typedef const std::string& ConstType;
+ typedef std::string* MutableType;
typedef StringTypeTraits Singular;
- static inline const string& Get(int number, const ExtensionSet& set,
+ static inline const std::string& Get(int number, const ExtensionSet& set,
ConstType default_value) {
return set.GetString(number, default_value);
}
- static inline void Set(int number, FieldType field_type,
- const string& value, ExtensionSet* set) {
+ static inline void Set(int number, FieldType field_type, const std::string& value,
+ ExtensionSet* set) {
set->SetString(number, field_type, value, NULL);
}
- static inline string* Mutable(int number, FieldType field_type,
+ static inline std::string* Mutable(int number, FieldType field_type,
ExtensionSet* set) {
return set->MutableString(number, field_type, NULL);
}
@@ -976,46 +1062,45 @@ class LIBPROTOBUF_EXPORT StringTypeTraits {
}
};
-class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits {
+class PROTOBUF_EXPORT RepeatedStringTypeTraits {
public:
- typedef const string& ConstType;
- typedef string* MutableType;
+ typedef const std::string& ConstType;
+ typedef std::string* MutableType;
typedef RepeatedStringTypeTraits Repeated;
- typedef RepeatedPtrField<string> RepeatedFieldType;
+ typedef RepeatedPtrField<std::string> RepeatedFieldType;
- static inline const string& Get(int number, const ExtensionSet& set,
+ static inline const std::string& Get(int number, const ExtensionSet& set,
int index) {
return set.GetRepeatedString(number, index);
}
- static inline void Set(int number, int index,
- const string& value, ExtensionSet* set) {
+ static inline void Set(int number, int index, const std::string& value,
+ ExtensionSet* set) {
set->SetRepeatedString(number, index, value);
}
- static inline string* Mutable(int number, int index, ExtensionSet* set) {
+ static inline std::string* Mutable(int number, int index, ExtensionSet* set) {
return set->MutableRepeatedString(number, index);
}
- static inline void Add(int number, FieldType field_type,
- bool /*is_packed*/, const string& value,
- ExtensionSet* set) {
+ static inline void Add(int number, FieldType field_type, bool /*is_packed*/,
+ const std::string& value, ExtensionSet* set) {
set->AddString(number, field_type, value, NULL);
}
- static inline string* Add(int number, FieldType field_type,
+ static inline std::string* Add(int number, FieldType field_type,
ExtensionSet* set) {
return set->AddString(number, field_type, NULL);
}
- static inline const RepeatedPtrField<string>&
- GetRepeated(int number, const ExtensionSet& set) {
- return *reinterpret_cast<const RepeatedPtrField<string>*>(
+ static inline const RepeatedPtrField<std::string>& GetRepeated(
+ int number, const ExtensionSet& set) {
+ return *reinterpret_cast<const RepeatedPtrField<std::string>*>(
set.GetRawRepeatedField(number, GetDefaultRepeatedField()));
}
- static inline RepeatedPtrField<string>*
- MutableRepeated(int number, FieldType field_type,
- bool is_packed, ExtensionSet* set) {
- return reinterpret_cast<RepeatedPtrField<string>*>(
- set->MutableRawRepeatedField(number, field_type,
- is_packed, NULL));
+ static inline RepeatedPtrField<std::string>* MutableRepeated(int number,
+ FieldType field_type,
+ bool is_packed,
+ ExtensionSet* set) {
+ return reinterpret_cast<RepeatedPtrField<std::string>*>(
+ set->MutableRawRepeatedField(number, field_type, is_packed, NULL));
}
static const RepeatedFieldType* GetDefaultRepeatedField();
@@ -1047,8 +1132,8 @@ class EnumTypeTraits {
ConstType default_value) {
return static_cast<Type>(set.GetEnum(number, default_value));
}
- static inline void Set(int number, FieldType field_type,
- ConstType value, ExtensionSet* set) {
+ static inline void Set(int number, FieldType field_type, ConstType value,
+ ExtensionSet* set) {
GOOGLE_DCHECK(IsValid(value));
set->SetEnum(number, field_type, value, NULL);
}
@@ -1071,19 +1156,18 @@ class RepeatedEnumTypeTraits {
static inline ConstType Get(int number, const ExtensionSet& set, int index) {
return static_cast<Type>(set.GetRepeatedEnum(number, index));
}
- static inline void Set(int number, int index,
- ConstType value, ExtensionSet* set) {
+ static inline void Set(int number, int index, ConstType value,
+ ExtensionSet* set) {
GOOGLE_DCHECK(IsValid(value));
set->SetRepeatedEnum(number, index, value);
}
- static inline void Add(int number, FieldType field_type,
- bool is_packed, ConstType value, ExtensionSet* set) {
+ static inline void Add(int number, FieldType field_type, bool is_packed,
+ ConstType value, ExtensionSet* set) {
GOOGLE_DCHECK(IsValid(value));
set->AddEnum(number, field_type, is_packed, value, NULL);
}
- static inline const RepeatedField<Type>& GetRepeated(int number,
- const ExtensionSet&
- set) {
+ static inline const RepeatedField<Type>& GetRepeated(
+ int number, const ExtensionSet& set) {
// Hack: the `Extension` struct stores a RepeatedField<int> for enums.
// RepeatedField<int> cannot implicitly convert to RepeatedField<EnumType>
// so we need to do some casting magic. See message.h for similar
@@ -1132,13 +1216,12 @@ class MessageTypeTraits {
static inline ConstType Get(int number, const ExtensionSet& set,
ConstType default_value) {
- return static_cast<const Type&>(
- set.GetMessage(number, default_value));
+ return static_cast<const Type&>(set.GetMessage(number, default_value));
}
static inline MutableType Mutable(int number, FieldType field_type,
ExtensionSet* set) {
- return static_cast<Type*>(
- set->MutableMessage(number, field_type, Type::default_instance(), NULL));
+ return static_cast<Type*>(set->MutableMessage(
+ number, field_type, Type::default_instance(), NULL));
}
static inline void SetAllocated(int number, FieldType field_type,
MutableType message, ExtensionSet* set) {
@@ -1151,14 +1234,14 @@ class MessageTypeTraits {
}
static inline MutableType Release(int number, FieldType /* field_type */,
ExtensionSet* set) {
- return static_cast<Type*>(set->ReleaseMessage(
- number, Type::default_instance()));
+ return static_cast<Type*>(
+ set->ReleaseMessage(number, Type::default_instance()));
}
static inline MutableType UnsafeArenaRelease(int number,
FieldType /* field_type */,
ExtensionSet* set) {
- return static_cast<Type*>(set->UnsafeArenaReleaseMessage(
- number, Type::default_instance()));
+ return static_cast<Type*>(
+ set->UnsafeArenaReleaseMessage(number, Type::default_instance()));
}
template <typename ExtendeeT>
static void Register(int number, FieldType type, bool is_packed) {
@@ -1191,9 +1274,8 @@ class RepeatedMessageTypeTraits {
return static_cast<Type*>(
set->AddMessage(number, field_type, Type::default_instance(), NULL));
}
- static inline const RepeatedPtrField<Type>& GetRepeated(int number,
- const ExtensionSet&
- set) {
+ static inline const RepeatedPtrField<Type>& GetRepeated(
+ int number, const ExtensionSet& set) {
// See notes above in RepeatedEnumTypeTraits::GetRepeated(): same
// casting hack applies here, because a RepeatedPtrField<MessageLite>
// cannot naturally become a RepeatedPtrType<Type> even though Type is
@@ -1219,9 +1301,9 @@ class RepeatedMessageTypeTraits {
}
};
-template<typename Type> inline
- const typename RepeatedMessageTypeTraits<Type>::RepeatedFieldType*
- RepeatedMessageTypeTraits<Type>::GetDefaultRepeatedField() {
+template <typename Type>
+inline const typename RepeatedMessageTypeTraits<Type>::RepeatedFieldType*
+RepeatedMessageTypeTraits<Type>::GetDefaultRepeatedField() {
static auto instance = OnShutdownDelete(new RepeatedFieldType);
return instance;
}
@@ -1236,15 +1318,15 @@ template<typename Type> inline
//
// Note that we could, in theory, supply the field number as a template
// parameter, and thus make an instance of ExtensionIdentifier have no
-// actual contents. However, if we did that, then using at extension
+// actual contents. However, if we did that, then using an extension
// identifier would not necessarily cause the compiler to output any sort
// 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.
-template <typename ExtendeeType, typename TypeTraitsType,
- FieldType field_type, bool is_packed>
+template <typename ExtendeeType, typename TypeTraitsType, FieldType field_type,
+ bool is_packed>
class ExtensionIdentifier {
public:
typedef TypeTraitsType TypeTraits;
@@ -1281,182 +1363,182 @@ class ExtensionIdentifier {
//
// For similar reason, we use "_field_type" and "_is_packed" as parameter names
// below, so that "field_type" and "is_packed" can be used as field names.
-#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \
+#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \
/* Has, Size, Clear */ \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline bool HasExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
return _extensions_.Has(id.number()); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void ClearExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
_extensions_.ClearExtension(id.number()); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline int ExtensionSize( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
return _extensions_.ExtensionSize(id.number()); \
} \
\
/* Singular accessors */ \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Singular::ConstType GetExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
return _proto_TypeTraits::Get(id.number(), _extensions_, \
id.default_value()); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Singular::MutableType MutableExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
return _proto_TypeTraits::Mutable(id.number(), _field_type, \
&_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void SetExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
typename _proto_TypeTraits::Singular::ConstType value) { \
_proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void SetAllocatedExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
typename _proto_TypeTraits::Singular::MutableType value) { \
- _proto_TypeTraits::SetAllocated(id.number(), _field_type, \
- value, &_extensions_); \
+ _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, \
+ &_extensions_); \
} \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void UnsafeArenaSetAllocatedExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
typename _proto_TypeTraits::Singular::MutableType value) { \
_proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, \
value, &_extensions_); \
} \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Singular::MutableType ReleaseExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
return _proto_TypeTraits::Release(id.number(), _field_type, \
&_extensions_); \
} \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Singular::MutableType \
- UnsafeArenaReleaseExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
+ UnsafeArenaReleaseExtension( \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, \
&_extensions_); \
} \
\
/* Repeated accessors */ \
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Repeated::ConstType GetExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
int index) const { \
return _proto_TypeTraits::Get(id.number(), _extensions_, index); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Repeated::MutableType MutableExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
int index) { \
return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void SetExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
int index, typename _proto_TypeTraits::Repeated::ConstType value) { \
_proto_TypeTraits::Set(id.number(), index, value, &_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Repeated::MutableType AddExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
return _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline void AddExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id, \
typename _proto_TypeTraits::Repeated::ConstType value) { \
- _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, \
- value, &_extensions_); \
+ _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, \
+ &_extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline const typename _proto_TypeTraits::Repeated::RepeatedFieldType& \
- GetRepeatedExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, \
- _is_packed>& id) const { \
+ GetRepeatedExtension( \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) const { \
return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); \
} \
\
template <typename _proto_TypeTraits, \
- ::google::protobuf::internal::FieldType _field_type, \
+ ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, \
bool _is_packed> \
inline typename _proto_TypeTraits::Repeated::RepeatedFieldType* \
- MutableRepeatedExtension( \
- const ::google::protobuf::internal::ExtensionIdentifier< \
- CLASSNAME, _proto_TypeTraits, _field_type, \
- _is_packed>& id) { \
+ MutableRepeatedExtension( \
+ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< \
+ CLASSNAME, _proto_TypeTraits, _field_type, _is_packed>& id) { \
return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, \
_is_packed, &_extensions_); \
}
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_EXTENSION_SET_H__
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc
index a3c84167..20d36ab7 100644
--- a/src/google/protobuf/extension_set_heavy.cc
+++ b/src/google/protobuf/extension_set_heavy.cc
@@ -45,10 +45,13 @@
#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.h>
#include <google/protobuf/wire_format_lite_inl.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+namespace google {
namespace protobuf {
namespace internal {
@@ -85,9 +88,9 @@ class DescriptorPoolExtensionFinder : public ExtensionFinder {
MessageFactory* factory,
const Descriptor* containing_type)
: pool_(pool), factory_(factory), containing_type_(containing_type) {}
- virtual ~DescriptorPoolExtensionFinder() {}
+ ~DescriptorPoolExtensionFinder() override {}
- virtual bool Find(int number, ExtensionInfo* output);
+ bool Find(int number, ExtensionInfo* output) override;
private:
const DescriptorPool* pool_;
@@ -244,7 +247,7 @@ ExtensionSet::Extension* ExtensionSet::MaybeNewRepeatedExtension(const FieldDesc
GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE);
extension->is_repeated = true;
extension->repeated_message_value =
- ::google::protobuf::Arena::CreateMessage<RepeatedPtrField<MessageLite> >(arena_);
+ Arena::CreateMessage<RepeatedPtrField<MessageLite> >(arena_);
} else {
GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE);
}
@@ -258,7 +261,7 @@ MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor,
// RepeatedPtrField<Message> does not know how to Add() since it cannot
// allocate an abstract object, so we have to be tricky.
MessageLite* result =
- reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
+ reinterpret_cast<internal::RepeatedPtrFieldBase*>(
extension->repeated_message_value)
->AddFromCleared<GenericTypeHandler<MessageLite> >();
if (result == NULL) {
@@ -312,6 +315,234 @@ bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) {
}
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+bool ExtensionSet::FindExtension(int wire_type, uint32 field,
+ const Message* containing_type,
+ const internal::ParseContext* ctx,
+ ExtensionInfo* extension,
+ bool* was_packed_on_wire) {
+ if (ctx->extra_parse_data().pool == nullptr) {
+ GeneratedExtensionFinder finder(containing_type);
+ if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension,
+ was_packed_on_wire)) {
+ return false;
+ }
+ } else {
+ DescriptorPoolExtensionFinder finder(ctx->extra_parse_data().pool,
+ ctx->extra_parse_data().factory,
+ containing_type->GetDescriptor());
+ if (!FindExtensionInfoFromFieldNumber(wire_type, field, &finder, extension,
+ was_packed_on_wire)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+std::pair<const char*, bool> ExtensionSet::ParseField(
+ uint64 tag, ParseClosure parent, const char* begin, const char* end,
+ const Message* containing_type,
+ internal::InternalMetadataWithArena* metadata,
+ internal::ParseContext* ctx) {
+ int number = tag >> 3;
+ bool was_packed_on_wire;
+ ExtensionInfo extension;
+ if (!FindExtension(tag & 7, number, containing_type, ctx, &extension,
+ &was_packed_on_wire)) {
+ return UnknownFieldParse(tag, parent, begin, end,
+ metadata->mutable_unknown_fields(), ctx);
+ }
+ auto ptr = begin;
+ ParseClosure child;
+ int depth;
+ if (was_packed_on_wire) {
+ switch (extension.type) {
+#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE) \
+ case WireFormatLite::TYPE_##UPPERCASE: \
+ child = { \
+ internal::Packed##CPP_CAMELCASE##Parser, \
+ MutableRawRepeatedField(number, extension.type, extension.is_packed, \
+ extension.descriptor)}; \
+ goto length_delim
+ HANDLE_TYPE(INT32, Int32);
+ HANDLE_TYPE(INT64, Int64);
+ HANDLE_TYPE(UINT32, UInt32);
+ HANDLE_TYPE(UINT64, UInt64);
+ HANDLE_TYPE(SINT32, SInt32);
+ HANDLE_TYPE(SINT64, SInt64);
+ HANDLE_TYPE(FIXED32, Fixed32);
+ HANDLE_TYPE(FIXED64, Fixed64);
+ HANDLE_TYPE(SFIXED32, SFixed32);
+ HANDLE_TYPE(SFIXED64, SFixed64);
+ HANDLE_TYPE(FLOAT, Float);
+ HANDLE_TYPE(DOUBLE, Double);
+ HANDLE_TYPE(BOOL, Bool);
+#undef HANDLE_TYPE
+
+ case WireFormatLite::TYPE_ENUM:
+ ctx->extra_parse_data().SetEnumValidatorArg(
+ extension.enum_validity_check.func,
+ extension.enum_validity_check.arg,
+ metadata->mutable_unknown_fields(), tag >> 3);
+ child = {
+ internal::PackedValidEnumParserArg,
+ MutableRawRepeatedField(number, extension.type, extension.is_packed,
+ extension.descriptor)};
+ goto length_delim;
+ case WireFormatLite::TYPE_STRING:
+ case WireFormatLite::TYPE_BYTES:
+ case WireFormatLite::TYPE_GROUP:
+ case WireFormatLite::TYPE_MESSAGE:
+ GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed.";
+ break;
+ }
+ } else {
+ switch (extension.type) {
+#define HANDLE_VARINT_TYPE(UPPERCASE, CPP_CAMELCASE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ uint64 value; \
+ ptr = Varint::Parse64(ptr, &value); \
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_VARINT_TYPE(INT32, Int32);
+ HANDLE_VARINT_TYPE(INT64, Int64);
+ HANDLE_VARINT_TYPE(UINT32, UInt32);
+ HANDLE_VARINT_TYPE(UINT64, UInt64);
+#undef HANDLE_VARINT_TYPE
+#define HANDLE_SVARINT_TYPE(UPPERCASE, CPP_CAMELCASE, SIZE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ uint64 val; \
+ ptr = Varint::Parse64(ptr, &val); \
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true)); \
+ auto value = WireFormatLite::ZigZagDecode##SIZE(val); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_SVARINT_TYPE(SINT32, Int32, 32);
+ HANDLE_SVARINT_TYPE(SINT64, Int64, 64);
+#undef HANDLE_SVARINT_TYPE
+#define HANDLE_FIXED_TYPE(UPPERCASE, CPP_CAMELCASE, CPPTYPE) \
+ case WireFormatLite::TYPE_##UPPERCASE: { \
+ CPPTYPE value; \
+ std::memcpy(&value, ptr, sizeof(CPPTYPE)); \
+ ptr += sizeof(CPPTYPE); \
+ if (extension.is_repeated) { \
+ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
+ extension.is_packed, value, extension.descriptor); \
+ } else { \
+ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
+ extension.descriptor); \
+ } \
+ } break
+
+ HANDLE_FIXED_TYPE(FIXED32, UInt32, uint32);
+ HANDLE_FIXED_TYPE(FIXED64, UInt64, uint64);
+ HANDLE_FIXED_TYPE(SFIXED32, Int32, int32);
+ HANDLE_FIXED_TYPE(SFIXED64, Int64, int64);
+ HANDLE_FIXED_TYPE(FLOAT, Float, float);
+ HANDLE_FIXED_TYPE(DOUBLE, Double, double);
+ HANDLE_FIXED_TYPE(BOOL, Bool, bool);
+#undef HANDLE_FIXED_TYPE
+
+ case WireFormatLite::TYPE_ENUM: {
+ uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ int value = val;
+
+ if (!extension.enum_validity_check.func(
+ extension.enum_validity_check.arg, value)) {
+ WriteVarint(number, val, metadata->mutable_unknown_fields());
+ } else if (extension.is_repeated) {
+ AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value,
+ extension.descriptor);
+ } else {
+ SetEnum(number, WireFormatLite::TYPE_ENUM, value,
+ extension.descriptor);
+ }
+ break;
+ }
+
+ case WireFormatLite::TYPE_BYTES:
+ case WireFormatLite::TYPE_STRING: {
+ string* value = extension.is_repeated
+ ? AddString(number, WireFormatLite::TYPE_STRING,
+ extension.descriptor)
+ : MutableString(number, WireFormatLite::TYPE_STRING,
+ extension.descriptor);
+ child = {StringParser, value};
+ goto length_delim;
+ }
+
+ case WireFormatLite::TYPE_GROUP: {
+ MessageLite* value =
+ extension.is_repeated
+ ? AddMessage(number, WireFormatLite::TYPE_GROUP,
+ *extension.message_prototype, extension.descriptor)
+ : MutableMessage(number, WireFormatLite::TYPE_GROUP,
+ *extension.message_prototype,
+ extension.descriptor);
+ child = {value->_ParseFunc(), value};
+ bool ok = ctx->PrepareGroup(tag, &depth);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = child(ptr, end, ctx);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ if (ctx->GroupContinues(depth)) goto group_continues;
+ break;
+ }
+
+ case WireFormatLite::TYPE_MESSAGE: {
+ MessageLite* value =
+ extension.is_repeated
+ ? AddMessage(number, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype, extension.descriptor)
+ : MutableMessage(number, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype,
+ extension.descriptor);
+ child = {value->_ParseFunc(), value};
+ goto length_delim;
+ }
+ }
+ }
+
+ return std::make_pair(ptr, false);
+
+length_delim:
+ uint32 size;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ if (size > end - ptr) goto len_delim_till_end;
+ {
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange(child, ptr, newend);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = newend;
+ }
+ return std::make_pair(ptr, false);
+len_delim_till_end:
+ return std::make_pair(ctx->StoreAndTailCall(ptr, end, parent, child, size),
+ true);
+
+group_continues:
+ ctx->StoreGroup(parent, child, depth);
+ return std::make_pair(ptr, true);
+}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
const Message* containing_type,
UnknownFieldSet* unknown_fields) {
@@ -327,6 +558,82 @@ bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input,
}
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ExtensionSet::ParseMessageSetItem(
+ ParseClosure parent, const char* begin, const char* end,
+ const Message* containing_type,
+ internal::InternalMetadataWithArena* metadata,
+ internal::ParseContext* ctx) {
+ auto ptr = begin;
+ while (ptr < end) {
+ uint32 tag = *ptr++;
+ if (tag == WireFormatLite::kMessageSetTypeIdTag) {
+ uint32 type_id;
+ ptr = Varint::Parse32(ptr, &type_id);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+
+ if (ctx->extra_parse_data().payload.empty()) {
+ tag = *ptr++;
+ GOOGLE_PROTOBUF_PARSER_ASSERT(tag ==
+ WireFormatLite::kMessageSetMessageTag);
+ auto res = ParseField(static_cast<uint64>(type_id) * 8 + 2, parent, ptr,
+ end, containing_type, metadata, ctx);
+ ptr = res.first;
+ if (res.second) break;
+ } else {
+ ExtensionInfo extension;
+ GeneratedExtensionFinder finder(containing_type);
+ bool was_packed_on_wire;
+ if (!FindExtension(2, type_id, containing_type, ctx, &extension,
+ &was_packed_on_wire)) {
+ metadata->mutable_unknown_fields()->AddLengthDelimited(
+ type_id, ctx->extra_parse_data().payload);
+ continue;
+ }
+ MessageLite* value =
+ extension.is_repeated
+ ? AddMessage(type_id, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype, extension.descriptor)
+ : MutableMessage(type_id, WireFormatLite::TYPE_MESSAGE,
+ *extension.message_prototype,
+ extension.descriptor);
+ ParseClosure parser = {value->_ParseFunc(), value};
+ StringPiece chunk(ctx->extra_parse_data().payload.data());
+ bool ok = ctx->ParseExactRange(parser, chunk.begin(), chunk.end());
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ }
+ } else if (tag == WireFormatLite::kMessageSetItemEndTag) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ break;
+ } else if (tag == WireFormatLite::kMessageSetMessageTag) {
+ uint32 size;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ParseClosure child = {internal::StringParser,
+ &ctx->extra_parse_data().payload};
+ if (size > end - ptr) {
+ return ctx->StoreAndTailCall(ptr, end, parent, child, size);
+ } else {
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange(child, ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ }
+ } else {
+ ptr--;
+ ptr = Varint::Parse32(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ auto res =
+ ParseField(tag, parent, ptr, end, containing_type, metadata, ctx);
+ ptr = res.first;
+ if (res.second) break;
+ }
+ }
+ return ptr;
+}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
const Message* containing_type,
UnknownFieldSet* unknown_fields) {
@@ -385,11 +692,10 @@ size_t ExtensionSet::Extension::SpaceUsedExcludingSelfLong() const {
// 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(
- reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
- repeated_message_value));
+ total_size += sizeof(*repeated_message_value) +
+ RepeatedMessage_SpaceUsedExcludingSelfLong(
+ reinterpret_cast<internal::RepeatedPtrFieldBase*>(
+ repeated_message_value));
break;
}
} else {
@@ -420,21 +726,19 @@ uint8* ExtensionSet::SerializeWithCachedSizesToArray(int start_field_number,
uint8* target) const {
return InternalSerializeWithCachedSizesToArray(
start_field_number, end_field_number,
- google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(),
- target);
+ io::CodedOutputStream::IsDefaultSerializationDeterministic(), target);
}
uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray(
uint8* target) const {
return InternalSerializeMessageSetWithCachedSizesToArray(
- google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(),
- target);
+ io::CodedOutputStream::IsDefaultSerializationDeterministic(), target);
}
uint8* ExtensionSet::InternalSerializeWithCachedSizesToArray(
int start_field_number, int end_field_number, bool deterministic,
uint8* target) const {
- if (GOOGLE_PREDICT_FALSE(is_large())) {
+ if (PROTOBUF_PREDICT_FALSE(is_large())) {
const auto& end = map_.large->end();
for (auto it = map_.large->lower_bound(start_field_number);
it != end && it->first < end_field_number; ++it) {
@@ -650,165 +954,27 @@ bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
}
}
-bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input,
- const MessageLite* containing_type) {
- MessageSetFieldSkipper skipper(NULL);
- GeneratedExtensionFinder finder(containing_type);
- return ParseMessageSet(input, &finder, &skipper);
-}
-
bool ExtensionSet::ParseMessageSetItem(io::CodedInputStream* input,
ExtensionFinder* extension_finder,
MessageSetFieldSkipper* field_skipper) {
- // TODO(kenton): It would be nice to share code between this and
- // WireFormatLite::ParseAndMergeMessageSetItem(), but I think the
- // differences would be hard to factor out.
-
- // This method parses a group which should contain two fields:
- // required int32 type_id = 2;
- // required data message = 3;
-
- uint32 last_type_id = 0;
-
- // If we see message data before the type_id, we'll append it to this so
- // we can parse it later.
- string message_data;
-
- while (true) {
- const uint32 tag = input->ReadTagNoLastTag();
- if (tag == 0) return false;
-
- switch (tag) {
- case WireFormatLite::kMessageSetTypeIdTag: {
- uint32 type_id;
- if (!input->ReadVarint32(&type_id)) return false;
- last_type_id = type_id;
-
- if (!message_data.empty()) {
- // We saw some message data before the type_id. Have to parse it
- // now.
- io::CodedInputStream sub_input(
- reinterpret_cast<const uint8*>(message_data.data()),
- message_data.size());
- if (!ParseFieldMaybeLazily(WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
- last_type_id, &sub_input,
- extension_finder, field_skipper)) {
- return false;
- }
- message_data.clear();
- }
-
- break;
- }
-
- case WireFormatLite::kMessageSetMessageTag: {
- if (last_type_id == 0) {
- // We haven't seen a type_id yet. Append this data to message_data.
- string temp;
- uint32 length;
- if (!input->ReadVarint32(&length)) return false;
- if (!input->ReadString(&temp, length)) return false;
- io::StringOutputStream output_stream(&message_data);
- io::CodedOutputStream coded_output(&output_stream);
- coded_output.WriteVarint32(length);
- coded_output.WriteString(temp);
- } else {
- // Already saw type_id, so we can parse this directly.
- if (!ParseFieldMaybeLazily(WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
- last_type_id, input,
- extension_finder, field_skipper)) {
- return false;
- }
- }
-
- break;
- }
-
- case WireFormatLite::kMessageSetItemEndTag: {
- return true;
- }
-
- default: {
- if (!field_skipper->SkipField(input, tag)) return false;
- }
+ struct MSFull {
+ bool ParseField(int type_id, io::CodedInputStream* input) {
+ return me->ParseFieldMaybeLazily(
+ WireFormatLite::WIRETYPE_LENGTH_DELIMITED, type_id, input,
+ extension_finder, field_skipper);
}
- }
-}
-
-void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes(
- int number,
- io::CodedOutputStream* output) const {
- if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
- // Not a valid MessageSet extension, but serialize it the normal way.
- SerializeFieldWithCachedSizes(number, output);
- return;
- }
-
- if (is_cleared) return;
-
- // Start group.
- output->WriteTag(WireFormatLite::kMessageSetItemStartTag);
-
- // Write type ID.
- WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber,
- number,
- output);
- // Write message.
- if (is_lazy) {
- lazymessage_value->WriteMessage(
- WireFormatLite::kMessageSetMessageNumber, output);
- } else {
- WireFormatLite::WriteMessageMaybeToArray(
- WireFormatLite::kMessageSetMessageNumber,
- *message_value,
- output);
- }
-
- // End group.
- output->WriteTag(WireFormatLite::kMessageSetItemEndTag);
-}
-
-size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
- if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
- // Not a valid MessageSet extension, but compute the byte size for it the
- // normal way.
- return ByteSize(number);
- }
-
- if (is_cleared) return 0;
-
- size_t our_size = WireFormatLite::kMessageSetItemTagsSize;
- // type_id
- our_size += io::CodedOutputStream::VarintSize32(number);
-
- // message
- size_t message_size = 0;
- if (is_lazy) {
- message_size = lazymessage_value->ByteSizeLong();
- } else {
- message_size = message_value->ByteSizeLong();
- }
-
- our_size += io::CodedOutputStream::VarintSize32(message_size);
- our_size += message_size;
-
- return our_size;
-}
+ bool SkipField(uint32 tag, io::CodedInputStream* input) {
+ return field_skipper->SkipField(input, tag);
+ }
-void ExtensionSet::SerializeMessageSetWithCachedSizes(
- io::CodedOutputStream* output) const {
- ForEach([output](int number, const Extension& ext) {
- ext.SerializeMessageSetItemWithCachedSizes(number, output);
- });
-}
+ ExtensionSet* me;
+ ExtensionFinder* extension_finder;
+ MessageSetFieldSkipper* field_skipper;
+ };
-size_t ExtensionSet::MessageSetByteSize() const {
- size_t total_size = 0;
- ForEach([&total_size](int number, const Extension& ext) {
- total_size += ext.MessageSetItemByteSize(number);
- });
- return total_size;
+ return ParseMessageSetItemImpl(input,
+ MSFull{this, extension_finder, field_skipper});
}
} // namespace internal
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc
index bc65d295..af398546 100644
--- a/src/google/protobuf/extension_set_unittest.cc
+++ b/src/google/protobuf/extension_set_unittest.cc
@@ -53,13 +53,13 @@
#include <gtest/gtest.h>
#include <google/protobuf/stubs/stl_util.h>
-namespace google {
+namespace google {
namespace protobuf {
namespace internal {
namespace {
-// This test closely mirrors google/protobuf/compiler/cpp/unittest.cc
+// This test closely mirrors net/proto2/compiler/cpp/internal/unittest.cc
// except that it uses extensions rather than regular fields.
TEST(ExtensionSetTest, Defaults) {
@@ -208,9 +208,9 @@ TEST(ExtensionSetTest, ReleaseExtension) {
}
TEST(ExtensionSetTest, ArenaUnsafeArenaSetAllocatedAndRelease) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllExtensions* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
unittest::ForeignMessage extension;
message->UnsafeArenaSetAllocatedExtension(
unittest::optional_foreign_message_extension,
@@ -258,9 +258,9 @@ TEST(ExtensionSetTest, UnsafeArenaSetAllocatedAndRelease) {
}
TEST(ExtensionSetTest, ArenaUnsafeArenaReleaseOfHeapAlloc) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllExtensions* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
unittest::ForeignMessage* extension = new unittest::ForeignMessage;
message->SetAllocatedExtension(
unittest::optional_foreign_message_extension,
@@ -392,17 +392,17 @@ TEST(ExtensionSetTest, SwapExtensionBothFull) {
}
TEST(ExtensionSetTest, ArenaSetAllExtension) {
- ::google::protobuf::Arena arena1;
+ Arena arena1;
unittest::TestAllExtensions* message1 =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
TestUtil::ExpectAllExtensionsSet(*message1);
}
TEST(ExtensionSetTest, ArenaCopyConstructor) {
- ::google::protobuf::Arena arena1;
+ Arena arena1;
unittest::TestAllExtensions* message1 =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
unittest::TestAllExtensions message2(*message1);
arena1.Reset();
@@ -410,9 +410,9 @@ TEST(ExtensionSetTest, ArenaCopyConstructor) {
}
TEST(ExtensionSetTest, ArenaMergeFrom) {
- ::google::protobuf::Arena arena1;
+ Arena arena1;
unittest::TestAllExtensions* message1 =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
TestUtil::SetAllExtensions(message1);
unittest::TestAllExtensions message2;
message2.MergeFrom(*message1);
@@ -421,9 +421,9 @@ TEST(ExtensionSetTest, ArenaMergeFrom) {
}
TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllExtensions* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
EXPECT_FALSE(message->HasExtension(
unittest::optional_foreign_message_extension));
// Add a extension using SetAllocatedExtension
@@ -444,8 +444,8 @@ TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) {
}
TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) {
- ::google::protobuf::Arena arena1;
- std::unique_ptr<google::protobuf::Arena> arena2(new ::google::protobuf::Arena());
+ Arena arena1;
+ std::unique_ptr<Arena> arena2(new Arena());
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
@@ -467,7 +467,7 @@ TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) {
arena2.reset(NULL);
TestUtil::ExpectAllExtensionsSet(*message1);
// Test corner cases, when one is empty and other is not.
- ::google::protobuf::Arena arena3, arena4;
+ Arena arena3, arena4;
unittest::TestAllExtensions* message3 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena3);
@@ -480,8 +480,8 @@ TEST(ExtensionSetTest, SwapExtensionBothFullWithArena) {
}
TEST(ExtensionSetTest, SwapFieldsOfExtensionBothFullWithArena) {
- google::protobuf::Arena arena1;
- google::protobuf::Arena* arena2 = new ::google::protobuf::Arena();
+ Arena arena1;
+ Arena* arena2 = new Arena();
unittest::TestAllExtensions* message1 =
Arena::CreateMessage<unittest::TestAllExtensions>(&arena1);
@@ -527,7 +527,7 @@ TEST(ExtensionSetTest, SerializationToArray) {
int size = source.ByteSize();
string data;
data.resize(size);
- uint8* target = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = source.SerializeWithCachedSizesToArray(target);
EXPECT_EQ(size, end - target);
EXPECT_TRUE(destination.ParseFromString(data));
@@ -549,7 +549,7 @@ TEST(ExtensionSetTest, SerializationToStream) {
string data;
data.resize(size);
{
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
source.SerializeWithCachedSizes(&output_stream);
ASSERT_FALSE(output_stream.HadError());
@@ -571,7 +571,7 @@ TEST(ExtensionSetTest, PackedSerializationToArray) {
int size = source.ByteSize();
string data;
data.resize(size);
- uint8* target = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = source.SerializeWithCachedSizesToArray(target);
EXPECT_EQ(size, end - target);
EXPECT_TRUE(destination.ParseFromString(data));
@@ -593,7 +593,7 @@ TEST(ExtensionSetTest, PackedSerializationToStream) {
string data;
data.resize(size);
{
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
source.SerializeWithCachedSizes(&output_stream);
ASSERT_FALSE(output_stream.HadError());
@@ -1051,11 +1051,15 @@ TEST(ExtensionSetTest, RepeatedFields) {
enum_const_iter;
RepeatedField<unittest::TestAllTypes_NestedEnum>::const_iterator
enum_const_end;
- for (enum_const_iter = message.GetRepeatedExtension(
- unittest::repeated_nested_enum_extension).begin(),
- enum_const_end = message.GetRepeatedExtension(
- unittest::repeated_nested_enum_extension).end();
- enum_iter != enum_end; ++enum_iter) {
+ for (enum_const_iter =
+ message
+ .GetRepeatedExtension(unittest::repeated_nested_enum_extension)
+ .begin(),
+ enum_const_end =
+ message
+ .GetRepeatedExtension(unittest::repeated_nested_enum_extension)
+ .end();
+ enum_const_iter != enum_const_end; ++enum_const_iter) {
ASSERT_EQ(*enum_const_iter, unittest::TestAllTypes::NestedEnum_MAX);
}
@@ -1271,10 +1275,10 @@ TEST(ExtensionSetTest, DynamicExtensions) {
const Message& sub_message =
message.GetReflection()->GetMessage(message, message_extension);
const unittest::ForeignMessage* typed_sub_message =
-#ifdef GOOGLE_PROTOBUF_NO_RTTI
- static_cast<const unittest::ForeignMessage*>(&sub_message);
-#else
+#if PROTOBUF_RTTI
dynamic_cast<const unittest::ForeignMessage*>(&sub_message);
+#else
+ static_cast<const unittest::ForeignMessage*>(&sub_message);
#endif
ASSERT_TRUE(typed_sub_message != NULL);
EXPECT_EQ(456, typed_sub_message->c());
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc
index 000fa8d3..8b252996 100644
--- a/src/google/protobuf/field_mask.pb.cc
+++ b/src/google/protobuf/field_mask.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class FieldMaskDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FieldMask>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FieldMask> _instance;
} _FieldMask_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto {
-static void InitDefaultsFieldMask() {
+static void InitDefaultsFieldMask_google_2fprotobuf_2ffield_5fmask_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,24 +35,26 @@ static void InitDefaultsFieldMask() {
::google::protobuf::FieldMask::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldMask_google_2fprotobuf_2ffield_5fmask_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_FieldMask.base);
+void InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FieldMask, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FieldMask, paths_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::FieldMask)},
};
@@ -65,51 +62,33 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_FieldMask_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/field_mask.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2ffield_5fmask_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto, "google/protobuf/field_mask.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto,
+ "\n google/protobuf/field_mask.proto\022\017goog"
+ "le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB"
+ "\214\001\n\023com.google.protobufB\016FieldMaskProtoP"
+ "\001Z9google.golang.org/genproto/protobuf/f"
+ "ield_mask;field_mask\370\001\001\242\002\003GPB\252\002\036Google.P"
+ "rotobuf.WellKnownTypesb\006proto3"
+,
+ "google/protobuf/field_mask.proto", &assign_descriptors_table_google_2fprotobuf_2ffield_5fmask_2eproto, 230,
+};
-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"
- "\001Z9google.golang.org/genproto/protobuf/f"
- "ield_mask;field_mask\242\002\003GPB\252\002\036Google.Prot"
- "obuf.WellKnownTypesb\006proto3"
+void AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 227);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/field_mask.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto = []() { AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -117,17 +96,27 @@ namespace protobuf {
void FieldMask::InitAsDefaultInstance() {
}
+class FieldMask::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FieldMask::kPathsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FieldMask::FieldMask()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldMask)
}
+FieldMask::FieldMask(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ paths_(arena) {
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldMask)
+}
FieldMask::FieldMask(const FieldMask& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
@@ -137,6 +126,8 @@ FieldMask::FieldMask(const FieldMask& from)
}
void FieldMask::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base);
}
FieldMask::~FieldMask() {
@@ -145,18 +136,20 @@ FieldMask::~FieldMask() {
}
void FieldMask::SharedDtor() {
+ GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);
}
+void FieldMask::ArenaDtor(void* object) {
+ FieldMask* _this = reinterpret_cast< FieldMask* >(object);
+ (void)_this;
+}
+void FieldMask::RegisterArenaDtor(::google::protobuf::Arena*) {
+}
void FieldMask::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FieldMask::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::scc_info_FieldMask.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FieldMask_google_2fprotobuf_2ffield_5fmask_2eproto.base);
return *internal_default_instance();
}
@@ -171,9 +164,65 @@ void FieldMask::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FieldMask::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FieldMask*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated string paths = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.FieldMask.paths");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->add_paths();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FieldMask::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FieldMask)
for (;;) {
@@ -183,8 +232,7 @@ bool FieldMask::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string paths = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_paths()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -217,6 +265,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FieldMask::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -234,9 +283,9 @@ void FieldMask::SerializeWithCachedSizes(
1, this->paths(i), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FieldMask)
}
@@ -258,9 +307,9 @@ void FieldMask::SerializeWithCachedSizes(
WriteStringToArray(1, this->paths(i), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FieldMask)
return target;
@@ -270,11 +319,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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated string paths = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->paths_size());
@@ -292,7 +345,7 @@ void FieldMask::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldMask)
GOOGLE_DCHECK_NE(&from, this);
const FieldMask* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FieldMask>(
+ ::google::protobuf::DynamicCastToGenerated<FieldMask>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FieldMask)
@@ -333,17 +386,32 @@ bool FieldMask::IsInitialized() const {
void FieldMask::Swap(FieldMask* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ FieldMask* temp = New(GetArenaNoVirtual());
+ temp->MergeFrom(*other);
+ other->CopyFrom(*this);
+ InternalSwap(temp);
+ if (GetArenaNoVirtual() == NULL) {
+ delete temp;
+ }
+ }
+}
+void FieldMask::UnsafeArenaSwap(FieldMask* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void FieldMask::InternalSwap(FieldMask* other) {
using std::swap;
- paths_.InternalSwap(CastToBase(&other->paths_));
_internal_metadata_.Swap(&other->_internal_metadata_);
+ paths_.InternalSwap(CastToBase(&other->paths_));
}
::google::protobuf::Metadata FieldMask::GetMetadata() const {
- protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ffield_5fmask_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto[kIndexInFileMessages];
}
@@ -352,10 +420,11 @@ void FieldMask::InternalSwap(FieldMask* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) {
- return Arena::CreateInternal< ::google::protobuf::FieldMask >(arena);
+template<> PROTOBUF_NOINLINE ::google::protobuf::FieldMask* Arena::CreateMaybeMessage< ::google::protobuf::FieldMask >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::google::protobuf::FieldMask >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index 54b6372d..5b8561df 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,30 +32,28 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ffield_5fmask_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2ffield_5fmask_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2ffield_5fmask_2eproto();
namespace google {
namespace protobuf {
class FieldMask;
class FieldMaskDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*);
+PROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::FieldMask* Arena::CreateMaybeMessage<::google::protobuf::FieldMask>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -62,7 +61,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ {
+class PROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ {
public:
FieldMask();
virtual ~FieldMask();
@@ -88,7 +87,15 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ inline ::google::protobuf::Arena* GetArena() const final {
+ return GetArenaNoVirtual();
+ }
+ inline void* GetMaybeArenaPointer() const final {
+ return MaybeArenaPtr();
+ }
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FieldMask& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -99,6 +106,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
static constexpr int kIndexInFileMessages =
0;
+ void UnsafeArenaSwap(FieldMask* other);
void Swap(FieldMask* other);
friend void swap(FieldMask& a, FieldMask& b) {
a.Swap(&b);
@@ -121,8 +129,13 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -134,12 +147,17 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(FieldMask* other);
+ protected:
+ explicit FieldMask(::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:
@@ -168,16 +186,20 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
#endif
void add_paths(const char* value);
void add_paths(const char* value, size_t size);
- const ::google::protobuf::RepeatedPtrField< ::std::string>& paths() const;
- ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_paths();
+ const ::google::protobuf::RepeatedPtrField<::std::string>& paths() const;
+ ::google::protobuf::RepeatedPtrField<::std::string>* mutable_paths();
// @@protoc_insertion_point(class_scope:google.protobuf.FieldMask)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::RepeatedPtrField< ::std::string> paths_;
+ template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::google::protobuf::RepeatedPtrField<::std::string> paths_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ffield_5fmask_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto;
};
// ===================================================================
@@ -248,12 +270,12 @@ inline 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)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline const ::google::protobuf::RepeatedPtrField<::std::string>&
FieldMask::paths() const {
// @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths)
return paths_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::google::protobuf::RepeatedPtrField<::std::string>*
FieldMask::mutable_paths() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths)
return &paths_;
@@ -270,4 +292,5 @@ FieldMask::mutable_paths() {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
diff --git a/src/google/protobuf/field_mask.proto b/src/google/protobuf/field_mask.proto
index 76e09f39..4015b1a3 100644
--- a/src/google/protobuf/field_mask.proto
+++ b/src/google/protobuf/field_mask.proto
@@ -38,6 +38,7 @@ option java_outer_classname = "FieldMaskProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
+option cc_enable_arenas = true;
// `FieldMask` represents a set of symbolic field paths, for example:
//
@@ -107,57 +108,49 @@ option go_package = "google.golang.org/genproto/protobuf/field_mask;field_mask";
// 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 repeated field is specified for an update operation, new values will
+// be appended to the existing repeated field in the target resource. 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:
+// update operation, then new value will be merged into the existing sub-message
+// in the target resource.
+//
+// For example, given the target message:
//
// f {
// b {
-// d : 1
-// x : 2
+// d: 1
+// x: 2
// }
-// c : 1
+// c: [1]
// }
//
// And an update message:
//
// f {
// b {
-// d : 10
+// d: 10
// }
+// c: [2]
// }
//
// then if the field mask is:
//
-// paths: "f.b"
+// paths: ["f.b", "f.c"]
//
// then the result will be:
//
// f {
// b {
-// d : 10
+// d: 10
+// x: 2
// }
-// c : 1
+// c: [1, 2]
// }
//
-// However, if the update mask was:
-//
-// paths: "f.b.d"
-//
-// then the result would be:
-//
-// f {
-// b {
-// d : 10
-// x : 2
-// }
-// c : 1
-// }
+// An implementation may provide options to override this default behavior for
+// repeated and message fields.
//
// 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.
diff --git a/src/google/protobuf/generated_enum_reflection.h b/src/google/protobuf/generated_enum_reflection.h
index 983d3185..774528ee 100644
--- a/src/google/protobuf/generated_enum_reflection.h
+++ b/src/google/protobuf/generated_enum_reflection.h
@@ -41,13 +41,22 @@
#include <string>
+#include <google/protobuf/port.h>
#include <google/protobuf/generated_enum_util.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
class EnumDescriptor;
} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
// Returns the EnumDescriptor for enum type E, which must be a
@@ -61,13 +70,12 @@ namespace internal {
// Helper for EnumType_Parse functions: try to parse the string 'name' as an
// enum name of the given type, returning true and filling in value on success,
// or returning false and leaving value unchanged on failure.
-LIBPROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor,
- const string& name,
- int* value);
+PROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor,
+ const std::string& name, int* value);
template<typename EnumType>
bool ParseNamedEnum(const EnumDescriptor* descriptor,
- const string& name,
+ const std::string& name,
EnumType* value) {
int tmp;
if (!ParseNamedEnum(descriptor, name, &tmp)) return false;
@@ -78,10 +86,13 @@ bool ParseNamedEnum(const EnumDescriptor* descriptor,
// Just a wrapper around printing the name of a value. The main point of this
// function is not to be inlined, so that you can do this without including
// descriptor.h.
-LIBPROTOBUF_EXPORT const string& NameOfEnum(const EnumDescriptor* descriptor, int value);
+PROTOBUF_EXPORT const std::string& NameOfEnum(const EnumDescriptor* descriptor,
+ int value);
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__
diff --git a/src/google/protobuf/generated_enum_util.h b/src/google/protobuf/generated_enum_util.h
index 96b03cc9..5c4dd659 100644
--- a/src/google/protobuf/generated_enum_util.h
+++ b/src/google/protobuf/generated_enum_util.h
@@ -33,6 +33,10 @@
#include <type_traits>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
@@ -41,6 +45,6 @@ namespace protobuf {
template <typename T> struct is_proto_enum : ::std::false_type {};
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc
index 74ad00e7..f926da27 100644
--- a/src/google/protobuf/generated_message_reflection.cc
+++ b/src/google/protobuf/generated_message_reflection.cc
@@ -44,6 +44,8 @@
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/map_field.h>
+#include <google/protobuf/map_field_inl.h>
+#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
@@ -200,15 +202,7 @@ GeneratedMessageReflection::~GeneratedMessageReflection() {}
const UnknownFieldSet& GeneratedMessageReflection::GetUnknownFields(
const Message& message) const {
- 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 when Proto3 defaults to
- // discard unknowns.
- return *UnknownFieldSet::default_instance();
- } else {
- return GetInternalMetadataWithArena(message).unknown_fields();
- }
+ return GetInternalMetadataWithArena(message).unknown_fields();
}
UnknownFieldSet* GeneratedMessageReflection::MutableUnknownFields(
@@ -369,15 +363,12 @@ void GeneratedMessageReflection::SwapField(
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (IsMapFieldInApi(field)) {
- MutableRaw<MapFieldBase>(message1, field)->
- MutableRepeatedField()->
- Swap<GenericTypeHandler<google::protobuf::Message> >(
- MutableRaw<MapFieldBase>(message2, field)->
- MutableRepeatedField());
+ MutableRaw<MapFieldBase>(message1, field)->Swap(
+ MutableRaw<MapFieldBase>(message2, field));
} else {
- MutableRaw<RepeatedPtrFieldBase>(message1, field)->
- Swap<GenericTypeHandler<google::protobuf::Message> >(
- MutableRaw<RepeatedPtrFieldBase>(message2, field));
+ MutableRaw<RepeatedPtrFieldBase>(message1, field)
+ ->Swap<GenericTypeHandler<Message> >(
+ MutableRaw<RepeatedPtrFieldBase>(message2, field));
}
break;
@@ -1035,8 +1026,6 @@ void GeneratedMessageReflection::ListFields(
const uint32* const has_bits =
schema_.HasHasbits() ? GetHasBits(message) : NULL;
const uint32* const has_bits_indices = schema_.has_bit_indices_;
- const uint32* const oneof_case_array =
- 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);
@@ -1047,6 +1036,8 @@ void GeneratedMessageReflection::ListFields(
} else {
const OneofDescriptor* containing_oneof = field->containing_oneof();
if (containing_oneof) {
+ const uint32* const oneof_case_array = GetConstPointerAtOffset<uint32>(
+ &message, schema_.oneof_case_offset_);
// Equivalent to: HasOneofField(message, field)
if (oneof_case_array[containing_oneof->index()] == field->number()) {
output->push_back(field);
@@ -1210,8 +1201,9 @@ void GeneratedMessageReflection::SetString(
MutableField<ArenaStringPtr>(message, field)->UnsafeSetDefault(
default_ptr);
}
- MutableField<ArenaStringPtr>(message, field)->Set(default_ptr,
- value, GetArena(message));
+ MutableField<ArenaStringPtr>(message, field)
+ ->Mutable(default_ptr, GetArena(message))
+ ->assign(value);
break;
}
}
@@ -1330,11 +1322,8 @@ void GeneratedMessageReflection::SetEnumValue(
const EnumValueDescriptor* value_desc =
field->enum_type()->FindValueByNumber(value);
if (value_desc == NULL) {
- GOOGLE_LOG(DFATAL) << "SetEnumValue accepts only valid integer values: value "
- << value << " unexpected for field " << field->full_name();
- // In production builds, DFATAL will not terminate the program, so we have
- // to do something reasonable: just set the default value.
- value = field->default_value_enum()->number();
+ MutableUnknownFields(message)->AddVarint(field->number(), value);
+ return;
}
}
SetEnumValueInternal(message, field, value);
@@ -1391,12 +1380,8 @@ void GeneratedMessageReflection::SetRepeatedEnumValue(
const EnumValueDescriptor* value_desc =
field->enum_type()->FindValueByNumber(value);
if (value_desc == NULL) {
- GOOGLE_LOG(DFATAL) << "SetRepeatedEnumValue accepts only valid integer values: "
- << "value " << value << " unexpected for field "
- << field->full_name();
- // In production builds, DFATAL will not terminate the program, so we have
- // to do something reasonable: just set the default value.
- value = field->default_value_enum()->number();
+ MutableUnknownFields(message)->AddVarint(field->number(), value);
+ return;
}
}
SetRepeatedEnumValueInternal(message, field, index, value);
@@ -1432,11 +1417,8 @@ void GeneratedMessageReflection::AddEnumValue(
const EnumValueDescriptor* value_desc =
field->enum_type()->FindValueByNumber(value);
if (value_desc == NULL) {
- GOOGLE_LOG(DFATAL) << "AddEnumValue accepts only valid integer values: value "
- << value << " unexpected for field " << field->full_name();
- // In production builds, DFATAL will not terminate the program, so we have
- // to do something reasonable: just set the default value.
- value = field->default_value_enum()->number();
+ MutableUnknownFields(message)->AddVarint(field->number(), value);
+ return;
}
}
AddEnumValueInternal(message, field, value);
@@ -1724,7 +1706,7 @@ void* GeneratedMessageReflection::MutableRawRepeatedField(
if (field->cpp_type() != cpptype)
ReportReflectionUsageTypeError(descriptor_,
field, "MutableRawRepeatedField", cpptype);
- if (ctype >= 0)
+ if (ctype >= 0 && !field->is_extension())
GOOGLE_CHECK_EQ(field->options().ctype(), ctype) << "subtype mismatch";
if (desc != NULL)
GOOGLE_CHECK_EQ(field->message_type(), desc) << "wrong submessage type";
@@ -2298,7 +2280,7 @@ class AssignDescriptorsHelper {
descriptor,
MigrationToReflectionSchema(default_instance_data_, offsets_,
*schemas_),
- ::google::protobuf::DescriptorPool::generated_pool(), factory_);
+ DescriptorPool::generated_pool(), factory_);
for (int i = 0; i < descriptor->enum_type_count(); i++) {
AssignEnumDescriptor(descriptor->enum_type(i));
}
@@ -2336,8 +2318,9 @@ struct MetadataOwner {
}
void AddArray(const Metadata* begin, const Metadata* end) {
- MutexLock lock(&mu_);
+ mu_.Lock();
metadata_arrays_.push_back(std::make_pair(begin, end));
+ mu_.Unlock();
}
static MetadataOwner* Instance() {
@@ -2348,28 +2331,30 @@ struct MetadataOwner {
private:
MetadataOwner() = default; // private because singleton
- Mutex mu_;
+ WrappedMutex mu_;
std::vector<std::pair<const Metadata*, const Metadata*> > metadata_arrays_;
};
-} // namespace
-
-void AssignDescriptors(
- const string& filename, const MigrationSchema* schemas,
- const Message* const* default_instances_, const uint32* offsets,
- // 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);
+void AssignDescriptorsImpl(const AssignDescriptorsTable* table) {
+ // Ensure the file descriptor is added to the pool.
+ {
+ // This only happens once per proto file. So a global mutex to serialize
+ // calls to AddDescriptors.
+ static WrappedMutex mu{GOOGLE_PROTOBUF_LINKER_INITIALIZED};
+ mu.Lock();
+ table->add_descriptors();
+ mu.Unlock();
+ }
+ // Fill the arrays with pointers to descriptors and reflection classes.
+ const FileDescriptor* file =
+ DescriptorPool::generated_pool()->FindFileByName(table->filename);
GOOGLE_CHECK(file != NULL);
MessageFactory* factory = MessageFactory::generated_factory();
- AssignDescriptorsHelper<MigrationSchema> helper(factory, file_level_metadata,
- file_level_enum_descriptors, schemas,
- default_instances_, offsets);
+ AssignDescriptorsHelper<MigrationSchema> helper(
+ factory, table->file_level_metadata, table->file_level_enum_descriptors,
+ table->schemas, table->default_instances, table->offsets);
for (int i = 0; i < file->message_type_count(); i++) {
helper.AssignMessageDescriptor(file->message_type(i));
@@ -2380,13 +2365,48 @@ void AssignDescriptors(
}
if (file->options().cc_generic_services()) {
for (int i = 0; i < file->service_count(); i++) {
- file_level_service_descriptors[i] = file->service(i);
+ table->file_level_service_descriptors[i] = file->service(i);
}
}
- MetadataOwner::Instance()->AddArray(
- file_level_metadata, helper.GetCurrentMetadataPtr());
+ MetadataOwner::Instance()->AddArray(table->file_level_metadata,
+ helper.GetCurrentMetadataPtr());
+}
+
+void AddDescriptorsImpl(const DescriptorTable* table, const InitFunc* deps,
+ int num_deps) {
+ // Ensure default instances of this proto file are initialized.
+ table->init_defaults();
+ // Ensure all dependent descriptors are registered to the generated descriptor
+ // pool and message factory.
+ for (int i = 0; i < num_deps; i++) {
+ // In case of weak fields deps[i] could be null.
+ if (deps[i]) deps[i]();
+ }
+ // Register the descriptor of this file.
+ DescriptorPool::InternalAddGeneratedFile(table->descriptor, table->size);
+ MessageFactory::InternalRegisterGeneratedFile(
+ table->filename, table->assign_descriptors_table);
+}
+
+} // namespace
+
+void AssignDescriptors(AssignDescriptorsTable* table) {
+ call_once(table->once, AssignDescriptorsImpl, table);
+}
+
+void AddDescriptors(DescriptorTable* table, const InitFunc* deps,
+ int num_deps) {
+ // AddDescriptors is not thread safe. Callers need to ensure calls are
+ // properly serialized. This function is only called pre-main by global
+ // descriptors and we can assume single threaded access or it's called
+ // by AssignDescriptorImpl which uses a mutex to sequence calls.
+ if (table->is_initialized) return;
+ table->is_initialized = true;
+ AddDescriptorsImpl(table, deps, num_deps);
}
+// Separate function because it needs to be a friend of
+// GeneratedMessageReflection
void RegisterAllTypesInternal(const Metadata* file_level_metadata, int size) {
for (int i = 0; i < size; i++) {
const GeneratedMessageReflection* reflection =
@@ -2394,26 +2414,28 @@ void RegisterAllTypesInternal(const Metadata* file_level_metadata, int size) {
file_level_metadata[i].reflection);
if (reflection) {
// It's not a map type
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ MessageFactory::InternalRegisterGeneratedMessage(
file_level_metadata[i].descriptor,
reflection->schema_.default_instance_);
}
}
}
-void RegisterAllTypes(const Metadata* file_level_metadata, int size) {
- RegisterAllTypesInternal(file_level_metadata, size);
+void RegisterFileLevelMetadata(void* assign_descriptors_table) {
+ auto table = static_cast<AssignDescriptorsTable*>(assign_descriptors_table);
+ AssignDescriptors(table);
+ RegisterAllTypesInternal(table->file_level_metadata, table->num_messages);
}
void UnknownFieldSetSerializer(const uint8* base, uint32 offset, uint32 tag,
uint32 has_offset,
- ::google::protobuf::io::CodedOutputStream* output) {
+ 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);
+ internal::WireFormat::SerializeUnknownFields(metadata->unknown_fields(),
+ output);
}
}
diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h
index 31f249b6..0ffb3ff2 100644
--- a/src/google/protobuf/generated_message_reflection.h
+++ b/src/google/protobuf/generated_message_reflection.h
@@ -47,33 +47,44 @@
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/metadata.h>
+#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/unknown_field_set.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace upb {
namespace google_opensource {
class GMR_Handlers;
} // namespace google_opensource
} // namespace upb
+namespace google {
namespace protobuf {
class DescriptorPool;
class MapKey;
class MapValueRef;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace flat {
class MetadataBuilder;
} // namespace flat
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace internal {
class DefaultEmptyOneof;
+class ReflectionAccessor;
// Defined in this file.
class GeneratedMessageReflection;
@@ -98,7 +109,7 @@ class WeakFieldMap; // weak_field_map.h
// 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.
+// PROTO2_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].
@@ -304,199 +315,198 @@ class GeneratedMessageReflection final : public Reflection {
const DescriptorPool* pool,
MessageFactory* factory);
- ~GeneratedMessageReflection();
+ ~GeneratedMessageReflection() override;
// implements Reflection -------------------------------------------
- const UnknownFieldSet& GetUnknownFields(const Message& message) const;
- UnknownFieldSet* MutableUnknownFields(Message* message) const;
+ const UnknownFieldSet& GetUnknownFields(
+ const Message& message) const override;
+ UnknownFieldSet* MutableUnknownFields(Message* message) const override;
- size_t SpaceUsedLong(const Message& message) const;
+ size_t SpaceUsedLong(const Message& message) const override;
- bool HasField(const Message& message, const FieldDescriptor* field) const;
- int FieldSize(const Message& message, const FieldDescriptor* field) const;
- void ClearField(Message* message, const FieldDescriptor* field) const;
+ bool HasField(const Message& message,
+ const FieldDescriptor* field) const override;
+ int FieldSize(const Message& message,
+ const FieldDescriptor* field) const override;
+ void ClearField(Message* message,
+ const FieldDescriptor* field) const override;
bool HasOneof(const Message& message,
- const OneofDescriptor* oneof_descriptor) const;
- void ClearOneof(Message* message, const OneofDescriptor* field) const;
- void RemoveLast(Message* message, const FieldDescriptor* field) const;
- Message* ReleaseLast(Message* message, const FieldDescriptor* field) const;
- void Swap(Message* message1, Message* message2) const;
- void SwapFields(Message* message1, Message* message2,
- const std::vector<const FieldDescriptor*>& fields) const;
- void SwapElements(Message* message, const FieldDescriptor* field,
- int index1, int index2) const;
+ const OneofDescriptor* oneof_descriptor) const override;
+ void ClearOneof(Message* message,
+ const OneofDescriptor* oneof_descriptor) const override;
+ void RemoveLast(Message* message,
+ const FieldDescriptor* field) const override;
+ Message* ReleaseLast(Message* message,
+ const FieldDescriptor* field) const override;
+ void Swap(Message* message1, Message* message2) const override;
+ void SwapFields(
+ Message* message1, Message* message2,
+ const std::vector<const FieldDescriptor*>& fields) const override;
+ void SwapElements(Message* message, const FieldDescriptor* field, int index1,
+ int index2) const override;
void ListFields(const Message& message,
- std::vector<const FieldDescriptor*>* output) const;
-
- int32 GetInt32 (const Message& message,
- const FieldDescriptor* field) const;
- int64 GetInt64 (const Message& message,
- const FieldDescriptor* field) const;
+ std::vector<const FieldDescriptor*>* output) const override;
+ int32 GetInt32(const Message& message,
+ const FieldDescriptor* field) const override;
+ int64 GetInt64(const Message& message,
+ const FieldDescriptor* field) const override;
uint32 GetUInt32(const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
uint64 GetUInt64(const Message& message,
- const FieldDescriptor* field) const;
- float GetFloat (const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
+ float GetFloat(const Message& message,
+ const FieldDescriptor* field) const override;
double GetDouble(const Message& message,
- const FieldDescriptor* field) const;
- bool GetBool (const Message& message,
- const FieldDescriptor* field) const;
- string GetString(const Message& message,
- const FieldDescriptor* field) const;
- const string& GetStringReference(const Message& message,
+ const FieldDescriptor* field) const override;
+ bool GetBool(const Message& message,
+ const FieldDescriptor* field) const override;
+ std::string GetString(const Message& message,
+ const FieldDescriptor* field) const override;
+ const std::string& GetStringReference(const Message& message,
const FieldDescriptor* field,
- string* scratch) const;
- const EnumValueDescriptor* GetEnum(const Message& message,
- const FieldDescriptor* field) const;
+ std::string* scratch) const override;
+ const EnumValueDescriptor* GetEnum(
+ const Message& message, const FieldDescriptor* field) const override;
int GetEnumValue(const Message& message,
- const FieldDescriptor* field) const;
+ const FieldDescriptor* field) const override;
const Message& GetMessage(const Message& message,
const FieldDescriptor* field,
- MessageFactory* factory = NULL) const;
+ MessageFactory* factory = NULL) const override;
const FieldDescriptor* GetOneofFieldDescriptor(
const Message& message,
- const OneofDescriptor* oneof_descriptor) const;
+ const OneofDescriptor* oneof_descriptor) const override;
private:
- bool ContainsMapKey(const Message& message,
- const FieldDescriptor* field,
- const MapKey& key) const;
- bool InsertOrLookupMapValue(Message* message,
- const FieldDescriptor* field,
+ bool ContainsMapKey(const Message& message, const FieldDescriptor* field,
+ const MapKey& key) const override;
+ bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
const MapKey& key,
- MapValueRef* val) const;
- bool DeleteMapValue(Message* message,
- const FieldDescriptor* field,
- const MapKey& key) const;
- MapIterator MapBegin(
- Message* message,
- const FieldDescriptor* field) const;
- MapIterator MapEnd(
- Message* message,
- const FieldDescriptor* field) const;
- int MapSize(const Message& message, const FieldDescriptor* field) const;
+ MapValueRef* val) const override;
+ bool DeleteMapValue(Message* message, const FieldDescriptor* field,
+ const MapKey& key) const override;
+ MapIterator MapBegin(Message* message,
+ const FieldDescriptor* field) const override;
+ MapIterator MapEnd(Message* message,
+ const FieldDescriptor* field) const override;
+ int MapSize(const Message& message,
+ const FieldDescriptor* field) const override;
public:
- void SetInt32 (Message* message,
- const FieldDescriptor* field, int32 value) const;
- void SetInt64 (Message* message,
- const FieldDescriptor* field, int64 value) const;
- void SetUInt32(Message* message,
- const FieldDescriptor* field, uint32 value) const;
- void SetUInt64(Message* message,
- const FieldDescriptor* field, uint64 value) const;
- void SetFloat (Message* message,
- const FieldDescriptor* field, float value) const;
- void SetDouble(Message* message,
- const FieldDescriptor* field, double value) const;
- void SetBool (Message* message,
- const FieldDescriptor* field, bool value) const;
- void SetString(Message* message,
- const FieldDescriptor* field,
- const string& value) const;
- void SetEnum (Message* message, const FieldDescriptor* field,
- const EnumValueDescriptor* value) const;
+ void SetInt32(Message* message, const FieldDescriptor* field,
+ int32 value) const override;
+ void SetInt64(Message* message, const FieldDescriptor* field,
+ int64 value) const override;
+ void SetUInt32(Message* message, const FieldDescriptor* field,
+ uint32 value) const override;
+ void SetUInt64(Message* message, const FieldDescriptor* field,
+ uint64 value) const override;
+ void SetFloat(Message* message, const FieldDescriptor* field,
+ float value) const override;
+ void SetDouble(Message* message, const FieldDescriptor* field,
+ double value) const override;
+ void SetBool(Message* message, const FieldDescriptor* field,
+ bool value) const override;
+ void SetString(Message* message, const FieldDescriptor* field,
+ const std::string& value) const override;
+ void SetEnum(Message* message, const FieldDescriptor* field,
+ const EnumValueDescriptor* value) const override;
void SetEnumValue(Message* message, const FieldDescriptor* field,
- int value) const;
+ int value) const override;
Message* MutableMessage(Message* message, const FieldDescriptor* field,
- MessageFactory* factory = NULL) const;
- void SetAllocatedMessage(Message* message,
- Message* sub_message,
- const FieldDescriptor* field) const;
+ MessageFactory* factory = NULL) const override;
+ void SetAllocatedMessage(Message* message, Message* sub_message,
+ const FieldDescriptor* field) const override;
Message* ReleaseMessage(Message* message, const FieldDescriptor* field,
- MessageFactory* factory = NULL) const;
-
- int32 GetRepeatedInt32 (const Message& message,
- const FieldDescriptor* field, int index) const;
- int64 GetRepeatedInt64 (const Message& message,
- const FieldDescriptor* field, int index) const;
- uint32 GetRepeatedUInt32(const Message& message,
- const FieldDescriptor* field, int index) const;
- uint64 GetRepeatedUInt64(const Message& message,
- const FieldDescriptor* field, int index) const;
- float GetRepeatedFloat (const Message& message,
- const FieldDescriptor* field, int index) const;
- double GetRepeatedDouble(const Message& message,
- const FieldDescriptor* field, int index) const;
- bool GetRepeatedBool (const Message& message,
- const FieldDescriptor* field, int index) const;
- string GetRepeatedString(const Message& message,
- const FieldDescriptor* field, int index) const;
- const string& GetRepeatedStringReference(const Message& message,
+ MessageFactory* factory = NULL) const override;
+
+ int32 GetRepeatedInt32(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ int64 GetRepeatedInt64(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ uint32 GetRepeatedUInt32(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ uint64 GetRepeatedUInt64(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ float GetRepeatedFloat(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ double GetRepeatedDouble(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ bool GetRepeatedBool(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ std::string GetRepeatedString(const Message& message, const FieldDescriptor* field,
+ int index) const override;
+ const std::string& GetRepeatedStringReference(const Message& message,
const FieldDescriptor* field,
- int index, string* scratch) const;
+ int index,
+ std::string* scratch) const override;
const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
const FieldDescriptor* field,
- int index) const;
- int GetRepeatedEnumValue(const Message& message,
- const FieldDescriptor* field,
- int index) const;
+ int index) const override;
+ int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field,
+ int index) const override;
const Message& GetRepeatedMessage(const Message& message,
const FieldDescriptor* field,
- int index) const;
+ int index) const override;
// Set the value of a field.
- void SetRepeatedInt32 (Message* message,
- const FieldDescriptor* field, int index, int32 value) const;
- void SetRepeatedInt64 (Message* message,
- const FieldDescriptor* field, int index, int64 value) const;
- void SetRepeatedUInt32(Message* message,
- const FieldDescriptor* field, int index, uint32 value) const;
- void SetRepeatedUInt64(Message* message,
- const FieldDescriptor* field, int index, uint64 value) const;
- void SetRepeatedFloat (Message* message,
- const FieldDescriptor* field, int index, float value) const;
- void SetRepeatedDouble(Message* message,
- const FieldDescriptor* field, int index, double value) const;
- void SetRepeatedBool (Message* message,
- const FieldDescriptor* field, int index, bool value) const;
- void SetRepeatedString(Message* message,
- const FieldDescriptor* field, int index,
- const string& value) const;
+ void SetRepeatedInt32(Message* message, const FieldDescriptor* field,
+ int index, int32 value) const override;
+ void SetRepeatedInt64(Message* message, const FieldDescriptor* field,
+ int index, int64 value) const override;
+ void SetRepeatedUInt32(Message* message, const FieldDescriptor* field,
+ int index, uint32 value) const override;
+ void SetRepeatedUInt64(Message* message, const FieldDescriptor* field,
+ int index, uint64 value) const override;
+ void SetRepeatedFloat(Message* message, const FieldDescriptor* field,
+ int index, float value) const override;
+ void SetRepeatedDouble(Message* message, const FieldDescriptor* field,
+ int index, double value) const override;
+ void SetRepeatedBool(Message* message, const FieldDescriptor* field,
+ int index, bool value) const override;
+ void SetRepeatedString(Message* message, const FieldDescriptor* field,
+ int index, const std::string& value) const override;
void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
- int index, const EnumValueDescriptor* value) const;
+ int index,
+ const EnumValueDescriptor* value) const override;
void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
- int index, int value) const;
+ int index, int value) const override;
// Get a mutable pointer to a field with a message type.
Message* MutableRepeatedMessage(Message* message,
const FieldDescriptor* field,
- int index) const;
-
- void AddInt32 (Message* message,
- const FieldDescriptor* field, int32 value) const;
- void AddInt64 (Message* message,
- const FieldDescriptor* field, int64 value) const;
- void AddUInt32(Message* message,
- const FieldDescriptor* field, uint32 value) const;
- void AddUInt64(Message* message,
- const FieldDescriptor* field, uint64 value) const;
- void AddFloat (Message* message,
- const FieldDescriptor* field, float value) const;
- void AddDouble(Message* message,
- const FieldDescriptor* field, double value) const;
- void AddBool (Message* message,
- const FieldDescriptor* field, bool value) const;
- void AddString(Message* message,
- const FieldDescriptor* field, const string& value) const;
- void AddEnum(Message* message,
- const FieldDescriptor* field,
- const EnumValueDescriptor* value) const;
- void AddEnumValue(Message* message,
- const FieldDescriptor* field,
- int value) const;
+ int index) const override;
+
+ void AddInt32(Message* message, const FieldDescriptor* field,
+ int32 value) const override;
+ void AddInt64(Message* message, const FieldDescriptor* field,
+ int64 value) const override;
+ void AddUInt32(Message* message, const FieldDescriptor* field,
+ uint32 value) const override;
+ void AddUInt64(Message* message, const FieldDescriptor* field,
+ uint64 value) const override;
+ void AddFloat(Message* message, const FieldDescriptor* field,
+ float value) const override;
+ void AddDouble(Message* message, const FieldDescriptor* field,
+ double value) const override;
+ void AddBool(Message* message, const FieldDescriptor* field,
+ bool value) const override;
+ void AddString(Message* message, const FieldDescriptor* field,
+ const std::string& value) const override;
+ void AddEnum(Message* message, const FieldDescriptor* field,
+ const EnumValueDescriptor* value) const override;
+ void AddEnumValue(Message* message, const FieldDescriptor* field,
+ int value) const override;
Message* AddMessage(Message* message, const FieldDescriptor* field,
- MessageFactory* factory = NULL) const;
- void AddAllocatedMessage(
- Message* message, const FieldDescriptor* field,
- Message* new_entry) const;
+ MessageFactory* factory = NULL) const override;
+ void AddAllocatedMessage(Message* message, const FieldDescriptor* field,
+ Message* new_entry) const override;
- const FieldDescriptor* FindKnownExtensionByName(const string& name) const;
- const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
+ const FieldDescriptor* FindKnownExtensionByName(
+ const std::string& name) const override;
+ const FieldDescriptor* FindKnownExtensionByNumber(int number) const override;
- bool SupportsUnknownEnumValues() const;
+ bool SupportsUnknownEnumValues() const override;
// This value for arena_offset_ indicates that there is no arena pointer in
// this message (e.g., old generated code).
@@ -512,24 +522,24 @@ class GeneratedMessageReflection final : public Reflection {
static const int kUnknownFieldSetInMetadata = -1;
protected:
- void* MutableRawRepeatedField(
- Message* message, const FieldDescriptor* field, FieldDescriptor::CppType,
- int ctype, const Descriptor* desc) const;
+ void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field,
+ FieldDescriptor::CppType, int ctype,
+ const Descriptor* desc) const override;
- const void* GetRawRepeatedField(
- const Message& message, const FieldDescriptor* field,
- FieldDescriptor::CppType, int ctype,
- const Descriptor* desc) const;
+ const void* GetRawRepeatedField(const Message& message,
+ const FieldDescriptor* field,
+ FieldDescriptor::CppType, int ctype,
+ const Descriptor* desc) const override;
- virtual MessageFactory* GetMessageFactory() const;
+ MessageFactory* GetMessageFactory() const override;
- virtual void* RepeatedFieldData(
- Message* message, const FieldDescriptor* field,
- FieldDescriptor::CppType cpp_type,
- const Descriptor* message_type) const;
+ void* RepeatedFieldData(Message* message, const FieldDescriptor* field,
+ FieldDescriptor::CppType cpp_type,
+ const Descriptor* message_type) const override;
private:
friend class google::protobuf::flat::MetadataBuilder;
+ friend class ReflectionAccessor;
friend class upb::google_opensource::GMR_Handlers;
const Descriptor* const descriptor_;
@@ -660,8 +670,8 @@ class GeneratedMessageReflection final : public Reflection {
Message* sub_message,
const FieldDescriptor* field) const;
- internal::MapFieldBase* MapData(
- Message* message, const FieldDescriptor* field) const;
+ internal::MapFieldBase* MapData(Message* message,
+ const FieldDescriptor* field) const override;
friend inline // inline so nobody can call this function.
void
@@ -669,89 +679,45 @@ class GeneratedMessageReflection final : public Reflection {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratedMessageReflection);
};
-// 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:
-// void MergeFrom(const FooMessage& other);
-// void MergeFrom(const Message& other);
-// The former method can be implemented directly in terms of FooMessage's
-// inline accessors, but the latter method must work with the reflection
-// interface. However, if the parameter to the latter method is actually of
-// type FooMessage, then we'd like to be able to just call the other method
-// as an optimization. So, we use dynamic_cast to check this.
-//
-// That said, dynamic_cast requires RTTI, which many people like to disable
-// for performance and code size reasons. When RTTI is not available, we
-// still need to produce correct results. So, in this case we have to fall
-// back to using reflection, which is what we would have done anyway if the
-// objects were not of the exact same class.
-//
-// dynamic_cast_if_available() implements this logic. If RTTI is
-// enabled, it does a dynamic_cast. If RTTI is disabled, it just returns
-// NULL.
-template<typename To, typename From>
-inline To dynamic_cast_if_available(From from) {
-#ifdef GOOGLE_PROTOBUF_NO_RTTI
- // Avoid the compiler warning about unused variables.
- (void)from;
- return NULL;
-#else
- return dynamic_cast<To>(from);
-#endif
-}
-
-// Tries to downcast this message to a generated message type.
-// Returns NULL if this class is not an instance of T.
-//
-// This is like dynamic_cast_if_available, except it works even when
-// dynamic_cast is not available by using Reflection. However it only works
-// with Message objects.
-//
-// TODO(haberman): can we remove dynamic_cast_if_available in favor of this?
-template <typename T>
-T* DynamicCastToGenerated(const Message* from) {
- // Compile-time assert that T is a generated type that has a
- // default_instance() accessor, but avoid actually calling it.
- const T&(*get_default_instance)() = &T::default_instance;
- (void)get_default_instance;
-
- // Compile-time assert that T is a subclass of google::protobuf::Message.
- const Message* unused = static_cast<T*>(NULL);
- (void)unused;
-
-#ifdef GOOGLE_PROTOBUF_NO_RTTI
- bool ok = &T::default_instance() ==
- from->GetReflection()->GetMessageFactory()->GetPrototype(
- from->GetDescriptor());
- return ok ? down_cast<T*>(from) : NULL;
-#else
- return dynamic_cast<T*>(from);
-#endif
-}
+typedef void (*InitFunc)();
+
+struct PROTOBUF_EXPORT AssignDescriptorsTable {
+ once_flag once;
+ InitFunc add_descriptors;
+ const char* filename;
+ const MigrationSchema* schemas;
+ const Message* const* default_instances;
+ const uint32* offsets;
+ // update the following descriptor arrays.
+ Metadata* file_level_metadata;
+ int num_messages;
+ const EnumDescriptor** file_level_enum_descriptors;
+ const ServiceDescriptor** file_level_service_descriptors;
+};
-template <typename T>
-T* DynamicCastToGenerated(Message* from) {
- const Message* message_const = from;
- return const_cast<T*>(DynamicCastToGenerated<const T>(message_const));
-}
+void PROTOBUF_EXPORT AssignDescriptors(AssignDescriptorsTable* table);
-LIBPROTOBUF_EXPORT void AssignDescriptors(
- const string& filename, const MigrationSchema* schemas,
- const Message* const* default_instances_, const uint32* offsets,
- // update the following descriptor arrays.
- Metadata* file_level_metadata,
- const EnumDescriptor** file_level_enum_descriptors,
- const ServiceDescriptor** file_level_service_descriptors);
+struct PROTOBUF_EXPORT DescriptorTable {
+ bool is_initialized;
+ InitFunc init_defaults;
+ const char* descriptor;
+ const char* filename;
+ AssignDescriptorsTable* assign_descriptors_table;
+ int size; // of serialized descriptor
+};
-LIBPROTOBUF_EXPORT void RegisterAllTypes(const Metadata* file_level_metadata, int size);
+void PROTOBUF_EXPORT AddDescriptors(DescriptorTable* table,
+ const InitFunc* deps, int num_deps);
// 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);
+PROTOBUF_EXPORT void UnknownFieldSetSerializer(const uint8* base, uint32 offset,
+ uint32 tag, uint32 has_offset,
+ io::CodedOutputStream* output);
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__
diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc
index 61eb6603..c74e4f5e 100644
--- a/src/google/protobuf/generated_message_reflection_unittest.cc
+++ b/src/google/protobuf/generated_message_reflection_unittest.cc
@@ -520,9 +520,9 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedMessageTest) {
TEST(GeneratedMessageReflectionTest, SetAllocatedMessageOnArenaTest) {
unittest::TestAllTypes from_message1;
unittest::TestAllTypes from_message2;
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllTypes* to_message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ Arena::CreateMessage<unittest::TestAllTypes>(&arena);
TestUtil::ReflectionTester reflection_tester(
unittest::TestAllTypes::descriptor());
reflection_tester.SetAllFieldsViaReflection(&from_message1);
@@ -586,9 +586,9 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageTest) {
}
TEST(GeneratedMessageReflectionTest, SetAllocatedExtensionMessageOnArenaTest) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllExtensions* to_message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
unittest::TestAllExtensions from_message1;
unittest::TestAllExtensions from_message2;
TestUtil::ReflectionTester reflection_tester(
@@ -798,9 +798,9 @@ TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageTest) {
TEST(GeneratedMessageReflectionTest, SetAllocatedOneofMessageOnArenaTest) {
unittest::TestOneof2 from_message1;
unittest::TestOneof2 from_message2;
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestOneof2* to_message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestOneof2>(&arena);
+ Arena::CreateMessage<unittest::TestOneof2>(&arena);
const Descriptor* descriptor = unittest::TestOneof2::descriptor();
const Reflection* reflection = to_message->GetReflection();
@@ -921,9 +921,9 @@ TEST(GeneratedMessageReflectionTest, ReleaseOneofMessageTest) {
}
TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllTypes* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllTypes>(&arena);
+ Arena::CreateMessage<unittest::TestAllTypes>(&arena);
TestUtil::ReflectionTester reflection_tester(
unittest::TestAllTypes::descriptor());
@@ -945,9 +945,9 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseMessageTest) {
}
TEST(GeneratedMessageReflectionTest, ArenaReleaseExtensionMessageTest) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestAllExtensions* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
+ Arena::CreateMessage<unittest::TestAllExtensions>(&arena);
TestUtil::ReflectionTester reflection_tester(
unittest::TestAllExtensions::descriptor());
@@ -969,9 +969,9 @@ TEST(GeneratedMessageReflectionTest, ArenaReleaseExtensionMessageTest) {
}
TEST(GeneratedMessageReflectionTest, ArenaReleaseOneofMessageTest) {
- ::google::protobuf::Arena arena;
+ Arena arena;
unittest::TestOneof2* message =
- ::google::protobuf::Arena::CreateMessage<unittest::TestOneof2>(&arena);
+ Arena::CreateMessage<unittest::TestOneof2>(&arena);
TestUtil::ReflectionTester::SetOneofViaReflection(message);
const Descriptor* descriptor = unittest::TestOneof2::descriptor();
diff --git a/src/google/protobuf/generated_message_table_driven.h b/src/google/protobuf/generated_message_table_driven.h
index 10ca3aaa..eb85ef5b 100644
--- a/src/google/protobuf/generated_message_table_driven.h
+++ b/src/google/protobuf/generated_message_table_driven.h
@@ -48,6 +48,10 @@
#define PROTOBUF_CONSTEXPR_VAR
#endif // !_clang
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -64,6 +68,10 @@ static constexpr const unsigned char kNotPackedMask = 0x10;
static 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_STRING_INLINED = 23,
TYPE_BYTES_INLINED = 24,
TYPE_MAP = 25,
@@ -183,18 +191,16 @@ bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table,
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>
+ typedef 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);
+ return 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
index 961329f3..83c81806 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.cc
+++ b/src/google/protobuf/generated_message_table_driven_lite.cc
@@ -54,23 +54,21 @@ struct UnknownFieldHandlerLite {
io::CodedInputStream* input,
int tag) {
GOOGLE_DCHECK(!table.unknown_field_set);
- ::google::protobuf::io::StringOutputStream unknown_fields_string(
+ io::StringOutputStream unknown_fields_string(
MutableUnknownFields(msg, table.arena_offset));
- ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
- &unknown_fields_string, false);
+ io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false);
- return ::google::protobuf::internal::WireFormatLite::SkipField(
- input, tag, &unknown_fields_stream);
+ return 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(
+ io::StringOutputStream unknown_fields_string(
MutableUnknownFields(msg, table.arena_offset));
- ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
- &unknown_fields_string, false);
+ io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false);
unknown_fields_stream.WriteVarint32(tag);
unknown_fields_stream.WriteVarint32(value);
}
@@ -86,10 +84,9 @@ struct UnknownFieldHandlerLite {
const MessageLite* prototype = table.default_instance();
GOOGLE_DCHECK(!table.unknown_field_set);
- ::google::protobuf::io::StringOutputStream unknown_fields_string(
+ io::StringOutputStream unknown_fields_string(
MutableUnknownFields(msg, table.arena_offset));
- ::google::protobuf::io::CodedOutputStream unknown_fields_stream(
- &unknown_fields_string, false);
+ io::CodedOutputStream unknown_fields_stream(&unknown_fields_string, false);
return extensions->ParseField(
tag, input, prototype, &unknown_fields_stream);
}
diff --git a/src/google/protobuf/generated_message_table_driven_lite.h b/src/google/protobuf/generated_message_table_driven_lite.h
index 0d90fe33..17e256a7 100644
--- a/src/google/protobuf/generated_message_table_driven_lite.h
+++ b/src/google/protobuf/generated_message_table_driven_lite.h
@@ -44,6 +44,8 @@
#include <type_traits>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -83,7 +85,7 @@ inline const Type* Raw(const MessageLite* msg, int64 offset) {
template <typename InternalMetadata>
inline Arena* GetArena(MessageLite* msg, int64 arena_offset) {
- if (GOOGLE_PREDICT_FALSE(arena_offset == -1)) {
+ if (PROTOBUF_PREDICT_FALSE(arena_offset == -1)) {
return NULL;
}
@@ -104,15 +106,14 @@ inline Type* AddField(MessageLite* msg, int64 offset) {
std::is_same<Type, InlinedStringField>::value,
"Do not assign");
- google::protobuf::RepeatedField<Type>* repeated =
- Raw<google::protobuf::RepeatedField<Type> >(msg, offset);
+ RepeatedField<Type>* repeated = Raw<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);
+inline std::string* AddField<std::string>(MessageLite* msg, int64 offset) {
+ RepeatedPtrField<std::string>* repeated =
+ Raw<RepeatedPtrField<std::string>>(msg, offset);
return repeated->Add();
}
@@ -168,7 +169,7 @@ inline void ClearOneofField(const ParseTableField& field, Arena* arena,
case WireFormatLite::TYPE_STRING:
case WireFormatLite::TYPE_BYTES:
Raw<ArenaStringPtr>(msg, field.offset)
- ->Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ ->Destroy(&GetEmptyStringAlreadyInited(), arena);
break;
case TYPE_STRING_INLINED:
@@ -206,11 +207,11 @@ inline void ResetOneofField(const ParseTable& table, int field_number,
switch (field_type) {
case ProcessingType_STRING:
Raw<ArenaStringPtr>(msg, offset)
- ->UnsafeSetDefault(static_cast<const string*>(default_ptr));
+ ->UnsafeSetDefault(static_cast<const std::string*>(default_ptr));
break;
case ProcessingType_INLINED:
new (Raw<InlinedStringField>(msg, offset))
- InlinedStringField(*static_cast<const string*>(default_ptr));
+ InlinedStringField(*static_cast<const std::string*>(default_ptr));
break;
case ProcessingType_MESSAGE:
MessageLite** submessage = Raw<MessageLite*>(msg, offset);
@@ -251,7 +252,7 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg,
GOOGLE_DCHECK(s != nullptr);
::std::string* value = s->MutableNoArena(NULL);
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
+ if (PROTOBUF_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
return false;
}
@@ -262,25 +263,25 @@ static inline bool HandleString(io::CodedInputStream* input, MessageLite* msg,
break;
}
case StringType_STRING: {
- string* value;
+ std::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);
+ ->Mutable(static_cast<const std::string*>(default_ptr), arena);
break;
case Cardinality_REPEATED:
- value = AddField<string>(msg, offset);
+ value = AddField<std::string>(msg, offset);
break;
case Cardinality_ONEOF:
value = Raw<ArenaStringPtr>(msg, offset)
- ->Mutable(static_cast<const string*>(default_ptr), arena);
+ ->Mutable(static_cast<const std::string*>(default_ptr), arena);
break;
}
GOOGLE_DCHECK(value != nullptr);
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
+ if (PROTOBUF_PREDICT_FALSE(!WireFormatLite::ReadString(input, value))) {
return false;
}
@@ -309,7 +310,7 @@ inline bool HandleEnum(const ParseTable& table, io::CodedInputStream* input,
uint32 presence_index, int64 offset, uint32 tag,
int field_number) {
int value;
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
input, &value)))) {
return false;
@@ -395,7 +396,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
continue;
}
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
!UnknownFieldHandler::Skip(msg, table, input, tag))) {
return false;
}
@@ -423,7 +424,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
#define HANDLE_TYPE(TYPE, CPPTYPE) \
case (WireFormatLite::TYPE_##TYPE): { \
CPPTYPE value; \
- if (GOOGLE_PREDICT_FALSE( \
+ if (PROTOBUF_PREDICT_FALSE( \
(!WireFormatLite::ReadPrimitive< \
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
return false; \
@@ -432,10 +433,9 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
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>( \
+ RepeatedField<CPPTYPE>* values = Raw<RepeatedField<CPPTYPE>>(msg, offset); \
+ if (PROTOBUF_PREDICT_FALSE((!WireFormatLite::ReadRepeatedPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>( \
data->tag_size, tag, input, values)))) { \
return false; \
} \
@@ -444,7 +444,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
case (WireFormatLite::TYPE_##TYPE) | kOneofMask: { \
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset); \
CPPTYPE value; \
- if (GOOGLE_PREDICT_FALSE( \
+ if (PROTOBUF_PREDICT_FALSE( \
(!WireFormatLite::ReadPrimitive< \
CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)))) { \
return false; \
@@ -482,7 +482,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
GetArena<InternalMetadata>(msg, table.arena_offset);
const void* default_ptr = table.aux[field_number].strings.default_ptr;
- if (GOOGLE_PREDICT_FALSE((
+ if (PROTOBUF_PREDICT_FALSE((
!HandleString<Cardinality_SINGULAR, false, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, NULL)))) {
@@ -499,8 +499,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
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_INLINED>(
+ if (PROTOBUF_PREDICT_FALSE((!HandleString<Cardinality_SINGULAR, false,
+ StringType_INLINED>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, NULL)))) {
return false;
@@ -521,7 +521,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
table, field_number, arena, msg, oneof_case + presence_index,
offset, default_ptr);
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleString<Cardinality_ONEOF, false, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, NULL)))) {
@@ -541,7 +541,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
const void* default_ptr =
table.aux[field_number].strings.default_ptr;
- if (GOOGLE_PREDICT_FALSE((
+ if (PROTOBUF_PREDICT_FALSE((
!HandleString<Cardinality_REPEATED, false, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, NULL)))) {
@@ -556,7 +556,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
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(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleString<Cardinality_SINGULAR, true, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, field_name)))) {
@@ -571,7 +571,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
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(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleString<Cardinality_REPEATED, true, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, field_name)))) {
@@ -590,7 +590,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
table, field_number, arena, msg, oneof_case + presence_index,
offset, default_ptr);
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleString<Cardinality_ONEOF, true, StringType_STRING>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, field_name)))) {
@@ -600,7 +600,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
#endif
case WireFormatLite::TYPE_ENUM: {
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleEnum<UnknownFieldHandler, InternalMetadata,
Cardinality_SINGULAR>(
table, input, msg, has_bits, presence_index, offset, tag,
@@ -610,7 +610,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
break;
}
case WireFormatLite::TYPE_ENUM | kRepeatedMask: {
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleEnum<UnknownFieldHandler, InternalMetadata,
Cardinality_REPEATED>(
table, input, msg, has_bits, presence_index, offset, tag,
@@ -621,7 +621,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
case WireFormatLite::TYPE_ENUM | kOneofMask: {
uint32* oneof_case = Raw<uint32>(msg, table.oneof_case_offset);
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
(!HandleEnum<UnknownFieldHandler, InternalMetadata,
Cardinality_ONEOF>(table, input, msg, oneof_case,
presence_index, offset, tag,
@@ -644,7 +644,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
*submsg_holder = submsg;
}
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
!WireFormatLite::ReadGroup(field_number, input, submsg))) {
return false;
}
@@ -660,7 +660,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
MessageLite* submsg =
MergePartialFromCodedStreamHelper::Add(field, prototype);
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
!WireFormatLite::ReadGroup(field_number, input, submsg))) {
return false;
}
@@ -678,14 +678,14 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
if (prototype == NULL) {
- prototype =
- ::google::protobuf::internal::ImplicitWeakMessage::default_instance();
+ prototype = ImplicitWeakMessage::default_instance();
}
submsg = prototype->New(arena);
*submsg_holder = submsg;
}
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ if (PROTOBUF_PREDICT_FALSE(
+ !WireFormatLite::ReadMessage(input, submsg))) {
return false;
}
@@ -698,14 +698,14 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
const MessageLite* prototype =
table.aux[field_number].messages.default_message();
if (prototype == NULL) {
- prototype =
- ::google::protobuf::internal::ImplicitWeakMessage::default_instance();
+ prototype = ImplicitWeakMessage::default_instance();
}
MessageLite* submsg =
MergePartialFromCodedStreamHelper::Add(field, prototype);
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ if (PROTOBUF_PREDICT_FALSE(
+ !WireFormatLite::ReadMessage(input, submsg))) {
return false;
}
@@ -721,7 +721,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
offset, NULL);
MessageLite* submsg = *submsg_holder;
- if (GOOGLE_PREDICT_FALSE(!WireFormatLite::ReadMessage(input, submsg))) {
+ if (PROTOBUF_PREDICT_FALSE(
+ !WireFormatLite::ReadMessage(input, submsg))) {
return false;
}
@@ -734,7 +735,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
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((
+ if (PROTOBUF_PREDICT_FALSE((
!HandleString<Cardinality_SINGULAR, true, StringType_INLINED>(
input, msg, arena, has_bits, presence_index, offset,
default_ptr, field_name)))) {
@@ -744,7 +745,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
case TYPE_MAP: {
- if (GOOGLE_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)(
+ if (PROTOBUF_PREDICT_FALSE(!(*table.aux[field_number].maps.parse_map)(
input, Raw<void>(msg, offset)))) {
return false;
}
@@ -772,16 +773,15 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
// 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; \
+#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case WireFormatLite::TYPE_##TYPE: { \
+ RepeatedField<CPPTYPE>* values = Raw<RepeatedField<CPPTYPE>>(msg, offset); \
+ if (PROTOBUF_PREDICT_FALSE( \
+ (!WireFormatLite::ReadPackedPrimitive< \
+ CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, values)))) { \
+ return false; \
+ } \
+ break; \
}
HANDLE_PACKED_TYPE(INT32, int32, Int32)
@@ -807,20 +807,19 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
// are valid, we implement our own parser rather than call
// WireFormat::ReadPackedEnumPreserveUnknowns.
uint32 length;
- if (GOOGLE_PREDICT_FALSE(!input->ReadVarint32(&length))) {
+ if (PROTOBUF_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);
+ RepeatedField<int>* values = Raw<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<
+ if (PROTOBUF_PREDICT_FALSE(
+ (!WireFormatLite::ReadPrimitive<
int, WireFormatLite::TYPE_ENUM>(input, &value)))) {
return false;
}
@@ -858,7 +857,7 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
}
// process unknown field.
- if (GOOGLE_PREDICT_FALSE(
+ if (PROTOBUF_PREDICT_FALSE(
!UnknownFieldHandler::Skip(msg, table, input, tag))) {
return false;
}
@@ -868,6 +867,8 @@ bool MergePartialFromCodedStreamImpl(MessageLite* msg, const ParseTable& table,
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#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 e0241361..ba8ec6d4 100644
--- a/src/google/protobuf/generated_message_util.cc
+++ b/src/google/protobuf/generated_message_util.cc
@@ -47,13 +47,14 @@
#include <google/protobuf/message_lite.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/stubs/mutex.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 {
+#include <google/protobuf/port_def.inc>
+
+namespace google {
namespace protobuf {
namespace internal {
@@ -62,14 +63,8 @@ void DestroyMessage(const void* message) {
}
void DestroyString(const void* s) { static_cast<const string*>(s)->~string(); }
-ExplicitlyConstructed<std::string> fixed_address_empty_string;
+ExplicitlyConstructed<::std::string> fixed_address_empty_string;
-double Infinity() {
- return std::numeric_limits<double>::infinity();
-}
-double NaN() {
- return std::numeric_limits<double>::quiet_NaN();
-}
static bool InitProtobufDefaultsImpl() {
fixed_address_empty_string.DefaultConstruct();
@@ -108,8 +103,7 @@ struct PrimitiveTypeHelper;
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_BOOL> {
typedef bool Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteBoolNoTag(Get<bool>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -120,8 +114,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_BOOL> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {
typedef int32 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteInt32NoTag(Get<int32>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -132,8 +125,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT32> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT32> {
typedef int32 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteSInt32NoTag(Get<int32>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -144,8 +136,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT32> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT32> {
typedef uint32 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteUInt32NoTag(Get<uint32>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -155,8 +146,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT32> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT64> {
typedef int64 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteInt64NoTag(Get<int64>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -167,8 +157,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_INT64> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT64> {
typedef int64 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteSInt64NoTag(Get<int64>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -178,8 +167,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_SINT64> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT64> {
typedef uint64 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteUInt64NoTag(Get<uint64>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -190,8 +178,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_UINT64> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
typedef uint32 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteFixed32NoTag(Get<uint32>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -202,8 +189,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED32> {
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_FIXED64> {
typedef uint64 Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
WireFormatLite::WriteFixed64NoTag(Get<uint64>(ptr), output);
}
static uint8* SerializeToArray(const void* ptr, uint8* buffer) {
@@ -239,8 +225,7 @@ struct PrimitiveTypeHelper<WireFormatLite::TYPE_DOUBLE>
template <>
struct PrimitiveTypeHelper<WireFormatLite::TYPE_STRING> {
typedef string Type;
- static void Serialize(const void* ptr,
- ::google::protobuf::io::CodedOutputStream* output) {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
const Type& value = *static_cast<const Type*>(ptr);
output->WriteVarint32(value.size());
output->WriteRawMaybeAliased(value.data(), value.size());
@@ -283,9 +268,8 @@ void WriteLengthTo(uint32 length, O* 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) {
+struct OutputHelper<io::CodedOutputStream, type> {
+ static void Serialize(const void* ptr, io::CodedOutputStream* output) {
PrimitiveTypeHelper<type>::Serialize(ptr, output);
}
};
@@ -304,7 +288,7 @@ struct OutputHelper<ArrayOutput, type> {
};
void SerializeMessageNoTable(const MessageLite* msg,
- ::google::protobuf::io::CodedOutputStream* output) {
+ io::CodedOutputStream* output) {
msg->SerializeWithCachedSizes(output);
}
@@ -314,10 +298,10 @@ void SerializeMessageNoTable(const MessageLite* msg, ArrayOutput* output) {
}
// Helper to branch to fast path if possible
-void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
+void SerializeMessageDispatch(const MessageLite& msg,
const FieldMetadata* field_table, int num_fields,
int32 cached_size,
- ::google::protobuf::io::CodedOutputStream* output) {
+ io::CodedOutputStream* output) {
const uint8* base = reinterpret_cast<const uint8*>(&msg);
// Try the fast path
uint8* ptr = output->GetDirectBufferForNBytesAndAdvance(cached_size);
@@ -332,7 +316,7 @@ void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
}
// Helper to branch to fast path if possible
-void SerializeMessageDispatch(const ::google::protobuf::MessageLite& msg,
+void SerializeMessageDispatch(const MessageLite& msg,
const FieldMetadata* field_table, int num_fields,
int32 cached_size, ArrayOutput* output) {
const uint8* base = reinterpret_cast<const uint8*>(&msg);
@@ -635,8 +619,7 @@ bool IsNull<FieldMetadata::kInlinedType>(const void* ptr) {
void SerializeInternal(const uint8* base,
const FieldMetadata* field_metadata_table,
- int32 num_fields,
- ::google::protobuf::io::CodedOutputStream* output) {
+ int32 num_fields, 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;
@@ -725,15 +708,14 @@ uint8* SerializeInternalToArray(const uint8* base,
#undef SERIALIZERS_FOR_TYPE
void ExtensionSerializer(const uint8* ptr, uint32 offset, uint32 tag,
- uint32 has_offset,
- ::google::protobuf::io::CodedOutputStream* output) {
+ uint32 has_offset, 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) {
+ io::CodedOutputStream* output) {
output->WriteString(
reinterpret_cast<const InternalMetadataWithArenaLite*>(ptr + offset)
->unknown_fields());
diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h
index 04f68a6e..b9bbb26b 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -46,15 +46,26 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/once.h> // Add direct dep on port for pb.cc
#include <google/protobuf/has_bits.h>
#include <google/protobuf/implicit_weak_message.h>
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/message_lite.h>
+#include <google/protobuf/stubs/once.h> // Add direct dep on port for pb.cc
+#include <google/protobuf/port.h>
#include <google/protobuf/wire_format_lite.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#if GOOGLE_PROTOBUF_ENABLE_MOMI_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
+
+
+namespace google {
namespace protobuf {
class Arena;
@@ -64,59 +75,15 @@ namespace io { class CodedInputStream; }
namespace internal {
-// Annotation for the compiler to emit a deprecation message if a field marked
-// with option 'deprecated=true' is used in the code, or for other things in
-// generated code which are deprecated.
-//
-// For internal use in the pb.cc files, deprecation warnings are suppressed
-// there.
-#undef DEPRECATED_PROTOBUF_FIELD
-#define PROTOBUF_DEPRECATED
-
-#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();
-
-LIBPROTOBUF_EXPORT void InitProtobufDefaults();
+PROTOBUF_EXPORT void InitProtobufDefaults();
// This used by proto1
-inline const std::string& GetEmptyString() {
+PROTOBUF_EXPORT inline const ::std::string& GetEmptyString() {
InitProtobufDefaults();
return GetEmptyStringAlreadyInited();
}
+
// 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
@@ -133,10 +100,10 @@ template <class Type> bool AllAreInitialized(const Type& t) {
// This version operates on MessageLite to avoid introducing a dependency on the
// concrete message type.
template <class T>
-bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField<T>& t) {
+bool AllAreInitializedWeak(const RepeatedPtrField<T>& t) {
for (int i = t.size(); --i >= 0;) {
- if (!reinterpret_cast<const ::google::protobuf::internal::RepeatedPtrFieldBase&>(t)
- .Get<::google::protobuf::internal::ImplicitWeakTypeHandler<T> >(i)
+ if (!reinterpret_cast<const RepeatedPtrFieldBase&>(t)
+ .Get<ImplicitWeakTypeHandler<T> >(i)
.IsInitialized()) {
return false;
}
@@ -144,7 +111,7 @@ bool AllAreInitializedWeak(const ::google::protobuf::RepeatedPtrField<T>& t) {
return true;
}
-struct LIBPROTOBUF_EXPORT FieldMetadata {
+struct PROTOBUF_EXPORT FieldMetadata {
uint32 offset; // offset of this field in the struct
uint32 tag; // field * 8 + wire_type
// byte offset * 8 + bit_offset;
@@ -191,26 +158,29 @@ inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) {
typedef void (*SpecialSerializer)(const uint8* base, uint32 offset, uint32 tag,
uint32 has_offset,
- ::google::protobuf::io::CodedOutputStream* output);
+ 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);
+PROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset,
+ uint32 tag, uint32 has_offset,
+ io::CodedOutputStream* output);
+PROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base,
+ uint32 offset, uint32 tag,
+ uint32 has_offset,
+ io::CodedOutputStream* output);
struct SerializationTable {
int num_fields;
const FieldMetadata* field_table;
};
-LIBPROTOBUF_EXPORT void SerializeInternal(const uint8* base, const FieldMetadata* table,
- int num_fields, ::google::protobuf::io::CodedOutputStream* output);
+PROTOBUF_EXPORT void SerializeInternal(const uint8* base,
+ const FieldMetadata* table,
+ int32 num_fields,
+ io::CodedOutputStream* output);
-inline void TableSerialize(const ::google::protobuf::MessageLite& msg,
+inline void TableSerialize(const MessageLite& msg,
const SerializationTable* table,
- ::google::protobuf::io::CodedOutputStream* output) {
+ 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);
@@ -224,10 +194,10 @@ inline void TableSerialize(const ::google::protobuf::MessageLite& msg,
}
uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table,
- int num_fields, bool is_deterministic,
+ int32 num_fields, bool is_deterministic,
uint8* buffer);
-inline uint8* TableSerializeToArray(const ::google::protobuf::MessageLite& msg,
+inline uint8* TableSerializeToArray(const MessageLite& msg,
const SerializationTable* table,
bool is_deterministic, uint8* buffer) {
const uint8* base = reinterpret_cast<const uint8*>(&msg);
@@ -262,8 +232,7 @@ struct CompareMapKey {
template <typename MapFieldType, const SerializationTable* table>
void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag,
- uint32 has_offset,
- ::google::protobuf::io::CodedOutputStream* output) {
+ uint32 has_offset, io::CodedOutputStream* output) {
typedef MapEntryHelper<typename MapFieldType::EntryTypeTrait> Entry;
typedef typename MapFieldType::MapType::const_iterator Iter;
@@ -297,10 +266,10 @@ void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag,
}
}
-LIBPROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message);
-LIBPROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena,
- MessageLite* submessage,
- Arena* submessage_arena);
+PROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message);
+PROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena,
+ MessageLite* submessage,
+ Arena* submessage_arena);
template <typename T>
T* DuplicateIfNonNull(T* message) {
@@ -322,7 +291,7 @@ T* GetOwnedMessage(Arena* message_arena, T* submessage,
// Hide atomic from the public header and allow easy change to regular int
// on platforms where the atomic might have a perf impact.
-class LIBPROTOBUF_EXPORT CachedSize {
+class PROTOBUF_EXPORT CachedSize {
public:
int Get() const { return size_.load(std::memory_order_relaxed); }
void Set(int size) { size_.store(size, std::memory_order_relaxed); }
@@ -332,7 +301,7 @@ class LIBPROTOBUF_EXPORT CachedSize {
// SCCInfo represents information of a strongly connected component of
// mutual dependent messages.
-struct LIBPROTOBUF_EXPORT SCCInfoBase {
+struct PROTOBUF_EXPORT SCCInfoBase {
// We use 0 for the Initialized state, because test eax,eax, jnz is smaller
// and is subject to macro fusion.
enum {
@@ -340,15 +309,15 @@ struct LIBPROTOBUF_EXPORT SCCInfoBase {
kRunning = 1,
kUninitialized = -1, // initial state
};
-#ifndef _MSC_VER
- std::atomic<int> visit_status;
-#else
+#if defined(_MSC_VER) && !defined(__clang__)
// MSVC doesnt make std::atomic constant initialized. This union trick
// makes it so.
union {
int visit_status_to_make_linker_init;
std::atomic<int> visit_status;
};
+#else
+ std::atomic<int> visit_status;
#endif
int num_deps;
void (*init_func)();
@@ -366,26 +335,29 @@ struct SCCInfo {
SCCInfoBase* deps[N ? N : 1];
};
-LIBPROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc);
+PROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc);
inline void InitSCC(SCCInfoBase* scc) {
auto status = scc->visit_status.load(std::memory_order_acquire);
- if (GOOGLE_PREDICT_FALSE(status != SCCInfoBase::kInitialized)) InitSCCImpl(scc);
+ if (PROTOBUF_PREDICT_FALSE(status != SCCInfoBase::kInitialized))
+ InitSCCImpl(scc);
}
-LIBPROTOBUF_EXPORT void DestroyMessage(const void* message);
-LIBPROTOBUF_EXPORT void DestroyString(const void* s);
+PROTOBUF_EXPORT void DestroyMessage(const void* message);
+PROTOBUF_EXPORT void DestroyString(const void* s);
// Destroy (not delete) the message
inline void OnShutdownDestroyMessage(const void* ptr) {
OnShutdownRun(DestroyMessage, ptr);
}
// Destroy the string (call string destructor)
-inline void OnShutdownDestroyString(const std::string* ptr) {
+inline void OnShutdownDestroyString(const ::std::string* ptr) {
OnShutdownRun(DestroyString, ptr);
}
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
diff --git a/src/google/protobuf/has_bits.h b/src/google/protobuf/has_bits.h
index e3a0149a..d15b3f8d 100644
--- a/src/google/protobuf/has_bits.h
+++ b/src/google/protobuf/has_bits.h
@@ -32,7 +32,13 @@
#define GOOGLE_PROTOBUF_HAS_BITS_H__
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
+
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
namespace google {
namespace protobuf {
@@ -41,18 +47,17 @@ namespace internal {
template<size_t doublewords>
class HasBits {
public:
- HasBits() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE { Clear(); }
+ HasBits() PROTOBUF_ALWAYS_INLINE { Clear(); }
- void Clear() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void Clear() PROTOBUF_ALWAYS_INLINE {
memset(has_bits_, 0, sizeof(has_bits_));
}
- ::google::protobuf::uint32& operator[](int index) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ::google::protobuf::uint32& operator[](int index) PROTOBUF_ALWAYS_INLINE {
return has_bits_[index];
}
- const ::google::protobuf::uint32& operator[](int index) const
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ const ::google::protobuf::uint32& operator[](int index) const PROTOBUF_ALWAYS_INLINE {
return has_bits_[index];
}
@@ -100,6 +105,8 @@ inline bool HasBits<doublewords>::empty() const {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_HAS_BITS_H__
diff --git a/src/google/protobuf/implicit_weak_message.cc b/src/google/protobuf/implicit_weak_message.cc
index 7a1d4446..582d7084 100644
--- a/src/google/protobuf/implicit_weak_message.cc
+++ b/src/google/protobuf/implicit_weak_message.cc
@@ -30,10 +30,15 @@
#include <google/protobuf/implicit_weak_message.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/stubs/once.h>
#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/port_def.inc>
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -44,17 +49,26 @@ bool ImplicitWeakMessage::MergePartialFromCodedStream(io::CodedInputStream* inpu
return WireFormatLite::SkipMessage(input, &coded_stream);
}
-::google::protobuf::internal::ExplicitlyConstructed<ImplicitWeakMessage>
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ImplicitWeakMessage::_InternalParse(const char* begin,
+ const char* end, void* object,
+ ParseContext* ctx) {
+ return internal::StringParser(
+ begin, end, &(static_cast<ImplicitWeakMessage*>(object)->data_), ctx);
+}
+#endif
+
+ExplicitlyConstructed<ImplicitWeakMessage>
implicit_weak_message_default_instance;
-GOOGLE_PROTOBUF_DECLARE_ONCE(implicit_weak_message_once_init_);
+internal::once_flag implicit_weak_message_once_init_;
void InitImplicitWeakMessageDefaultInstance() {
implicit_weak_message_default_instance.DefaultConstruct();
}
const ImplicitWeakMessage* ImplicitWeakMessage::default_instance() {
- ::google::protobuf::GoogleOnceInit(&implicit_weak_message_once_init_,
- &InitImplicitWeakMessageDefaultInstance);
+ internal::call_once(implicit_weak_message_once_init_,
+ InitImplicitWeakMessageDefaultInstance);
return &implicit_weak_message_default_instance.get();
}
diff --git a/src/google/protobuf/implicit_weak_message.h b/src/google/protobuf/implicit_weak_message.h
index 3279bd17..5d3b479a 100644
--- a/src/google/protobuf/implicit_weak_message.h
+++ b/src/google/protobuf/implicit_weak_message.h
@@ -31,10 +31,17 @@
#ifndef GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
#define GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
+#include <string>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/message_lite.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
// This file is logically internal-only and should only be used by protobuf
// generated code.
@@ -45,45 +52,52 @@ namespace internal {
// An implementation of MessageLite that treats all data as unknown. This type
// acts as a placeholder for an implicit weak field in the case where the true
// message type does not get linked into the binary.
-class LIBPROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
+class PROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
public:
ImplicitWeakMessage() : arena_(NULL) {}
explicit ImplicitWeakMessage(Arena* arena) : arena_(arena) {}
static const ImplicitWeakMessage* default_instance();
- string GetTypeName() const { return ""; }
+ std::string GetTypeName() const override { return ""; }
- MessageLite* New() const { return new ImplicitWeakMessage; }
- MessageLite* New(Arena* arena) const {
+ MessageLite* New() const override { return new ImplicitWeakMessage; }
+ MessageLite* New(Arena* arena) const override {
return Arena::CreateMessage<ImplicitWeakMessage>(arena);
}
- Arena* GetArena() const { return arena_; }
+ Arena* GetArena() const override { return arena_; }
- void Clear() { data_.clear(); }
+ void Clear() override { data_.clear(); }
- bool IsInitialized() const { return true; }
+ bool IsInitialized() const override { return true; }
- void CheckTypeAndMergeFrom(const MessageLite& other) {
+ void CheckTypeAndMergeFrom(const MessageLite& other) override {
data_.append(static_cast<const ImplicitWeakMessage&>(other).data_);
}
- bool MergePartialFromCodedStream(io::CodedInputStream* input);
+ bool MergePartialFromCodedStream(io::CodedInputStream* input) override;
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ ParseFunc _ParseFunc() const override { return _InternalParse; }
+
+ static const char* _InternalParse(const char* begin, const char* end,
+ void* object, ParseContext* ctx);
+#endif
- size_t ByteSizeLong() const { return data_.size(); }
+ size_t ByteSizeLong() const override { return data_.size(); }
- void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
+ void SerializeWithCachedSizes(io::CodedOutputStream* output) const override {
output->WriteString(data_);
}
- int GetCachedSize() const { return static_cast<int>(data_.size()); }
+ int GetCachedSize() const override { return static_cast<int>(data_.size()); }
typedef void InternalArenaConstructable_;
private:
Arena* const arena_;
- string data_;
+ std::string data_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage);
};
@@ -92,7 +106,7 @@ template <typename ImplicitWeakType>
class ImplicitWeakTypeHandler {
public:
typedef ImplicitWeakType Type;
- typedef ::google::protobuf::MessageLite WeakType;
+ typedef MessageLite WeakType;
static const bool Moveable = false;
// With implicit weak fields, we need separate NewFromPrototype and
@@ -100,27 +114,24 @@ class ImplicitWeakTypeHandler {
// strong dependency on the message type, and it just delegates to the
// GenericTypeHandler. The latter avoids creating a strong dependency, by
// simply calling MessageLite::New.
- static inline ::google::protobuf::MessageLite* NewFromPrototype(
- const ::google::protobuf::MessageLite* prototype, ::google::protobuf::Arena* arena = NULL) {
+ static inline MessageLite* NewFromPrototype(const MessageLite* prototype,
+ Arena* arena = NULL) {
return prototype->New(arena);
}
- static inline void Delete(::google::protobuf::MessageLite* value, Arena* arena) {
+ static inline void Delete(MessageLite* value, Arena* arena) {
if (arena == NULL) {
delete value;
}
}
- static inline ::google::protobuf::Arena* GetArena(::google::protobuf::MessageLite* value) {
+ static inline Arena* GetArena(MessageLite* value) {
return value->GetArena();
}
- static inline void* GetMaybeArenaPointer(::google::protobuf::MessageLite* value) {
+ static inline void* GetMaybeArenaPointer(MessageLite* value) {
return value->GetArena();
}
- static inline void Clear(::google::protobuf::MessageLite* value) {
- value->Clear();
- }
- static void Merge(const ::google::protobuf::MessageLite& from,
- ::google::protobuf::MessageLite* to) {
+ static inline void Clear(MessageLite* value) { value->Clear(); }
+ static void Merge(const MessageLite& from, MessageLite* to) {
to->CheckTypeAndMergeFrom(from);
}
static inline size_t SpaceUsedLong(const Type& value) {
@@ -130,6 +141,8 @@ class ImplicitWeakTypeHandler {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
diff --git a/src/google/protobuf/inlined_string_field.h b/src/google/protobuf/inlined_string_field.h
index 95d4687b..c5077b4b 100644
--- a/src/google/protobuf/inlined_string_field.h
+++ b/src/google/protobuf/inlined_string_field.h
@@ -32,10 +32,17 @@
#define GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__
#include <string>
+#include <utility>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
@@ -51,55 +58,49 @@ namespace internal {
// default_value parameters are taken for consistency with ArenaStringPtr, but
// are not used for most methods. With inlining, these should be removed from
// the generated binary.
-class LIBPROTOBUF_EXPORT InlinedStringField {
+class PROTOBUF_EXPORT InlinedStringField {
public:
- InlinedStringField()
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ InlinedStringField() PROTOBUF_ALWAYS_INLINE;
explicit InlinedStringField(const ::std::string& default_value);
void AssignWithDefault(const ::std::string* default_value,
- const InlinedStringField& from)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ const InlinedStringField& from) PROTOBUF_ALWAYS_INLINE;
- void ClearToEmpty(const ::std::string* default_value, Arena* arena)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void ClearToEmpty(const ::std::string* default_value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
ClearToEmptyNoArena(default_value);
}
- void ClearNonDefaultToEmpty() GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void ClearNonDefaultToEmpty() PROTOBUF_ALWAYS_INLINE {
ClearNonDefaultToEmptyNoArena();
}
void ClearToEmptyNoArena(const ::std::string* default_value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ PROTOBUF_ALWAYS_INLINE {
ClearNonDefaultToEmptyNoArena();
}
- void ClearNonDefaultToEmptyNoArena()
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ void ClearNonDefaultToEmptyNoArena() PROTOBUF_ALWAYS_INLINE;
- void ClearToDefault(const ::std::string* default_value, Arena* arena)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void ClearToDefault(const ::std::string* default_value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
ClearToDefaultNoArena(default_value);
}
void ClearToDefaultNoArena(const ::std::string* default_value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ PROTOBUF_ALWAYS_INLINE;
- void Destroy(const ::std::string* default_value, Arena* arena)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void Destroy(const ::std::string* default_value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
DestroyNoArena(default_value);
}
- void DestroyNoArena(const ::std::string* default_value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ void DestroyNoArena(const ::std::string* default_value) PROTOBUF_ALWAYS_INLINE;
- const ::std::string& Get() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
- return GetNoArena();
- }
- const ::std::string& GetNoArena() const GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ const ::std::string& Get() const PROTOBUF_ALWAYS_INLINE { return GetNoArena(); }
+ const ::std::string& GetNoArena() const PROTOBUF_ALWAYS_INLINE;
- ::std::string* Mutable(const ::std::string* default_value, Arena* arena)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ ::std::string* Mutable(const ::std::string* default_value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
return MutableNoArena(default_value);
}
::std::string* MutableNoArena(const ::std::string* default_value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ PROTOBUF_ALWAYS_INLINE;
::std::string* Release(const ::std::string* default_value, Arena* arena) {
return ReleaseNoArena(default_value);
@@ -112,37 +113,31 @@ class LIBPROTOBUF_EXPORT InlinedStringField {
}
::std::string* ReleaseNonDefaultNoArena(const ::std::string* default_value);
- void Set(const ::std::string* default_value,
- StringPiece value,
- Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void Set(const ::std::string* default_value, StringPiece value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
SetNoArena(default_value, value);
}
- void SetLite(const ::std::string* default_value,
- StringPiece value,
- Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void SetLite(const ::std::string* default_value, StringPiece value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
SetNoArena(default_value, value);
}
void SetNoArena(const ::std::string* default_value,
- StringPiece value) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ StringPiece value) PROTOBUF_ALWAYS_INLINE;
- void Set(const ::std::string* default_value,
- const ::std::string& value,
- Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void Set(const ::std::string* default_value, const ::std::string& value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
SetNoArena(default_value, value);
}
- void SetLite(const ::std::string* default_value,
- const ::std::string& value,
- Arena* arena) GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE {
+ void SetLite(const ::std::string* default_value, const ::std::string& value,
+ Arena* arena) PROTOBUF_ALWAYS_INLINE {
SetNoArena(default_value, value);
}
void SetNoArena(const ::std::string* default_value,
- const ::std::string& value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ const ::std::string& value) PROTOBUF_ALWAYS_INLINE;
#if LANG_CXX11
void SetNoArena(const ::std::string* default_value,
- ::std::string&& value)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ ::std::string&& value) PROTOBUF_ALWAYS_INLINE;
#endif
void SetAllocated(const ::std::string* default_value,
::std::string* value,
@@ -151,8 +146,7 @@ class LIBPROTOBUF_EXPORT InlinedStringField {
}
void SetAllocatedNoArena(const ::std::string* default_value,
::std::string* value);
- void Swap(InlinedStringField* from)
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE;
+ void Swap(InlinedStringField* from) PROTOBUF_ALWAYS_INLINE;
::std::string* UnsafeMutablePointer();
void UnsafeSetDefault(const ::std::string* default_value);
::std::string* UnsafeArenaRelease(const ::std::string* default_value, Arena* arena);
@@ -220,8 +214,8 @@ inline ::std::string* InlinedStringField::ReleaseNonDefaultNoArena(
return released;
}
-inline void InlinedStringField::SetNoArena(
- const ::std::string* default_value, StringPiece value) {
+inline void InlinedStringField::SetNoArena(const ::std::string* default_value,
+ StringPiece value) {
value_.assign(value.data(), value.length());
}
@@ -266,6 +260,8 @@ inline void InlinedStringField::UnsafeArenaSetAllocated(
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_INLINED_STRING_FIELD_H__
diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc
index 0851ff0c..547c5c64 100644
--- a/src/google/protobuf/io/coded_stream.cc
+++ b/src/google/protobuf/io/coded_stream.cc
@@ -49,6 +49,8 @@
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -121,7 +123,7 @@ CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) {
// security: byte_limit is possibly evil, so check for negative values
// 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 &&
+ if (PROTOBUF_PREDICT_TRUE(byte_limit >= 0 &&
byte_limit <= INT_MAX - current_position &&
byte_limit < current_limit_ - current_position)) {
current_limit_ = current_position + byte_limit;
@@ -191,7 +193,7 @@ void CodedInputStream::PrintTotalBytesLimitError() {
"big (more than " << total_bytes_limit_
<< " bytes). To increase the limit (or to disable these "
"warnings), see CodedInputStream::SetTotalBytesLimit() "
- "in google/protobuf/io/coded_stream.h.";
+ "in net/proto2/io/public/coded_stream.h.";
}
bool CodedInputStream::SkipFallback(int count, int original_buffer_size) {
@@ -312,11 +314,25 @@ bool CodedInputStream::ReadLittleEndian64Fallback(uint64* value) {
namespace {
+// Decodes varint64 with known size, N, and returns next pointer. Knowing N at
+// compile time, compiler can generate optimal code. For example, instead of
+// subtracting 0x80 at each iteration, it subtracts properly shifted mask once.
+template <size_t N>
+const uint8* DecodeVarint64KnownSize(const uint8* buffer, uint64* value) {
+ GOOGLE_DCHECK_GT(N, 0);
+ uint64 result = static_cast<uint64>(buffer[N - 1]) << (7 * (N - 1));
+ for (int i = 0, offset = 0; i < N - 1; i++, offset += 7) {
+ result += static_cast<uint64>(buffer[i] - 0x80) << offset;
+ }
+ *value = result;
+ return buffer + N;
+}
+
// Read a varint from the given buffer, write it to *value, and return a pair.
// 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+PROTOBUF_ALWAYS_INLINE
::std::pair<bool, const uint8*> ReadVarint32FromArray(
uint32 first_byte, const uint8* buffer,
uint32* value);
@@ -354,47 +370,39 @@ inline ::std::pair<bool, const uint8*> ReadVarint32FromArray(
return std::make_pair(true, ptr);
}
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE::std::pair<bool, const uint8*>
-ReadVarint64FromArray(const uint8* buffer, uint64* value);
+PROTOBUF_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;
- uint32 b;
-
- // Splitting into 32-bit pieces gives better performance on 32-bit
- // processors.
- uint32 part0 = 0, part1 = 0, part2 = 0;
-
- b = *(ptr++); part0 = b ; if (!(b & 0x80)) goto done;
- part0 -= 0x80;
- b = *(ptr++); part0 += b << 7; if (!(b & 0x80)) goto done;
- part0 -= 0x80 << 7;
- b = *(ptr++); part0 += b << 14; if (!(b & 0x80)) goto done;
- part0 -= 0x80 << 14;
- b = *(ptr++); part0 += b << 21; if (!(b & 0x80)) goto done;
- part0 -= 0x80 << 21;
- b = *(ptr++); part1 = b ; if (!(b & 0x80)) goto done;
- part1 -= 0x80;
- b = *(ptr++); part1 += b << 7; if (!(b & 0x80)) goto done;
- part1 -= 0x80 << 7;
- b = *(ptr++); part1 += b << 14; if (!(b & 0x80)) goto done;
- part1 -= 0x80 << 14;
- b = *(ptr++); part1 += b << 21; if (!(b & 0x80)) goto done;
- part1 -= 0x80 << 21;
- b = *(ptr++); part2 = b ; if (!(b & 0x80)) goto done;
- part2 -= 0x80;
- b = *(ptr++); part2 += b << 7; if (!(b & 0x80)) goto done;
- // "part2 -= 0x80 << 7" is irrelevant because (0x80 << 7) << 56 is 0.
-
- // We have overrun the maximum size of a varint (10 bytes). Assume
- // the data is corrupt.
- return std::make_pair(false, ptr);
+ // Assumes varint64 is at least 2 bytes.
+ GOOGLE_DCHECK_GE(buffer[0], 128);
+
+ const uint8* next;
+ if (buffer[1] < 128) {
+ next = DecodeVarint64KnownSize<2>(buffer, value);
+ } else if (buffer[2] < 128) {
+ next = DecodeVarint64KnownSize<3>(buffer, value);
+ } else if (buffer[3] < 128) {
+ next = DecodeVarint64KnownSize<4>(buffer, value);
+ } else if (buffer[4] < 128) {
+ next = DecodeVarint64KnownSize<5>(buffer, value);
+ } else if (buffer[5] < 128) {
+ next = DecodeVarint64KnownSize<6>(buffer, value);
+ } else if (buffer[6] < 128) {
+ next = DecodeVarint64KnownSize<7>(buffer, value);
+ } else if (buffer[7] < 128) {
+ next = DecodeVarint64KnownSize<8>(buffer, value);
+ } else if (buffer[8] < 128) {
+ next = DecodeVarint64KnownSize<9>(buffer, value);
+ } else if (buffer[9] < 128) {
+ next = DecodeVarint64KnownSize<10>(buffer, value);
+ } else {
+ // We have overrun the maximum size of a varint (10 bytes). Assume
+ // the data is corrupt.
+ return std::make_pair(false, buffer + 11);
+ }
- done:
- *value = (static_cast<uint64>(part0)) |
- (static_cast<uint64>(part1) << 28) |
- (static_cast<uint64>(part2) << 56);
- return std::make_pair(true, ptr);
+ return std::make_pair(true, next);
}
} // namespace
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h
index 0f70ecde..63631d1f 100644
--- a/src/google/protobuf/io/coded_stream.h
+++ b/src/google/protobuf/io/coded_stream.h
@@ -133,11 +133,17 @@
#endif
#endif
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/stubs/port.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include "util/coding/varint.h"
+#endif
+
+namespace google {
namespace protobuf {
class DescriptorPool;
@@ -155,6 +161,13 @@ class CodedOutputStream;
class ZeroCopyInputStream; // zero_copy_stream.h
class ZeroCopyOutputStream; // zero_copy_stream.h
+template <typename T>
+T UnalignedLoad(const void* p) {
+ T res;
+ memcpy(&res, p, sizeof(T));
+ return res;
+}
+
// Class which reads and decodes binary data which is composed of varint-
// encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream.
// Most users will not need to deal with CodedInputStream.
@@ -162,7 +175,7 @@ class ZeroCopyOutputStream; // zero_copy_stream.h
// Most methods of CodedInputStream that return a bool return false if an
// underlying I/O error occurs or if the data is malformed. Once such a
// failure occurs, the CodedInputStream is broken and is no longer useful.
-class LIBPROTOBUF_EXPORT CodedInputStream {
+class PROTOBUF_EXPORT CodedInputStream {
public:
// Create a CodedInputStream that reads from the given ZeroCopyInputStream.
explicit CodedInputStream(ZeroCopyInputStream* input);
@@ -198,7 +211,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Like GetDirectBufferPointer, but this method is inlined, and does not
// attempt to Refresh() if the buffer is currently empty.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ PROTOBUF_ALWAYS_INLINE
void GetDirectBufferPointerInline(const void** data, int* size);
// Read raw bytes, copying them into the given buffer.
@@ -206,15 +219,15 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Like the above, with inlined optimizations. This should only be used
// by the protobuf implementation.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ PROTOBUF_ALWAYS_INLINE
bool InternalReadRawInline(void* buffer, int size);
// Like ReadRaw, but reads into a string.
- bool ReadString(string* buffer, int size);
+ bool ReadString(std::string* buffer, int size);
// Like the above, with inlined optimizations. This should only be used
// by the protobuf implementation.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- bool InternalReadStringInline(string* buffer, int size);
+ PROTOBUF_ALWAYS_INLINE
+ bool InternalReadStringInline(std::string* buffer, int size);
// Read a 32-bit little-endian integer.
@@ -257,12 +270,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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTag() {
+ PROTOBUF_ALWAYS_INLINE uint32 ReadTag() {
return last_tag_ = ReadTagNoLastTag();
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE uint32 ReadTagNoLastTag();
-
+ PROTOBUF_ALWAYS_INLINE uint32 ReadTagNoLastTag();
// This usually a faster alternative to ReadTag() when cutoff is a manifest
// constant. It does particularly well for cutoff >= 127. The first part
@@ -272,14 +284,14 @@ 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ PROTOBUF_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
+ PROTOBUF_ALWAYS_INLINE
std::pair<uint32, bool> ReadTagWithCutoffNoLastTag(uint32 cutoff);
// Usually returns true if calling ReadVarint32() now would produce the given
@@ -289,7 +301,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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool ExpectTag(uint32 expected);
+ PROTOBUF_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
@@ -298,7 +310,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
//
// Returns a pointer beyond the expected tag if it was found, or NULL if it
// was not.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ PROTOBUF_ALWAYS_INLINE
static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected);
// Usually returns true if no more bytes can be read. Always returns false
@@ -328,6 +340,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// It also checks for some cases where, due to optimizations,
// MergeFromCodedStream() can incorrectly return true.
bool ConsumedEntireMessage();
+ void SetConsumed() { legitimate_message_end_ = true; }
// Limits ----------------------------------------------------------
// Limits are used when parsing length-delimited embedded messages.
@@ -384,7 +397,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// This is unrelated to PushLimit()/PopLimit().
void SetTotalBytesLimit(int total_bytes_limit);
- PROTOBUF_RUNTIME_DEPRECATED(
+ PROTOBUF_DEPRECATED_MSG(
"Please use the single parameter version of SetTotalBytesLimit(). The "
"second parameter is ignored.")
void SetTotalBytesLimit(int total_bytes_limit, int) {
@@ -403,6 +416,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// Sets the maximum recursion depth. The default is 100.
void SetRecursionLimit(int limit);
+ int RecursionBudget() { return recursion_budget_; }
// Increments the current recursion depth. Returns true if the depth is
@@ -621,7 +635,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// stream.
uint32 ReadTagFallback(uint32 first_byte_or_zero);
uint32 ReadTagSlow();
- bool ReadStringFallback(string* buffer, int size);
+ bool ReadStringFallback(std::string* buffer, int size);
// Return the size of the buffer.
int BufferSize() const;
@@ -677,7 +691,7 @@ class LIBPROTOBUF_EXPORT CodedInputStream {
// }
//
// delete coded_output;
-class LIBPROTOBUF_EXPORT CodedOutputStream {
+class PROTOBUF_EXPORT CodedOutputStream {
public:
// Create an CodedOutputStream that writes to the given ZeroCopyOutputStream.
explicit CodedOutputStream(ZeroCopyOutputStream* output);
@@ -731,11 +745,11 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
static uint8* WriteRawToArray(const void* buffer, int size, uint8* target);
// Equivalent to WriteRaw(str.data(), str.size()).
- void WriteString(const string& str);
+ void WriteString(const std::string& str);
// Like WriteString() but writing directly to the target array.
- static uint8* WriteStringToArray(const string& str, uint8* target);
+ static uint8* WriteStringToArray(const std::string& str, uint8* target);
// Write the varint-encoded size of str followed by str.
- static uint8* WriteStringWithSizeToArray(const string& str, uint8* target);
+ static uint8* WriteStringWithSizeToArray(const std::string& str, uint8* target);
// Instructs the CodedOutputStream to allow the underlying
@@ -782,7 +796,7 @@ 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+ PROTOBUF_ALWAYS_INLINE
static uint8* WriteTagToArray(uint32 value, uint8* target);
// Returns the number of bytes needed to encode the given value as a varint.
@@ -851,7 +865,8 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
}
static bool IsDefaultSerializationDeterministic() {
- return default_serialization_deterministic_.load(std::memory_order_relaxed) != 0;
+ return default_serialization_deterministic_.load(
+ std::memory_order_relaxed) != 0;
}
private:
@@ -889,7 +904,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
// 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();
+ friend void internal::MapTestForceDeterministic();
static void SetDefaultSerializationDeterministic() {
default_serialization_deterministic_.store(true, std::memory_order_relaxed);
}
@@ -901,7 +916,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
inline bool CodedInputStream::ReadVarint32(uint32* value) {
uint32 v = 0;
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
v = *buffer_;
if (v < 0x80) {
*value = v;
@@ -915,7 +930,7 @@ inline bool CodedInputStream::ReadVarint32(uint32* value) {
}
inline bool CodedInputStream::ReadVarint64(uint64* value) {
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) {
*value = *buffer_;
Advance(1);
return true;
@@ -926,7 +941,7 @@ inline bool CodedInputStream::ReadVarint64(uint64* value) {
}
inline bool CodedInputStream::ReadVarintSizeAsInt(int* value) {
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
int v = *buffer_;
if (v < 0x80) {
*value = v;
@@ -977,7 +992,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)))) {
+ if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
buffer_ = ReadLittleEndian32FromArray(buffer_, value);
return true;
} else {
@@ -990,7 +1005,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)))) {
+ if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) {
buffer_ = ReadLittleEndian64FromArray(buffer_, value);
return true;
} else {
@@ -1003,7 +1018,7 @@ inline bool CodedInputStream::ReadLittleEndian64(uint64* value) {
inline uint32 CodedInputStream::ReadTagNoLastTag() {
uint32 v = 0;
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
v = *buffer_;
if (v < 0x80) {
Advance(1);
@@ -1020,7 +1035,7 @@ inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
// constant, and things like "cutoff >= kMax1ByteVarint" to be evaluated at
// compile time.
uint32 first_byte_or_zero = 0;
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_)) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_)) {
// Hot case: buffer_ non_empty, buffer_[0] in [1, 128).
// TODO(gpike): Is it worth rearranging this? E.g., if the number of fields
// is large enough then is it better to check for the two-byte case first?
@@ -1034,8 +1049,8 @@ inline std::pair<uint32, bool> CodedInputStream::ReadTagWithCutoffNoLastTag(
// Other hot case: cutoff >= 0x80, buffer_ has at least two bytes available,
// and tag is two bytes. The latter is tested by bitwise-and-not of the
// first byte and the second byte.
- if (cutoff >= 0x80 && GOOGLE_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
- GOOGLE_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
+ if (cutoff >= 0x80 && PROTOBUF_PREDICT_TRUE(buffer_ + 1 < buffer_end_) &&
+ PROTOBUF_PREDICT_TRUE((buffer_[0] & ~buffer_[1]) >= 0x80)) {
const uint32 kMax2ByteVarint = (0x7f << 7) + 0x7f;
uint32 tag = (1u << 7) * buffer_[1] + (buffer_[0] - 0x80);
Advance(2);
@@ -1064,14 +1079,14 @@ inline bool CodedInputStream::ConsumedEntireMessage() {
inline bool CodedInputStream::ExpectTag(uint32 expected) {
if (expected < (1 << 7)) {
- if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) {
+ if (PROTOBUF_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) {
Advance(1);
return true;
} else {
return false;
}
} else if (expected < (1 << 14)) {
- if (GOOGLE_PREDICT_TRUE(BufferSize() >= 2) &&
+ if (PROTOBUF_PREDICT_TRUE(BufferSize() >= 2) &&
buffer_[0] == static_cast<uint8>(expected | 0x80) &&
buffer_[1] == static_cast<uint8>(expected >> 7)) {
Advance(2);
@@ -1262,7 +1277,7 @@ inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) {
}
}
-inline void CodedOutputStream::WriteString(const string& str) {
+inline void CodedOutputStream::WriteString(const std::string& str) {
WriteRaw(str.data(), static_cast<int>(str.size()));
}
@@ -1276,7 +1291,7 @@ inline void CodedOutputStream::WriteRawMaybeAliased(
}
inline uint8* CodedOutputStream::WriteStringToArray(
- const string& str, uint8* target) {
+ const std::string& str, uint8* target) {
return WriteRawToArray(str.data(), static_cast<int>(str.size()), target);
}
@@ -1390,11 +1405,13 @@ inline bool CodedInputStream::Skip(int count) {
} // namespace io
} // namespace protobuf
+} // namespace google
#if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
#pragma runtime_checks("c", restore)
#endif // _MSC_VER && !defined(__INTEL_COMPILER)
-} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
diff --git a/src/google/protobuf/io/coded_stream_inl.h b/src/google/protobuf/io/coded_stream_inl.h
index d95b06e0..df66282a 100644
--- a/src/google/protobuf/io/coded_stream_inl.h
+++ b/src/google/protobuf/io/coded_stream_inl.h
@@ -47,7 +47,7 @@ namespace google {
namespace protobuf {
namespace io {
-inline bool CodedInputStream::InternalReadStringInline(string* buffer,
+inline bool CodedInputStream::InternalReadStringInline(std::string* buffer,
int size) {
if (size < 0) return false; // security: size is often user-supplied
diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc
index 1c8d3272..52cc7c33 100644
--- a/src/google/protobuf/io/coded_stream_unittest.cc
+++ b/src/google/protobuf/io/coded_stream_unittest.cc
@@ -44,18 +44,20 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
-#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/stubs/casts.h>
+#include <google/protobuf/port_def.inc>
// This declares an unsigned long long integer literal in a portable way.
// (The original macro is way too big and ruins my formatting.)
#undef ULL
-#define ULL(x) GOOGLE_ULONGLONG(x)
+#define ULL(x) PROTOBUF_ULONGLONG(x)
-namespace google {
+namespace google {
namespace protobuf {
namespace io {
namespace {
diff --git a/src/google/protobuf/io/gzip_stream.h b/src/google/protobuf/io/gzip_stream.h
index df1a446e..b8eadfab 100644
--- a/src/google/protobuf/io/gzip_stream.h
+++ b/src/google/protobuf/io/gzip_stream.h
@@ -45,14 +45,17 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/port.h>
#include <zlib.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
// A ZeroCopyInputStream that reads compressed data through zlib
-class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream {
public:
// Format key for constructor
enum Format {
@@ -106,8 +109,7 @@ class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GzipInputStream);
};
-
-class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream {
public:
// Format key for constructor
enum Format {
@@ -118,7 +120,7 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream {
ZLIB = 2,
};
- struct LIBPROTOBUF_EXPORT Options {
+ struct PROTOBUF_EXPORT Options {
// Defaults to GZIP.
Format format;
@@ -204,6 +206,8 @@ class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream {
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__
diff --git a/src/google/protobuf/io/package_info.h b/src/google/protobuf/io/package_info.h
index dc1fc91e..46c3dac9 100644
--- a/src/google/protobuf/io/package_info.h
+++ b/src/google/protobuf/io/package_info.h
@@ -37,7 +37,6 @@
// documentation generator.
namespace google {
-
namespace protobuf {
// Auxiliary classes used for I/O.
diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc
index de67cef1..e988db80 100644
--- a/src/google/protobuf/io/printer.cc
+++ b/src/google/protobuf/io/printer.cc
@@ -32,6 +32,8 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
+#include <cctype>
+
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/logging.h>
@@ -178,123 +180,6 @@ void Printer::Print(const std::map<string, string>& variables,
WriteRaw(text + pos, size - pos);
}
-void Printer::Print(const char* text) {
- static std::map<string, string> empty;
- Print(empty, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable, const string& value) {
- std::map<string, string> vars;
- vars[variable] = value;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- vars[variable4] = value4;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- vars[variable4] = value4;
- vars[variable5] = value5;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- vars[variable4] = value4;
- vars[variable5] = value5;
- vars[variable6] = value6;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6,
- const char* variable7, const string& value7) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- vars[variable4] = value4;
- vars[variable5] = value5;
- vars[variable6] = value6;
- vars[variable7] = value7;
- Print(vars, text);
-}
-
-void Printer::Print(const char* text,
- const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6,
- const char* variable7, const string& value7,
- const char* variable8, const string& value8) {
- std::map<string, string> vars;
- vars[variable1] = value1;
- vars[variable2] = value2;
- vars[variable3] = value3;
- vars[variable4] = value4;
- vars[variable5] = value5;
- vars[variable6] = value6;
- vars[variable7] = value7;
- vars[variable8] = value8;
- Print(vars, text);
-}
-
void Printer::Indent() {
indent_ += " ";
}
@@ -343,6 +228,18 @@ void Printer::WriteRaw(const char* data, int size) {
CopyToBuffer(data, size);
}
+bool Printer::Next() {
+ do {
+ void* void_buffer;
+ if (!output_->Next(&void_buffer, &buffer_size_)) {
+ failed_ = true;
+ return false;
+ }
+ buffer_ = reinterpret_cast<char*>(void_buffer);
+ } while (buffer_size_ == 0);
+ return true;
+}
+
void Printer::CopyToBuffer(const char* data, int size) {
if (failed_) return;
if (size == 0) return;
@@ -369,6 +266,134 @@ void Printer::CopyToBuffer(const char* data, int size) {
offset_ += size;
}
+void Printer::IndentIfAtStart() {
+ if (at_start_of_line_) {
+ CopyToBuffer(indent_.data(), indent_.size());
+ at_start_of_line_ = false;
+ }
+}
+
+void Printer::FormatInternal(const std::vector<string>& args,
+ const std::map<string, string>& vars,
+ const char* format) {
+ auto save = format;
+ int arg_index = 0;
+ std::vector<AnnotationCollector::Annotation> annotations;
+ while (*format) {
+ char c = *format++;
+ switch (c) {
+ case '$':
+ format = WriteVariable(args, vars, format, &arg_index, &annotations);
+ continue;
+ case '\n':
+ at_start_of_line_ = true;
+ line_start_variables_.clear();
+ break;
+ default:
+ IndentIfAtStart();
+ break;
+ }
+ push_back(c);
+ }
+ if (arg_index != args.size()) {
+ GOOGLE_LOG(FATAL) << " Unused arguments. " << save;
+ }
+ if (!annotations.empty()) {
+ GOOGLE_LOG(FATAL) << " Annotation range is not-closed, expect $}$. " << save;
+ }
+}
+
+const char* Printer::WriteVariable(
+ const std::vector<string>& args, const std::map<string, string>& vars,
+ const char* format, int* arg_index,
+ std::vector<AnnotationCollector::Annotation>* annotations) {
+ auto start = format;
+ auto end = strchr(format, '$');
+ if (!end) {
+ GOOGLE_LOG(FATAL) << " Unclosed variable name.";
+ }
+ format = end + 1;
+ if (end == start) {
+ // "$$" is an escape for just '$'
+ IndentIfAtStart();
+ push_back('$');
+ return format;
+ }
+ if (*start == '{') {
+ GOOGLE_CHECK(std::isdigit(start[1]));
+ GOOGLE_CHECK_EQ(end - start, 2);
+ int idx = start[1] - '1';
+ if (idx < 0 || idx >= args.size()) {
+ GOOGLE_LOG(FATAL) << "Annotation ${" << idx + 1 << "$ is out of bounds.";
+ }
+ if (idx > *arg_index) {
+ GOOGLE_LOG(FATAL) << "Annotation arg must be in correct order as given. Expected"
+ << " ${" << (*arg_index) + 1 << "$ got ${" << idx + 1 << "$.";
+ } else if (idx == *arg_index) {
+ (*arg_index)++;
+ }
+ IndentIfAtStart();
+ annotations->push_back({{offset_, 0}, args[idx]});
+ return format;
+ } else if (*start == '}') {
+ GOOGLE_CHECK(annotations);
+ if (annotations->empty()) {
+ GOOGLE_LOG(FATAL) << "Unexpected end of annotation found.";
+ }
+ auto& a = annotations->back();
+ a.first.second = offset_;
+ if (annotation_collector_) annotation_collector_->AddAnnotationNew(a);
+ annotations->pop_back();
+ return format;
+ }
+ auto start_var = start;
+ while (start_var < end && *start_var == ' ') start_var++;
+ if (start_var == end) {
+ GOOGLE_LOG(FATAL) << " Empty variable.";
+ }
+ auto end_var = end;
+ while (start_var < end_var && *(end_var - 1) == ' ') end_var--;
+ string var_name{start_var,
+ static_cast<string::size_type>(end_var - start_var)};
+ string sub;
+ if (std::isdigit(var_name[0])) {
+ GOOGLE_CHECK_EQ(var_name.size(), 1); // No need for multi-digits
+ int idx = var_name[0] - '1'; // Start counting at 1
+ GOOGLE_CHECK_GE(idx, 0);
+ if (idx >= args.size()) {
+ GOOGLE_LOG(FATAL) << "Argument $" << idx + 1 << "$ is out of bounds.";
+ }
+ if (idx > *arg_index) {
+ GOOGLE_LOG(FATAL) << "Arguments must be used in same order as given. Expected $"
+ << (*arg_index) + 1 << "$ got $" << idx + 1 << "$.";
+ } else if (idx == *arg_index) {
+ (*arg_index)++;
+ }
+ sub = args[idx];
+ } else {
+ auto it = vars.find(var_name);
+ if (it == vars.end()) {
+ GOOGLE_LOG(FATAL) << " Unknown variable: " << var_name << ".";
+ }
+ sub = it->second;
+ }
+
+ // By returning here in case of empty we also skip possible spaces inside
+ // the $...$, i.e. "void$ dllexpor$ f();" -> "void f();" in the empty case.
+ if (sub.empty()) return format;
+
+ // We're going to write something non-empty so we need a possible indent.
+ IndentIfAtStart();
+
+ // Write the possible spaces in front.
+ CopyToBuffer(start, start_var - start);
+ // Write a non-empty substituted variable.
+ CopyToBuffer(sub.c_str(), sub.size());
+ // Finish off with writing possible trailing spaces.
+ CopyToBuffer(end_var, end - end_var);
+ return format;
+}
+
} // namespace io
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h
index d11745ce..ce693e54 100644
--- a/src/google/protobuf/io/printer.h
+++ b/src/google/protobuf/io/printer.h
@@ -42,6 +42,8 @@
#include <vector>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -49,14 +51,21 @@ namespace io {
class ZeroCopyOutputStream; // zero_copy_stream.h
// Records annotations about a Printer's output.
-class LIBPROTOBUF_EXPORT AnnotationCollector {
+class PROTOBUF_EXPORT AnnotationCollector {
public:
+ // Annotation is a ofset range and a payload pair.
+ typedef std::pair<std::pair<size_t, size_t>, std::string> Annotation;
+
// Records that the bytes in file_path beginning with begin_offset and ending
// before end_offset are associated with the SourceCodeInfo-style path.
virtual void AddAnnotation(size_t begin_offset, size_t end_offset,
- const string& file_path,
+ const std::string& file_path,
const std::vector<int>& path) = 0;
+ // TODO(gerbens) I don't see why we need virtuals here. Just a vector of
+ // range, payload pairs stored in a context should suffice.
+ virtual void AddAnnotationNew(Annotation& a) {}
+
virtual ~AnnotationCollector() {}
};
@@ -73,7 +82,7 @@ class AnnotationProtoCollector : public AnnotationCollector {
// Override for AnnotationCollector::AddAnnotation.
virtual void AddAnnotation(size_t begin_offset, size_t end_offset,
- const string& file_path,
+ const std::string& file_path,
const std::vector<int>& path) {
typename AnnotationProto::Annotation* annotation =
annotation_proto_->add_annotation();
@@ -84,6 +93,13 @@ class AnnotationProtoCollector : public AnnotationCollector {
annotation->set_begin(begin_offset);
annotation->set_end(end_offset);
}
+ // Override for AnnotationCollector::AddAnnotation.
+ virtual void AddAnnotationNew(Annotation& a) {
+ auto* annotation = annotation_proto_->add_annotation();
+ annotation->ParseFromString(a.second);
+ annotation->set_begin(a.first.first);
+ annotation->set_end(a.first.second);
+ }
private:
// The protocol buffer to which new annotations should be added.
@@ -162,7 +178,7 @@ class AnnotationProtoCollector : public AnnotationCollector {
// This code associates the span covering "call(bar,bar)" in the output with the
// call_ descriptor.
-class LIBPROTOBUF_EXPORT Printer {
+class PROTOBUF_EXPORT Printer {
public:
// Create a printer that writes text to the given output stream. Use the
// given character as the delimiter for variables.
@@ -203,7 +219,7 @@ class LIBPROTOBUF_EXPORT Printer {
// Link a subsitution variable emitted by the last call to Print to the file
// with path file_name.
- void Annotate(const char* varname, const string& file_name) {
+ void Annotate(const char* varname, const std::string& file_name) {
Annotate(varname, varname, file_name);
}
@@ -212,7 +228,7 @@ class LIBPROTOBUF_EXPORT Printer {
// at begin_varname's value and ends after the last character of the value
// substituted for end_varname.
void Annotate(const char* begin_varname, const char* end_varname,
- const string& file_name) {
+ const std::string& file_name) {
if (annotation_collector_ == NULL) {
// Annotations aren't turned on for this Printer.
return;
@@ -226,54 +242,14 @@ class LIBPROTOBUF_EXPORT Printer {
// substituted are identified by their names surrounded by delimiter
// characters (as given to the constructor). The variable bindings are
// defined by the given map.
- void Print(const std::map<string, string>& variables, const char* text);
+ void Print(const std::map<std::string, std::string>& variables, const char* text);
// Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable, const string& value);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6,
- const char* variable7, const string& value7);
- // Like the first Print(), except the substitutions are given as parameters.
- void Print(const char* text, const char* variable1, const string& value1,
- const char* variable2, const string& value2,
- const char* variable3, const string& value3,
- const char* variable4, const string& value4,
- const char* variable5, const string& value5,
- const char* variable6, const string& value6,
- const char* variable7, const string& value7,
- const char* variable8, const string& value8);
+ template <typename... Args>
+ void Print(const char* text, const Args&... args) {
+ std::map<std::string, std::string> vars;
+ PrintInternal(&vars, text, args...);
+ }
// 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
@@ -286,7 +262,7 @@ class LIBPROTOBUF_EXPORT Printer {
// Write a string to the output buffer.
// This method does not look for newlines to add indentation.
- void PrintRaw(const string& data);
+ void PrintRaw(const std::string& data);
// Write a zero-delimited string to output buffer.
// This method does not look for newlines to add indentation.
@@ -296,6 +272,14 @@ class LIBPROTOBUF_EXPORT Printer {
// This method does not look for newlines to add indentation.
void WriteRaw(const char* data, int size);
+ // FormatInternal is a helper function not meant to use directly, use
+ // compiler::cpp::Formatter instead. This function is meant to support
+ // formatting text using named variables (eq. "$foo$) from a lookup map (vars)
+ // and variables directly supplied by arguments (eq "$1$" meaning first
+ // argument which is the zero index element of args).
+ void FormatInternal(const std::vector<std::string>& args,
+ const std::map<std::string, std::string>& vars, const char* format);
+
// True if any write to the underlying stream failed. (We don't just
// crash in this case because this is an I/O failure, not a programming
// error.)
@@ -309,11 +293,42 @@ class LIBPROTOBUF_EXPORT Printer {
// substituted for end_varname. Note that begin_varname and end_varname
// may refer to the same variable.
void Annotate(const char* begin_varname, const char* end_varname,
- const string& file_path, const std::vector<int>& path);
+ const std::string& file_path, const std::vector<int>& path);
+
+ // Base case
+ void PrintInternal(std::map<std::string, std::string>* vars, const char* text) {
+ Print(*vars, text);
+ }
+
+ template <typename... Args>
+ void PrintInternal(std::map<std::string, std::string>* vars, const char* text,
+ const char* key, const std::string& value,
+ const Args&... args) {
+ (*vars)[key] = value;
+ PrintInternal(vars, text, args...);
+ }
// Copy size worth of bytes from data to buffer_.
void CopyToBuffer(const char* data, int size);
+ void push_back(char c) {
+ if (failed_) return;
+ if (buffer_size_ == 0) {
+ if (!Next()) return;
+ }
+ *buffer_++ = c;
+ buffer_size_--;
+ offset_++;
+ }
+
+ bool Next();
+
+ inline void IndentIfAtStart();
+ const char* WriteVariable(
+ const std::vector<std::string>& args, const std::map<std::string, std::string>& vars,
+ const char* format, int* arg_index,
+ std::vector<AnnotationCollector::Annotation>* annotations);
+
const char variable_delimiter_;
ZeroCopyOutputStream* const output_;
@@ -324,7 +339,7 @@ class LIBPROTOBUF_EXPORT Printer {
// used to calculate annotation ranges in the substitutions_ map below.
size_t offset_;
- string indent_;
+ std::string indent_;
bool at_start_of_line_;
bool failed_;
@@ -335,12 +350,12 @@ class LIBPROTOBUF_EXPORT Printer {
// start offset is the beginning of the substitution; the end offset is the
// last byte of the substitution plus one (such that (end - start) is the
// length of the substituted string).
- std::map<string, std::pair<size_t, size_t> > substitutions_;
+ std::map<std::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_;
+ std::vector<std::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
@@ -358,6 +373,8 @@ class LIBPROTOBUF_EXPORT Printer {
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_PRINTER_H__
diff --git a/src/google/protobuf/io/printer_unittest.cc b/src/google/protobuf/io/printer_unittest.cc
index d0a0ebee..fe46cee1 100644
--- a/src/google/protobuf/io/printer_unittest.cc
+++ b/src/google/protobuf/io/printer_unittest.cc
@@ -46,7 +46,6 @@
namespace google {
namespace protobuf {
namespace io {
-namespace {
// Each test repeats over several block sizes in order to test both cases
// where particular writes cross a buffer boundary and cases where they do
@@ -195,7 +194,7 @@ class MockDescriptor {
private:
// Allows access to GetLocationPath.
- friend class ::google::protobuf::io::Printer;
+ friend class Printer;
// Copies the pre-stored path to output.
void GetLocationPath(std::vector<int>* output) const { *output = path_; }
@@ -594,7 +593,136 @@ TEST(Printer, WriteFailureExact) {
EXPECT_EQ("0123456789abcdef", string(buffer, sizeof(buffer)));
}
-} // namespace
+TEST(Printer, FormatInternal) {
+ std::vector<string> args{"arg1", "arg2"};
+ std::map<string, string> vars{{"foo", "bar"}, {"baz", "bla"}, {"empty", ""}};
+ // Substitution tests
+ {
+ // Direct arg substitution
+ string s;
+ {
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ printer.FormatInternal(args, vars, "$1$ $2$");
+ }
+ EXPECT_EQ("arg1 arg2", s);
+ }
+ {
+ // Variable substitution including spaces left
+ string s;
+ {
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ printer.FormatInternal({}, vars, "$foo$$ baz$$ empty$");
+ }
+ EXPECT_EQ("bar bla", s);
+ }
+ {
+ // Variable substitution including spaces right
+ string s;
+ {
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ printer.FormatInternal({}, vars, "$empty $$foo $$baz$");
+ }
+ EXPECT_EQ("bar bla", s);
+ }
+ {
+ // Mixed variable substitution
+ string s;
+ {
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ printer.FormatInternal(args, vars, "$empty $$1$ $foo $$2$ $baz$");
+ }
+ EXPECT_EQ("arg1 bar arg2 bla", s);
+ }
+
+ // Indentation tests
+ {
+ // Empty lines shouldn't indent.
+ string s;
+ {
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ printer.Indent();
+ printer.FormatInternal(args, vars, "$empty $\n\n$1$ $foo $$2$\n$baz$");
+ printer.Outdent();
+ }
+ EXPECT_EQ("\n\n arg1 bar arg2\n bla", s);
+ }
+ {
+ // Annotations should respect indentation.
+ string s;
+ GeneratedCodeInfo info;
+ {
+ StringOutputStream output(&s);
+ AnnotationProtoCollector<GeneratedCodeInfo> info_collector(&info);
+ Printer printer(&output, '$', &info_collector);
+ printer.Indent();
+ GeneratedCodeInfo::Annotation annotation;
+ annotation.set_source_file("file.proto");
+ annotation.add_path(33);
+ std::vector<string> args{annotation.SerializeAsString(), "arg1", "arg2"};
+ printer.FormatInternal(args, vars, "$empty $\n\n${1$$2$$}$ $3$\n$baz$");
+ printer.Outdent();
+ }
+ EXPECT_EQ("\n\n arg1 arg2\n bla", s);
+ ASSERT_EQ(1, info.annotation_size());
+ const GeneratedCodeInfo::Annotation* arg1 = &info.annotation(0);
+ ASSERT_EQ(1, arg1->path_size());
+ EXPECT_EQ(33, arg1->path(0));
+ EXPECT_EQ("file.proto", arg1->source_file());
+ EXPECT_EQ(4, arg1->begin());
+ EXPECT_EQ(8, arg1->end());
+ }
+#ifdef PROTOBUF_HAS_DEATH_TEST
+ // Death tests in case of illegal format strings.
+ {
+ // Unused arguments
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal(args, vars, "$empty $$1$"), "Unused");
+ }
+ {
+ // Wrong order arguments
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal(args, vars, "$2$ $1$"), "order");
+ }
+ {
+ // Zero is illegal argument
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal(args, vars, "$0$"), "failed");
+ }
+ {
+ // Argument out of bounds
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal(args, vars, "$1$ $2$ $3$"), "bounds");
+ }
+ {
+ // Unknown variable
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal(args, vars, "$huh$ $1$$2$"), "Unknown");
+ }
+ {
+ // Illegal variable
+ string s;
+ StringOutputStream output(&s);
+ Printer printer(&output, '$');
+ EXPECT_DEATH(printer.FormatInternal({}, vars, "$ $"), "Empty");
+ }
+#endif // PROTOBUF_HAS_DEATH_TEST
+}
+
} // namespace io
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/io/strtod.h b/src/google/protobuf/io/strtod.h
index f56e41c8..38f544af 100644
--- a/src/google/protobuf/io/strtod.h
+++ b/src/google/protobuf/io/strtod.h
@@ -50,6 +50,6 @@ float SafeDoubleToFloat(double value);
} // namespace io
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_IO_STRTOD_H__
diff --git a/src/google/protobuf/io/tokenizer.h b/src/google/protobuf/io/tokenizer.h
index e80d564c..f6c3d273 100644
--- a/src/google/protobuf/io/tokenizer.h
+++ b/src/google/protobuf/io/tokenizer.h
@@ -42,6 +42,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -61,7 +63,7 @@ typedef int ColumnNumber;
// Abstract interface for an object which collects the errors that occur
// during parsing. A typical implementation might simply print the errors
// to stdout.
-class LIBPROTOBUF_EXPORT ErrorCollector {
+class PROTOBUF_EXPORT ErrorCollector {
public:
inline ErrorCollector() {}
virtual ~ErrorCollector();
@@ -70,13 +72,13 @@ class LIBPROTOBUF_EXPORT ErrorCollector {
// column numbers. The numbers are zero-based, so you may want to add
// 1 to each before printing them.
virtual void AddError(int line, ColumnNumber column,
- const string& message) = 0;
+ const std::string& message) = 0;
// Indicates that there was a warning in the input at the given line and
// column numbers. The numbers are zero-based, so you may want to add
// 1 to each before printing them.
virtual void AddWarning(int line, ColumnNumber column,
- const string& message) { }
+ const std::string& message) { }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector);
@@ -88,7 +90,7 @@ class LIBPROTOBUF_EXPORT ErrorCollector {
// precise descriptions. Whitespace and comments are skipped. By default,
// C- and C++-style comments are recognized, but other styles can be used by
// calling set_comment_style().
-class LIBPROTOBUF_EXPORT Tokenizer {
+class PROTOBUF_EXPORT Tokenizer {
public:
// Construct a Tokenizer that reads and tokenizes text from the given
// input stream and writes errors to the given error_collector.
@@ -124,7 +126,7 @@ class LIBPROTOBUF_EXPORT Tokenizer {
// Structure representing a token read from the token stream.
struct Token {
TokenType type;
- string text; // The exact text of the token as it appeared in
+ std::string text; // The exact text of the token as it appeared in
// the input. e.g. tokens of TYPE_STRING will still
// be escaped and in quotes.
@@ -190,31 +192,31 @@ class LIBPROTOBUF_EXPORT Tokenizer {
// /* Block comment attached to
// * grault. */
// optional int32 grault = 6;
- bool NextWithComments(string* prev_trailing_comments,
- std::vector<string>* detached_comments,
- string* next_leading_comments);
+ bool NextWithComments(std::string* prev_trailing_comments,
+ std::vector<std::string>* detached_comments,
+ std::string* next_leading_comments);
// Parse helpers ---------------------------------------------------
// Parses a TYPE_FLOAT token. This never fails, so long as the text actually
// comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the
// result is undefined (possibly an assert failure).
- static double ParseFloat(const string& text);
+ static double ParseFloat(const std::string& text);
// Parses a TYPE_STRING token. This never fails, so long as the text actually
// comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the
// result is undefined (possibly an assert failure).
- static void ParseString(const string& text, string* output);
+ static void ParseString(const std::string& text, std::string* output);
// Identical to ParseString, but appends to output.
- static void ParseStringAppend(const string& text, string* output);
+ static void ParseStringAppend(const std::string& text, std::string* output);
// Parses a TYPE_INTEGER token. Returns false if the result would be
// greater than max_value. Otherwise, returns true and sets *output to the
// result. If the text is not from a Token of type TYPE_INTEGER originally
// parsed by a Tokenizer, the result is undefined (possibly an assert
// failure).
- static bool ParseInteger(const string& text, uint64 max_value,
+ static bool ParseInteger(const std::string& text, uint64 max_value,
uint64* output);
// Options ---------------------------------------------------------
@@ -250,7 +252,7 @@ class LIBPROTOBUF_EXPORT Tokenizer {
}
// External helper: validate an identifier.
- static bool IsIdentifier(const string& text);
+ static bool IsIdentifier(const std::string& text);
// -----------------------------------------------------------------
private:
@@ -276,7 +278,7 @@ class LIBPROTOBUF_EXPORT Tokenizer {
// Call RecordTo(&str) to start recording and StopRecording() to stop.
// E.g. StartToken() calls RecordTo(&current_.text). record_start_ is the
// position within the current buffer where recording started.
- string* record_target_;
+ std::string* record_target_;
int record_start_;
// Options.
@@ -299,7 +301,7 @@ class LIBPROTOBUF_EXPORT Tokenizer {
// Read a new buffer from the input.
void Refresh();
- inline void RecordTo(string* target);
+ inline void RecordTo(std::string* target);
inline void StopRecording();
// Called when the current character is the first character of a new
@@ -311,7 +313,7 @@ class LIBPROTOBUF_EXPORT Tokenizer {
inline void EndToken();
// Convenience method to add an error at the current line and column.
- void AddError(const string& message) {
+ void AddError(const std::string& message) {
error_collector_->AddError(line_, column_, message);
}
@@ -334,9 +336,9 @@ class LIBPROTOBUF_EXPORT Tokenizer {
TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot);
// Consume the rest of a line.
- void ConsumeLineComment(string* content);
+ void ConsumeLineComment(std::string* content);
// Consume until "*/".
- void ConsumeBlockComment(string* content);
+ void ConsumeBlockComment(std::string* content);
enum NextCommentStatus {
// Started a line comment.
@@ -399,13 +401,15 @@ inline const Tokenizer::Token& Tokenizer::previous() {
return previous_;
}
-inline void Tokenizer::ParseString(const string& text, string* output) {
+inline void Tokenizer::ParseString(const std::string& text, std::string* output) {
output->clear();
ParseStringAppend(text, output);
}
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__
diff --git a/src/google/protobuf/io/zero_copy_stream.h b/src/google/protobuf/io/zero_copy_stream.h
index 62ace7ae..de2374b5 100644
--- a/src/google/protobuf/io/zero_copy_stream.h
+++ b/src/google/protobuf/io/zero_copy_stream.h
@@ -110,8 +110,10 @@
#include <string>
#include <google/protobuf/stubs/common.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
+namespace google {
namespace protobuf {
namespace io {
@@ -121,7 +123,7 @@ class ZeroCopyOutputStream;
// Abstract interface similar to an input stream but designed to minimize
// copying.
-class LIBPROTOBUF_EXPORT ZeroCopyInputStream {
+class PROTOBUF_EXPORT ZeroCopyInputStream {
public:
ZeroCopyInputStream() {}
virtual ~ZeroCopyInputStream() {}
@@ -178,7 +180,7 @@ class LIBPROTOBUF_EXPORT ZeroCopyInputStream {
// Abstract interface similar to an output stream but designed to minimize
// copying.
-class LIBPROTOBUF_EXPORT ZeroCopyOutputStream {
+class PROTOBUF_EXPORT ZeroCopyOutputStream {
public:
ZeroCopyOutputStream() {}
virtual ~ZeroCopyOutputStream() {}
@@ -243,6 +245,8 @@ class LIBPROTOBUF_EXPORT ZeroCopyOutputStream {
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h
index ea978bfb..46062a85 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl.h
@@ -47,6 +47,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -60,7 +62,7 @@ namespace io {
// The latter will introduce an extra layer of buffering, harming performance.
// Also, it's conceivable that FileInputStream could someday be enhanced
// to use zero-copy file descriptors on OSs which support them.
-class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given Unix file descriptor.
// If a block_size is given, it specifies the number of bytes that
@@ -87,24 +89,24 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
int GetErrno() { return copying_input_.GetErrno(); }
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
- class LIBPROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream {
+ class PROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream {
public:
CopyingFileInputStream(int file_descriptor);
- ~CopyingFileInputStream();
+ ~CopyingFileInputStream() override;
bool Close();
void SetCloseOnDelete(bool value) { close_on_delete_ = value; }
int GetErrno() { return errno_; }
// implements CopyingInputStream ---------------------------------
- int Read(void* buffer, int size);
- int Skip(int count);
+ int Read(void* buffer, int size) override;
+ int Skip(int count) override;
private:
// The file descriptor.
@@ -137,14 +139,14 @@ class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
// harming performance. Also, it's conceivable that FileOutputStream could
// someday be enhanced to use zero-copy file descriptors on OSs which
// support them.
-class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream {
public:
// Creates a stream that writes to the given Unix file descriptor.
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
explicit FileOutputStream(int file_descriptor, int block_size = -1);
- ~FileOutputStream();
+ ~FileOutputStream() override;
// Flushes any buffers and closes the underlying file. Returns false if
// an error occurs during the process; use GetErrno() to examine the error.
@@ -170,22 +172,22 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream {
int GetErrno() { return copying_output_.GetErrno(); }
// implements ZeroCopyOutputStream ---------------------------------
- bool Next(void** data, int* size);
- void BackUp(int count);
- int64 ByteCount() const;
+ bool Next(void** data, int* size) override;
+ void BackUp(int count) override;
+ int64 ByteCount() const override;
private:
- class LIBPROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream {
+ class PROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream {
public:
CopyingFileOutputStream(int file_descriptor);
- ~CopyingFileOutputStream();
+ ~CopyingFileOutputStream() override;
bool Close();
void SetCloseOnDelete(bool value) { close_on_delete_ = value; }
int GetErrno() { return errno_; }
// implements CopyingOutputStream --------------------------------
- bool Write(const void* buffer, int size);
+ bool Write(const void* buffer, int size) override;
private:
// The file descriptor.
@@ -211,7 +213,7 @@ class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream {
//
// Note that for reading files (or anything represented by a file descriptor),
// FileInputStream is more efficient.
-class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given C++ istream.
// If a block_size is given, it specifies the number of bytes that
@@ -220,19 +222,19 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
explicit IstreamInputStream(std::istream* stream, int block_size = -1);
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
- class LIBPROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream {
+ class PROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream {
public:
CopyingIstreamInputStream(std::istream* input);
- ~CopyingIstreamInputStream();
+ ~CopyingIstreamInputStream() override;
// implements CopyingInputStream ---------------------------------
- int Read(void* buffer, int size);
+ int Read(void* buffer, int size) override;
// (We use the default implementation of Skip().)
private:
@@ -254,28 +256,29 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
//
// Note that for writing files (or anything represented by a file descriptor),
// FileOutputStream is more efficient.
-class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
public:
// Creates a stream that writes to the given C++ ostream.
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
explicit OstreamOutputStream(std::ostream* stream, int block_size = -1);
- ~OstreamOutputStream();
+ ~OstreamOutputStream() override;
// implements ZeroCopyOutputStream ---------------------------------
- bool Next(void** data, int* size);
- void BackUp(int count);
- int64 ByteCount() const;
+ bool Next(void** data, int* size) override;
+ void BackUp(int count) override;
+ int64 ByteCount() const override;
private:
- class LIBPROTOBUF_EXPORT CopyingOstreamOutputStream : public CopyingOutputStream {
+ class PROTOBUF_EXPORT CopyingOstreamOutputStream
+ : public CopyingOutputStream {
public:
CopyingOstreamOutputStream(std::ostream* output);
- ~CopyingOstreamOutputStream();
+ ~CopyingOstreamOutputStream() override;
// implements CopyingOutputStream --------------------------------
- bool Write(const void* buffer, int size);
+ bool Write(const void* buffer, int size) override;
private:
// The stream.
@@ -299,17 +302,18 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
// ConcatenatingInputStream may do odd things. It is suggested that you do
// not use ConcatenatingInputStream on streams that might produce read errors
// other than end-of-stream.
-class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
public:
// 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() override = default;
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
@@ -326,16 +330,16 @@ class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
// A ZeroCopyInputStream which wraps some other stream and limits it to
// a particular byte count.
-class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream {
public:
LimitingInputStream(ZeroCopyInputStream* input, int64 limit);
- ~LimitingInputStream();
+ ~LimitingInputStream() override;
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
@@ -350,6 +354,8 @@ class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream {
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__
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 66ad49bc..7d7b689b 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.cc
@@ -37,9 +37,9 @@
#include <algorithm>
#include <limits>
-#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/stl_util.h>
namespace google {
@@ -200,8 +200,8 @@ int CopyingInputStream::Skip(int count) {
char junk[4096];
int skipped = 0;
while (skipped < count) {
- int bytes =
- Read(junk, std::min(count - skipped, implicit_cast<int>(sizeof(junk))));
+ int bytes = Read(junk, std::min(count - skipped,
+ ::google::protobuf::implicit_cast<int>(sizeof(junk))));
if (bytes <= 0) {
// EOF or read error.
return skipped;
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 29f63bf0..07d18849 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl_lite.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl_lite.h
@@ -53,6 +53,8 @@
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -60,7 +62,7 @@ namespace io {
// ===================================================================
// A ZeroCopyInputStream backed by an in-memory array of bytes.
-class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
public:
// Create an InputStream that returns the bytes pointed to by "data".
// "data" remains the property of the caller but must remain valid until
@@ -70,12 +72,13 @@ 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() override = default;
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
@@ -93,7 +96,7 @@ class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
// ===================================================================
// A ZeroCopyOutputStream backed by an in-memory array of bytes.
-class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
public:
// Create an OutputStream that writes to the bytes pointed to by "data".
// "data" remains the property of the caller but must remain valid until
@@ -103,11 +106,12 @@ 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() override = default;
// implements ZeroCopyOutputStream ---------------------------------
- bool Next(void** data, int* size);
- void BackUp(int count);
- int64 ByteCount() const;
+ bool Next(void** data, int* size) override;
+ void BackUp(int count) override;
+ int64 ByteCount() const override;
private:
uint8* const data_; // The byte array.
@@ -124,7 +128,7 @@ class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
// ===================================================================
// A ZeroCopyOutputStream which appends bytes to a string.
-class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
public:
// Create a StringOutputStream which appends bytes to the given string.
// The string remains property of the caller, but it is mutated in arbitrary
@@ -135,20 +139,21 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
// Hint: If you call target->reserve(n) before creating the stream,
// the first call to Next() will return at least n bytes of buffer
// space.
- explicit StringOutputStream(string* target);
+ explicit StringOutputStream(std::string* target);
+ ~StringOutputStream() override = default;
// implements ZeroCopyOutputStream ---------------------------------
- bool Next(void** data, int* size);
- void BackUp(int count);
- int64 ByteCount() const;
+ bool Next(void** data, int* size) override;
+ void BackUp(int count) override;
+ int64 ByteCount() const override;
protected:
- void SetString(string* target);
+ void SetString(std::string* target);
private:
static const int kMinimumSize = 16;
- string* target_;
+ std::string* target_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream);
};
@@ -170,7 +175,7 @@ class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
// CopyingInputStream implementations should avoid buffering if possible.
// CopyingInputStreamAdaptor does its own buffering and will read data
// in large blocks.
-class LIBPROTOBUF_EXPORT CopyingInputStream {
+class PROTOBUF_EXPORT CopyingInputStream {
public:
virtual ~CopyingInputStream() {}
@@ -196,7 +201,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStream {
// If you want to read from file descriptors or C++ istreams, this is
// already implemented for you: use FileInputStream or IstreamInputStream
// respectively.
-class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream {
+class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given CopyingInputStream.
// If a block_size is given, it specifies the number of bytes that
@@ -205,17 +210,17 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream
// copying_stream unless SetOwnsCopyingStream(true) is called.
explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream,
int block_size = -1);
- ~CopyingInputStreamAdaptor();
+ ~CopyingInputStreamAdaptor() override;
// Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to
// delete the underlying CopyingInputStream when it is destroyed.
void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
// implements ZeroCopyInputStream ----------------------------------
- bool Next(const void** data, int* size);
- void BackUp(int count);
- bool Skip(int count);
- int64 ByteCount() const;
+ bool Next(const void** data, int* size) override;
+ void BackUp(int count) override;
+ bool Skip(int count) override;
+ int64 ByteCount() const override;
private:
// Insures that buffer_ is not NULL.
@@ -264,7 +269,7 @@ class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream
// CopyingOutputStream implementations should avoid buffering if possible.
// CopyingOutputStreamAdaptor does its own buffering and will write data
// in large blocks.
-class LIBPROTOBUF_EXPORT CopyingOutputStream {
+class PROTOBUF_EXPORT CopyingOutputStream {
public:
virtual ~CopyingOutputStream() {}
@@ -280,7 +285,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStream {
// If you want to write to file descriptors or C++ ostreams, this is
// already implemented for you: use FileOutputStream or OstreamOutputStream
// respectively.
-class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream {
+class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream {
public:
// Creates a stream that writes to the given Unix file descriptor.
// If a block_size is given, it specifies the size of the buffers
@@ -288,7 +293,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea
// is used.
explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream,
int block_size = -1);
- ~CopyingOutputStreamAdaptor();
+ ~CopyingOutputStreamAdaptor() override;
// Writes all pending data to the underlying stream. Returns false if a
// write error occurred on the underlying stream. (The underlying
@@ -300,9 +305,9 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea
void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
// implements ZeroCopyOutputStream ---------------------------------
- bool Next(void** data, int* size);
- void BackUp(int count);
- int64 ByteCount() const;
+ bool Next(void** data, int* size) override;
+ void BackUp(int count) override;
+ int64 ByteCount() const override;
private:
// Write the current buffer, if it is present.
@@ -353,7 +358,7 @@ class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStrea
// Return a pointer to mutable characters underlying the given string. The
// return value is valid until the next time the string is resized. We
// trust the caller to treat the return value as an array of length s->size().
-inline char* mutable_string_data(string* s) {
+inline char* mutable_string_data(std::string* s) {
#ifdef LANG_CXX11
// This should be simpler & faster than string_as_array() because the latter
// is guaranteed to return NULL when *s is empty, so it has to check for that.
@@ -367,7 +372,7 @@ inline char* mutable_string_data(string* s) {
// ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); })
// Sometimes it's faster: in some scenarios p cannot be NULL, and then the
// code can avoid that check.
-inline std::pair<char*, bool> as_string_data(string* s) {
+inline std::pair<char*, bool> as_string_data(std::string* s) {
char *p = mutable_string_data(s);
#ifdef LANG_CXX11
return std::make_pair(p, true);
@@ -378,6 +383,8 @@ inline std::pair<char*, bool> as_string_data(string* s) {
} // namespace io
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc
index 08de8cb1..48132064 100644
--- a/src/google/protobuf/io/zero_copy_stream_unittest.cc
+++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc
@@ -59,6 +59,7 @@
#include <sstream>
#include <google/protobuf/testing/file.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -566,11 +567,10 @@ string IoTest::Uncompress(const string& data) {
TEST_F(IoTest, CompressionOptions) {
// Some ad-hoc testing of compression options.
+ string golden_filename =
+ TestUtil::GetTestDataPath("net/proto2/internal/testdata/golden_message");
string golden;
- GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() +
- "/google/protobuf/testdata/golden_message",
- &golden, true));
+ GOOGLE_CHECK_OK(File::GetContents(golden_filename, &golden, true));
GzipOutputStream::Options options;
string gzip_compressed = Compress(golden, options);
diff --git a/src/google/protobuf/lite_arena_unittest.cc b/src/google/protobuf/lite_arena_unittest.cc
index 3e88314d..df88d2cc 100644
--- a/src/google/protobuf/lite_arena_unittest.cc
+++ b/src/google/protobuf/lite_arena_unittest.cc
@@ -45,7 +45,7 @@ class LiteArenaTest : public testing::Test {
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);
+ Arena::CreateArray<char>(arena_.get(), 1);
}
std::unique_ptr<Arena> arena_;
@@ -58,23 +58,23 @@ TEST_F(LiteArenaTest, MapNoHeapAllocation) {
{
// TODO(teboring): Enable no heap check when ArenaStringPtr is used in
// Map.
- // google::protobuf::internal::NoHeapChecker no_heap;
+ // internal::NoHeapChecker no_heap;
protobuf_unittest::TestArenaMapLite* from =
Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(arena_.get());
- google::protobuf::MapLiteTestUtil::SetArenaMapFields(from);
+ MapLiteTestUtil::SetArenaMapFields(from);
from->SerializeToString(&data);
protobuf_unittest::TestArenaMapLite* to =
Arena::CreateMessage<protobuf_unittest::TestArenaMapLite>(arena_.get());
to->ParseFromString(data);
- google::protobuf::MapLiteTestUtil::ExpectArenaMapFieldsSet(*to);
+ MapLiteTestUtil::ExpectArenaMapFieldsSet(*to);
}
}
TEST_F(LiteArenaTest, UnknownFieldMemLeak) {
protobuf_unittest::ForeignMessageArenaLite* message =
- google::protobuf::Arena::CreateMessage<protobuf_unittest::ForeignMessageArenaLite>(
+ Arena::CreateMessage<protobuf_unittest::ForeignMessageArenaLite>(
arena_.get());
string data = "\012\000";
int original_capacity = data.capacity();
diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc
index b42a7b14..e893316b 100644
--- a/src/google/protobuf/lite_unittest.cc
+++ b/src/google/protobuf/lite_unittest.cc
@@ -46,22 +46,25 @@
#include <google/protobuf/wire_format_lite_inl.h>
#include <gtest/gtest.h>
+// When string == std::string inside Google, we can remove this typedef.
#include <google/protobuf/stubs/strutil.h>
-using std::string;
+typedef std::string ProtoString;
+
+namespace google {
+namespace protobuf {
-namespace {
// Helper methods to test parsing merge behavior.
-void ExpectMessageMerged(const google::protobuf::unittest::TestAllTypesLite& message) {
+void ExpectMessageMerged(const unittest::TestAllTypesLite& message) {
EXPECT_EQ(message.optional_int32(), 3);
EXPECT_EQ(message.optional_int64(), 2);
EXPECT_EQ(message.optional_string(), "hello");
}
void AssignParsingMergeMessages(
- google::protobuf::unittest::TestAllTypesLite* msg1,
- google::protobuf::unittest::TestAllTypesLite* msg2,
- google::protobuf::unittest::TestAllTypesLite* msg3) {
+ unittest::TestAllTypesLite* msg1,
+ unittest::TestAllTypesLite* msg2,
+ unittest::TestAllTypesLite* msg3) {
msg1->set_optional_int32(1);
msg2->set_optional_int64(2);
msg3->set_optional_int32(3);
@@ -69,114 +72,112 @@ void AssignParsingMergeMessages(
}
void SetAllTypesInEmptyMessageUnknownFields(
- google::protobuf::unittest::TestEmptyMessageLite* empty_message) {
+ unittest::TestEmptyMessageLite* empty_message) {
protobuf_unittest::TestAllTypesLite message;
- google::protobuf::TestUtilLite::ExpectClear(message);
- google::protobuf::TestUtilLite::SetAllFields(&message);
- string data = message.SerializeAsString();
+ TestUtilLite::ExpectClear(message);
+ TestUtilLite::SetAllFields(&message);
+ ProtoString data = message.SerializeAsString();
empty_message->ParseFromString(data);
}
void SetSomeTypesInEmptyMessageUnknownFields(
- google::protobuf::unittest::TestEmptyMessageLite* empty_message) {
+ unittest::TestEmptyMessageLite* empty_message) {
protobuf_unittest::TestAllTypesLite message;
- google::protobuf::TestUtilLite::ExpectClear(message);
+ TestUtilLite::ExpectClear(message);
message.set_optional_int32(101);
message.set_optional_int64(102);
message.set_optional_uint32(103);
message.set_optional_uint64(104);
- string data = message.SerializeAsString();
+ ProtoString data = message.SerializeAsString();
empty_message->ParseFromString(data);
}
-} // namespace
-
TEST(Lite, AllLite1) {
- string data;
+ ProtoString data;
{
protobuf_unittest::TestAllTypesLite message, message2, message3;
- google::protobuf::TestUtilLite::ExpectClear(message);
- google::protobuf::TestUtilLite::SetAllFields(&message);
+ TestUtilLite::ExpectClear(message);
+ TestUtilLite::SetAllFields(&message);
message2.CopyFrom(message);
data = message.SerializeAsString();
message3.ParseFromString(data);
- google::protobuf::TestUtilLite::ExpectAllFieldsSet(message);
- google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2);
- google::protobuf::TestUtilLite::ExpectAllFieldsSet(message3);
- google::protobuf::TestUtilLite::ModifyRepeatedFields(&message);
- google::protobuf::TestUtilLite::ExpectRepeatedFieldsModified(message);
+ TestUtilLite::ExpectAllFieldsSet(message);
+ TestUtilLite::ExpectAllFieldsSet(message2);
+ TestUtilLite::ExpectAllFieldsSet(message3);
+ TestUtilLite::ModifyRepeatedFields(&message);
+ TestUtilLite::ExpectRepeatedFieldsModified(message);
message.Clear();
- google::protobuf::TestUtilLite::ExpectClear(message);
+ TestUtilLite::ExpectClear(message);
}
}
TEST(Lite, AllLite2) {
- string data;
+ ProtoString data;
{
protobuf_unittest::TestAllExtensionsLite message, message2, message3;
- google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
- google::protobuf::TestUtilLite::SetAllExtensions(&message);
+ TestUtilLite::ExpectExtensionsClear(message);
+ TestUtilLite::SetAllExtensions(&message);
message2.CopyFrom(message);
- string extensions_data = message.SerializeAsString();
+ ProtoString extensions_data = message.SerializeAsString();
message3.ParseFromString(extensions_data);
- google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message);
- google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2);
- google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message3);
- google::protobuf::TestUtilLite::ModifyRepeatedExtensions(&message);
- google::protobuf::TestUtilLite::ExpectRepeatedExtensionsModified(message);
+ TestUtilLite::ExpectAllExtensionsSet(message);
+ TestUtilLite::ExpectAllExtensionsSet(message2);
+ TestUtilLite::ExpectAllExtensionsSet(message3);
+ TestUtilLite::ModifyRepeatedExtensions(&message);
+ TestUtilLite::ExpectRepeatedExtensionsModified(message);
message.Clear();
- google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
+ TestUtilLite::ExpectExtensionsClear(message);
}
}
TEST(Lite, AllLite3) {
- string data, packed_data;
+ ProtoString data, packed_data;
{
protobuf_unittest::TestPackedTypesLite message, message2, message3;
- google::protobuf::TestUtilLite::ExpectPackedClear(message);
- google::protobuf::TestUtilLite::SetPackedFields(&message);
+ TestUtilLite::ExpectPackedClear(message);
+ TestUtilLite::SetPackedFields(&message);
message2.CopyFrom(message);
packed_data = message.SerializeAsString();
message3.ParseFromString(packed_data);
- google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message);
- google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2);
- google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message3);
- google::protobuf::TestUtilLite::ModifyPackedFields(&message);
- google::protobuf::TestUtilLite::ExpectPackedFieldsModified(message);
+ TestUtilLite::ExpectPackedFieldsSet(message);
+ TestUtilLite::ExpectPackedFieldsSet(message2);
+ TestUtilLite::ExpectPackedFieldsSet(message3);
+ TestUtilLite::ModifyPackedFields(&message);
+ TestUtilLite::ExpectPackedFieldsModified(message);
message.Clear();
- google::protobuf::TestUtilLite::ExpectPackedClear(message);
+ TestUtilLite::ExpectPackedClear(message);
}
{
protobuf_unittest::TestPackedExtensionsLite message, message2, message3;
- google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
- google::protobuf::TestUtilLite::SetPackedExtensions(&message);
+ TestUtilLite::ExpectPackedExtensionsClear(message);
+ TestUtilLite::SetPackedExtensions(&message);
message2.CopyFrom(message);
- string packed_extensions_data = message.SerializeAsString();
+ ProtoString packed_extensions_data = message.SerializeAsString();
EXPECT_EQ(packed_extensions_data, packed_data);
message3.ParseFromString(packed_extensions_data);
- google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message);
- google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2);
- google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message3);
- google::protobuf::TestUtilLite::ModifyPackedExtensions(&message);
- google::protobuf::TestUtilLite::ExpectPackedExtensionsModified(message);
+ TestUtilLite::ExpectPackedExtensionsSet(message);
+ TestUtilLite::ExpectPackedExtensionsSet(message2);
+ TestUtilLite::ExpectPackedExtensionsSet(message3);
+ TestUtilLite::ModifyPackedExtensions(&message);
+ TestUtilLite::ExpectPackedExtensionsModified(message);
message.Clear();
- google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
+ TestUtilLite::ExpectPackedExtensionsClear(message);
}
}
TEST(Lite, AllLite5) {
- string data;
+ ProtoString data;
{
// Test that if an optional or required message/group field appears multiple
// times in the input, they need to be merged.
- google::protobuf::unittest::TestParsingMergeLite::RepeatedFieldsGenerator generator;
- google::protobuf::unittest::TestAllTypesLite* msg1;
- google::protobuf::unittest::TestAllTypesLite* msg2;
- google::protobuf::unittest::TestAllTypesLite* msg3;
+ unittest::TestParsingMergeLite::RepeatedFieldsGenerator generator;
+ unittest::TestAllTypesLite* msg1;
+ unittest::TestAllTypesLite* msg2;
+ unittest::TestAllTypesLite* msg3;
#define ASSIGN_REPEATED_FIELD(FIELD) \
msg1 = generator.add_##FIELD(); \
@@ -202,9 +203,9 @@ TEST(Lite, AllLite5) {
#undef ASSIGN_REPEATED_GROUP
- string buffer;
+ ProtoString buffer;
generator.SerializeToString(&buffer);
- google::protobuf::unittest::TestParsingMergeLite parsing_merge;
+ unittest::TestParsingMergeLite parsing_merge;
parsing_merge.ParseFromString(buffer);
// Required and optional fields should be merged.
@@ -213,100 +214,100 @@ TEST(Lite, AllLite5) {
ExpectMessageMerged(
parsing_merge.optionalgroup().optional_group_all_types());
ExpectMessageMerged(parsing_merge.GetExtension(
- google::protobuf::unittest::TestParsingMergeLite::optional_ext));
+ unittest::TestParsingMergeLite::optional_ext));
// Repeated fields should not be merged.
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),
+ unittest::TestParsingMergeLite::repeated_ext),
3);
}
}
TEST(Lite, AllLite6) {
- string data;
+ ProtoString data;
// Test unknown fields support for lite messages.
{
protobuf_unittest::TestAllTypesLite message, message2;
protobuf_unittest::TestEmptyMessageLite empty_message;
- google::protobuf::TestUtilLite::ExpectClear(message);
- google::protobuf::TestUtilLite::SetAllFields(&message);
+ TestUtilLite::ExpectClear(message);
+ TestUtilLite::SetAllFields(&message);
data = message.SerializeAsString();
empty_message.ParseFromString(data);
data.clear();
data = empty_message.SerializeAsString();
message2.ParseFromString(data);
data = message2.SerializeAsString();
- google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2);
+ TestUtilLite::ExpectAllFieldsSet(message2);
message.Clear();
- google::protobuf::TestUtilLite::ExpectClear(message);
+ TestUtilLite::ExpectClear(message);
}
}
TEST(Lite, AllLite7) {
- string data;
+ ProtoString data;
{
protobuf_unittest::TestAllExtensionsLite message, message2;
protobuf_unittest::TestEmptyMessageLite empty_message;
- google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
- google::protobuf::TestUtilLite::SetAllExtensions(&message);
+ TestUtilLite::ExpectExtensionsClear(message);
+ TestUtilLite::SetAllExtensions(&message);
data = message.SerializeAsString();
empty_message.ParseFromString(data);
data.clear();
data = empty_message.SerializeAsString();
message2.ParseFromString(data);
data = message2.SerializeAsString();
- google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2);
+ TestUtilLite::ExpectAllExtensionsSet(message2);
message.Clear();
- google::protobuf::TestUtilLite::ExpectExtensionsClear(message);
+ TestUtilLite::ExpectExtensionsClear(message);
}
}
TEST(Lite, AllLite8) {
- string data;
+ ProtoString data;
{
protobuf_unittest::TestPackedTypesLite message, message2;
protobuf_unittest::TestEmptyMessageLite empty_message;
- google::protobuf::TestUtilLite::ExpectPackedClear(message);
- google::protobuf::TestUtilLite::SetPackedFields(&message);
+ TestUtilLite::ExpectPackedClear(message);
+ TestUtilLite::SetPackedFields(&message);
data = message.SerializeAsString();
empty_message.ParseFromString(data);
data.clear();
data = empty_message.SerializeAsString();
message2.ParseFromString(data);
data = message2.SerializeAsString();
- google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2);
+ TestUtilLite::ExpectPackedFieldsSet(message2);
message.Clear();
- google::protobuf::TestUtilLite::ExpectPackedClear(message);
+ TestUtilLite::ExpectPackedClear(message);
}
}
TEST(Lite, AllLite9) {
- string data;
+ ProtoString data;
{
protobuf_unittest::TestPackedExtensionsLite message, message2;
protobuf_unittest::TestEmptyMessageLite empty_message;
- google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
- google::protobuf::TestUtilLite::SetPackedExtensions(&message);
+ TestUtilLite::ExpectPackedExtensionsClear(message);
+ TestUtilLite::SetPackedExtensions(&message);
data = message.SerializeAsString();
empty_message.ParseFromString(data);
data.clear();
data = empty_message.SerializeAsString();
message2.ParseFromString(data);
data = message2.SerializeAsString();
- google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2);
+ TestUtilLite::ExpectPackedExtensionsSet(message2);
message.Clear();
- google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message);
+ TestUtilLite::ExpectPackedExtensionsClear(message);
}
}
TEST(Lite, AllLite10) {
- string data;
+ ProtoString data;
{
// Test Unknown fields swap
@@ -314,7 +315,7 @@ TEST(Lite, AllLite10) {
SetAllTypesInEmptyMessageUnknownFields(&empty_message);
SetSomeTypesInEmptyMessageUnknownFields(&empty_message2);
data = empty_message.SerializeAsString();
- string data2 = empty_message2.SerializeAsString();
+ ProtoString data2 = empty_message2.SerializeAsString();
empty_message.Swap(&empty_message2);
EXPECT_EQ(data, empty_message2.SerializeAsString());
EXPECT_EQ(data2, empty_message.SerializeAsString());
@@ -322,7 +323,7 @@ TEST(Lite, AllLite10) {
}
TEST(Lite, AllLite11) {
- string data;
+ ProtoString data;
{
// Test unknown fields swap with self
@@ -335,7 +336,7 @@ TEST(Lite, AllLite11) {
}
TEST(Lite, AllLite12) {
- string data;
+ ProtoString data;
{
// Test MergeFrom with unknown fields
@@ -343,10 +344,10 @@ TEST(Lite, AllLite12) {
protobuf_unittest::TestEmptyMessageLite empty_message, empty_message2;
message.set_optional_int32(101);
message.add_repeated_int32(201);
- message.set_optional_nested_enum(google::protobuf::unittest::TestAllTypesLite::BAZ);
+ message.set_optional_nested_enum(unittest::TestAllTypesLite::BAZ);
message2.set_optional_int64(102);
message2.add_repeated_int64(202);
- message2.set_optional_foreign_enum(google::protobuf::unittest::FOREIGN_LITE_BAZ);
+ message2.set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ);
data = message.SerializeAsString();
empty_message.ParseFromString(data);
@@ -365,22 +366,22 @@ TEST(Lite, AllLite12) {
}
TEST(Lite, AllLite13) {
- string data;
+ ProtoString data;
{
// Test unknown enum value
protobuf_unittest::TestAllTypesLite message;
- string buffer;
+ ProtoString buffer;
{
- google::protobuf::io::StringOutputStream output_stream(&buffer);
- google::protobuf::io::CodedOutputStream coded_output(&output_stream);
- google::protobuf::internal::WireFormatLite::WriteTag(
+ io::StringOutputStream output_stream(&buffer);
+ io::CodedOutputStream coded_output(&output_stream);
+ internal::WireFormatLite::WriteTag(
protobuf_unittest::TestAllTypesLite::kOptionalNestedEnumFieldNumber,
- google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
+ internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
coded_output.WriteVarint32(10);
- google::protobuf::internal::WireFormatLite::WriteTag(
+ internal::WireFormatLite::WriteTag(
protobuf_unittest::TestAllTypesLite::kRepeatedNestedEnumFieldNumber,
- google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
+ internal::WireFormatLite::WIRETYPE_VARINT, &coded_output);
coded_output.WriteVarint32(20);
}
message.ParseFromString(buffer);
@@ -390,7 +391,7 @@ TEST(Lite, AllLite13) {
}
TEST(Lite, AllLite14) {
- string data;
+ ProtoString data;
{
// Test Clear with unknown fields
@@ -404,77 +405,77 @@ TEST(Lite, AllLite14) {
// Tests for map lite =============================================
TEST(Lite, AllLite15) {
- string data;
+ ProtoString data;
{
// Accessors
protobuf_unittest::TestMapLite message;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);
+ MapLiteTestUtil::SetMapFields(&message);
+ MapLiteTestUtil::ExpectMapFieldsSet(message);
- google::protobuf::MapLiteTestUtil::ModifyMapFields(&message);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message);
+ MapLiteTestUtil::ModifyMapFields(&message);
+ MapLiteTestUtil::ExpectMapFieldsModified(message);
}
}
TEST(Lite, AllLite16) {
- string data;
+ ProtoString data;
{
// SetMapFieldsInitialized
protobuf_unittest::TestMapLite message;
- google::protobuf::MapLiteTestUtil::SetMapFieldsInitialized(&message);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSetInitialized(message);
+ MapLiteTestUtil::SetMapFieldsInitialized(&message);
+ MapLiteTestUtil::ExpectMapFieldsSetInitialized(message);
}
}
TEST(Lite, AllLite17) {
- string data;
+ ProtoString data;
{
// Clear
protobuf_unittest::TestMapLite message;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message);
+ MapLiteTestUtil::SetMapFields(&message);
message.Clear();
- google::protobuf::MapLiteTestUtil::ExpectClear(message);
+ MapLiteTestUtil::ExpectClear(message);
}
}
TEST(Lite, AllLite18) {
- string data;
+ ProtoString data;
{
// ClearMessageMap
protobuf_unittest::TestMessageMapLite message;
// Creates a TestAllTypes with default value
- google::protobuf::TestUtilLite::ExpectClear(
+ TestUtilLite::ExpectClear(
(*message.mutable_map_int32_message())[0]);
}
}
TEST(Lite, AllLite19) {
- string data;
+ ProtoString data;
{
// CopyFrom
protobuf_unittest::TestMapLite message1, message2;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message1);
message2.CopyFrom(message1);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
// Copying from self should be a no-op.
message2.CopyFrom(message2);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite20) {
- string data;
+ ProtoString data;
{
// CopyFromMessageMap
@@ -492,93 +493,93 @@ TEST(Lite, AllLite20) {
}
TEST(Lite, AllLite21) {
- string data;
+ ProtoString data;
{
// SwapWithEmpty
protobuf_unittest::TestMapLite message1, message2;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1);
- google::protobuf::MapLiteTestUtil::ExpectClear(message2);
+ MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::ExpectMapFieldsSet(message1);
+ MapLiteTestUtil::ExpectClear(message2);
message1.Swap(&message2);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
- google::protobuf::MapLiteTestUtil::ExpectClear(message1);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectClear(message1);
}
}
TEST(Lite, AllLite22) {
- string data;
+ ProtoString data;
{
// SwapWithSelf
protobuf_unittest::TestMapLite message;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);
+ MapLiteTestUtil::SetMapFields(&message);
+ MapLiteTestUtil::ExpectMapFieldsSet(message);
message.Swap(&message);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message);
+ MapLiteTestUtil::ExpectMapFieldsSet(message);
}
}
TEST(Lite, AllLite23) {
- string data;
+ ProtoString data;
{
// SwapWithOther
protobuf_unittest::TestMapLite message1, message2;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
- google::protobuf::MapLiteTestUtil::SetMapFields(&message2);
- google::protobuf::MapLiteTestUtil::ModifyMapFields(&message2);
+ MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message2);
+ MapLiteTestUtil::ModifyMapFields(&message2);
message1.Swap(&message2);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsModified(message1);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsModified(message1);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite24) {
- string data;
+ ProtoString data;
{
// CopyConstructor
protobuf_unittest::TestMapLite message1;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message1);
protobuf_unittest::TestMapLite message2(message1);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite25) {
- string data;
+ ProtoString data;
{
// CopyAssignmentOperator
protobuf_unittest::TestMapLite message1;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message1);
protobuf_unittest::TestMapLite message2;
message2 = message1;
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
// Make sure that self-assignment does something sane.
message2.operator=(message2);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite26) {
- string data;
+ ProtoString data;
{
// NonEmptyMergeFrom
protobuf_unittest::TestMapLite message1, message2;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message1);
// This field will test merging into an empty spot.
(*message2.mutable_map_int32_int32())[1] = 1;
@@ -589,12 +590,12 @@ TEST(Lite, AllLite26) {
(*message1.mutable_map_int32_double())[1] = 2;
message1.MergeFrom(message2);
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message1);
+ MapLiteTestUtil::ExpectMapFieldsSet(message1);
}
}
TEST(Lite, AllLite27) {
- string data;
+ ProtoString data;
{
// MergeFromMessageMap
@@ -612,50 +613,49 @@ TEST(Lite, AllLite27) {
}
TEST(Lite, AllLite28) {
- string data;
+ ProtoString data;
{
// Test the generated SerializeWithCachedSizesToArray()
protobuf_unittest::TestMapLite message1, message2;
- string data;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ ProtoString data;
+ MapLiteTestUtil::SetMapFields(&message1);
int size = message1.ByteSize();
data.resize(size);
::google::protobuf::uint8* start = reinterpret_cast<::google::protobuf::uint8*>(::google::protobuf::string_as_array(&data));
::google::protobuf::uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite29) {
- string data;
+ ProtoString data;
{
// Test the generated SerializeWithCachedSizes()
protobuf_unittest::TestMapLite message1, message2;
- google::protobuf::MapLiteTestUtil::SetMapFields(&message1);
+ MapLiteTestUtil::SetMapFields(&message1);
int size = message1.ByteSize();
- string data;
+ ProtoString data;
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
- google::protobuf::io::ArrayOutputStream array_stream(
- ::google::protobuf::string_as_array(&data), size, 1);
- google::protobuf::io::CodedOutputStream output_stream(&array_stream);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
+ io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
}
EXPECT_TRUE(message2.ParseFromString(data));
- google::protobuf::MapLiteTestUtil::ExpectMapFieldsSet(message2);
+ MapLiteTestUtil::ExpectMapFieldsSet(message2);
}
}
TEST(Lite, AllLite32) {
- string data;
+ ProtoString data;
{
// Proto2UnknownEnum
@@ -664,14 +664,14 @@ TEST(Lite, AllLite32) {
protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE;
(*from.mutable_unknown_map_field())[0] =
protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE;
- string data;
+ ProtoString data;
from.SerializeToString(&data);
protobuf_unittest::TestEnumMapLite to;
EXPECT_TRUE(to.ParseFromString(data));
EXPECT_EQ(0, to.unknown_map_field().size());
EXPECT_FALSE(to.mutable_unknown_fields()->empty());
- EXPECT_EQ(1, to.known_map_field().size());
+ ASSERT_EQ(1, to.known_map_field().size());
EXPECT_EQ(protobuf_unittest::PROTO2_MAP_ENUM_FOO_LITE,
to.known_map_field().at(0));
@@ -679,141 +679,147 @@ TEST(Lite, AllLite32) {
from.Clear();
to.SerializeToString(&data);
EXPECT_TRUE(from.ParseFromString(data));
- EXPECT_EQ(1, from.known_map_field().size());
+ ASSERT_EQ(1, from.known_map_field().size());
EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_FOO_LITE,
from.known_map_field().at(0));
- EXPECT_EQ(1, from.unknown_map_field().size());
+ ASSERT_EQ(1, from.unknown_map_field().size());
EXPECT_EQ(protobuf_unittest::E_PROTO2_MAP_ENUM_EXTRA_LITE,
from.unknown_map_field().at(0));
}
}
TEST(Lite, AllLite33) {
- string data;
+ ProtoString data;
{
// StandardWireFormat
protobuf_unittest::TestMapLite message;
- string data = "\x0A\x04\x08\x01\x10\x01";
+ ProtoString data = "\x0A\x04\x08\x01\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(1));
}
}
TEST(Lite, AllLite34) {
- string data;
+ ProtoString data;
{
// UnorderedWireFormat
protobuf_unittest::TestMapLite message;
// put value before key in wire format
- string data = "\x0A\x04\x10\x01\x08\x02";
+ ProtoString data = "\x0A\x04\x10\x01\x08\x02";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(2),
+ message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
}
TEST(Lite, AllLite35) {
- string data;
+ ProtoString data;
{
// DuplicatedKeyWireFormat
protobuf_unittest::TestMapLite message;
// Two key fields in wire format
- string data = "\x0A\x06\x08\x01\x08\x02\x10\x01";
+ ProtoString data = "\x0A\x06\x08\x01\x08\x02\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
}
TEST(Lite, AllLite36) {
- string data;
+ ProtoString data;
{
// DuplicatedValueWireFormat
protobuf_unittest::TestMapLite message;
// Two value fields in wire format
- string data = "\x0A\x06\x08\x01\x10\x01\x10\x02";
+ ProtoString data = "\x0A\x06\x08\x01\x10\x01\x10\x02";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(2, message.map_int32_int32().at(1));
}
}
TEST(Lite, AllLite37) {
- string data;
+ ProtoString data;
{
// MissedKeyWireFormat
protobuf_unittest::TestMapLite message;
// No key field in wire format
- string data = "\x0A\x02\x10\x01";
+ ProtoString data = "\x0A\x02\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(0),
+ message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(0));
}
}
TEST(Lite, AllLite38) {
- string data;
+ ProtoString data;
{
// MissedValueWireFormat
protobuf_unittest::TestMapLite message;
// No value field in wire format
- string data = "\x0A\x02\x08\x01";
+ ProtoString data = "\x0A\x02\x08\x01";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(1),
+ message.map_int32_int32().end());
EXPECT_EQ(0, message.map_int32_int32().at(1));
}
}
TEST(Lite, AllLite39) {
- string data;
+ ProtoString data;
{
// UnknownFieldWireFormat
protobuf_unittest::TestMapLite message;
// Unknown field in wire format
- string data = "\x0A\x06\x08\x02\x10\x03\x18\x01";
+ ProtoString data = "\x0A\x06\x08\x02\x10\x03\x18\x01";
EXPECT_TRUE(message.ParseFromString(data));
- EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(3, message.map_int32_int32().at(2));
}
}
TEST(Lite, AllLite40) {
- string data;
+ ProtoString data;
{
// CorruptedWireFormat
protobuf_unittest::TestMapLite message;
// corrupted data in wire format
- string data = "\x0A\x06\x08\x02\x11\x03";
+ ProtoString data = "\x0A\x06\x08\x02\x11\x03";
EXPECT_FALSE(message.ParseFromString(data));
}
}
TEST(Lite, AllLite41) {
- string data;
+ ProtoString data;
{
// IsInitialized
@@ -832,7 +838,7 @@ TEST(Lite, AllLite41) {
}
TEST(Lite, AllLite42) {
- string data;
+ ProtoString data;
{
// Check that adding more values to enum does not corrupt message
@@ -841,7 +847,7 @@ TEST(Lite, AllLite42) {
v2_message.set_int_field(800);
// Set enum field to the value not understood by the old client.
v2_message.set_enum_field(protobuf_unittest::V2_SECOND);
- string v2_bytes = v2_message.SerializeAsString();
+ ProtoString v2_bytes = v2_message.SerializeAsString();
protobuf_unittest::V1MessageLite v1_message;
v1_message.ParseFromString(v2_bytes);
@@ -852,7 +858,7 @@ TEST(Lite, AllLite42) {
EXPECT_EQ(v1_message.enum_field(), protobuf_unittest::V1_FIRST);
// However, when re-serialized, it should preserve enum value.
- string v1_bytes = v1_message.SerializeAsString();
+ ProtoString v1_bytes = v1_message.SerializeAsString();
protobuf_unittest::V2MessageLite same_v2_message;
same_v2_message.ParseFromString(v1_bytes);
@@ -868,14 +874,14 @@ TEST(Lite, AllLite43) {
protobuf_unittest::TestOneofParsingLite message1;
message1.set_oneof_int32(17);
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(message1.SerializeToString(&serialized));
// Submessage
{
protobuf_unittest::TestOneofParsingLite message2;
message2.mutable_oneof_submessage();
- google::protobuf::io::CodedInputStream input_stream(
+ 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());
@@ -885,7 +891,7 @@ TEST(Lite, AllLite43) {
{
protobuf_unittest::TestOneofParsingLite message2;
message2.set_oneof_string("string");
- google::protobuf::io::CodedInputStream input_stream(
+ 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());
@@ -895,7 +901,7 @@ TEST(Lite, AllLite43) {
{
protobuf_unittest::TestOneofParsingLite message2;
message2.set_oneof_bytes("bytes");
- google::protobuf::io::CodedInputStream input_stream(
+ 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());
@@ -910,11 +916,11 @@ TEST(Lite, AllLite44) {
{
protobuf_unittest::TestOneofParsingLite original;
original.set_oneof_int32(17);
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(original.SerializeToString(&serialized));
protobuf_unittest::TestOneofParsingLite parsed;
for (int i = 0; i < 2; ++i) {
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
serialized.size());
EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
@@ -926,11 +932,11 @@ TEST(Lite, AllLite44) {
{
protobuf_unittest::TestOneofParsingLite original;
original.mutable_oneof_submessage()->set_optional_int32(5);
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(original.SerializeToString(&serialized));
protobuf_unittest::TestOneofParsingLite parsed;
for (int i = 0; i < 2; ++i) {
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
serialized.size());
EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
@@ -942,11 +948,11 @@ TEST(Lite, AllLite44) {
{
protobuf_unittest::TestOneofParsingLite original;
original.set_oneof_string("string");
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(original.SerializeToString(&serialized));
protobuf_unittest::TestOneofParsingLite parsed;
for (int i = 0; i < 2; ++i) {
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
serialized.size());
EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
@@ -958,11 +964,11 @@ TEST(Lite, AllLite44) {
{
protobuf_unittest::TestOneofParsingLite original;
original.set_oneof_bytes("bytes");
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(original.SerializeToString(&serialized));
protobuf_unittest::TestOneofParsingLite parsed;
for (int i = 0; i < 2; ++i) {
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
serialized.size());
EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
@@ -974,11 +980,11 @@ TEST(Lite, AllLite44) {
{
protobuf_unittest::TestOneofParsingLite original;
original.set_oneof_enum(protobuf_unittest::V2_SECOND);
- string serialized;
+ ProtoString serialized;
EXPECT_TRUE(original.SerializeToString(&serialized));
protobuf_unittest::TestOneofParsingLite parsed;
for (int i = 0; i < 2; ++i) {
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(serialized.data()),
serialized.size());
EXPECT_TRUE(parsed.MergeFromCodedStream(&input_stream));
@@ -991,15 +997,15 @@ TEST(Lite, AllLite44) {
TEST(Lite, AllLite45) {
// Test unknown fields are not discarded upon parsing.
- string data = "\20\1"; // varint 1 with field number 2
+ ProtoString data = "\20\1"; // varint 1 with field number 2
protobuf_unittest::ForeignMessageLite a;
EXPECT_TRUE(a.ParseFromString(data));
- google::protobuf::io::CodedInputStream input_stream(
+ io::CodedInputStream input_stream(
reinterpret_cast<const ::google::protobuf::uint8*>(data.data()), data.size());
EXPECT_TRUE(a.MergePartialFromCodedStream(&input_stream));
- string serialized = a.SerializeAsString();
+ ProtoString serialized = a.SerializeAsString();
EXPECT_EQ(serialized.substr(0, 2), data);
EXPECT_EQ(serialized.substr(2), data);
}
@@ -1014,7 +1020,7 @@ TEST(Lite, AllLite45) {
TEST(Lite, AllLite46) {
protobuf_unittest::PackedInt32 packed;
packed.add_repeated_int32(42);
- string serialized;
+ ProtoString serialized;
ASSERT_TRUE(packed.SerializeToString(&serialized));
protobuf_unittest::NonPackedInt32 non_packed;
@@ -1026,7 +1032,7 @@ TEST(Lite, AllLite46) {
TEST(Lite, AllLite47) {
protobuf_unittest::NonPackedFixed32 non_packed;
non_packed.add_repeated_fixed32(42);
- string serialized;
+ ProtoString serialized;
ASSERT_TRUE(non_packed.SerializeToString(&serialized));
protobuf_unittest::PackedFixed32 packed;
@@ -1034,3 +1040,20 @@ TEST(Lite, AllLite47) {
ASSERT_EQ(1, packed.repeated_fixed32_size());
EXPECT_EQ(42, packed.repeated_fixed32(0));
}
+
+TEST(Lite, MapCrash) {
+ // See b/113635730
+ Arena arena;
+ auto msg = Arena::CreateMessage<protobuf_unittest::TestMapLite>(&arena);
+ // Payload for the map<string, Enum> with a enum varint that's longer > 10
+ // bytes. This causes a parse fail and a subsequent delete.
+ // field 16 (map<int32, MapEnumLite>) tag = 128+2 = \202 \1
+ // 13 long \15
+ // int32 key = 1 (\10 \1)
+ // MapEnumLite value = too long varint (parse error)
+ EXPECT_FALSE(msg->ParseFromString(
+ "\202\1\15\10\1\200\200\200\200\200\200\200\200\200\200\1"));
+}
+
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h
index 6463ac2e..a7126c16 100644
--- a/src/google/protobuf/map.h
+++ b/src/google/protobuf/map.h
@@ -49,6 +49,12 @@
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/stubs/hash.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -78,7 +84,7 @@ class DynamicMapField;
class GeneratedMessageReflection;
} // namespace internal
-// This is the class for google::protobuf::Map's internal value_type. Instead of using
+// This is the class for 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.
template <typename Key, typename T>
@@ -105,11 +111,11 @@ class MapPair {
T second;
private:
- friend class ::google::protobuf::Arena;
+ friend class Arena;
friend class Map<Key, T>;
};
-// google::protobuf::Map is an associative container type used to store protobuf map
+// Map is an associative container type used to store protobuf map
// fields. Each Map instance may or may not use a different hash function, a
// different iteration order, and so on. E.g., please don't examine
// implementation details to decide if the following would work:
@@ -181,7 +187,7 @@ class Map {
}
// re-implement std::allocator to use arena allocator for memory allocation.
- // Used for google::protobuf::Map implementation. Users should not use this class
+ // Used for Map implementation. Users should not use this class
// directly.
template <typename U>
class MapAllocator {
@@ -622,7 +628,7 @@ class Map {
}
DestroyNode(item);
--num_elements_;
- if (GOOGLE_PREDICT_FALSE(b == index_of_first_non_null_)) {
+ if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) {
while (index_of_first_non_null_ < num_buckets_ &&
table_[index_of_first_non_null_] == NULL) {
++index_of_first_non_null_;
@@ -679,7 +685,7 @@ class Map {
if (TableEntryIsEmpty(b)) {
result = InsertUniqueInList(b, node);
} else if (TableEntryIsNonEmptyList(b)) {
- if (GOOGLE_PREDICT_FALSE(TableEntryIsTooLong(b))) {
+ if (PROTOBUF_PREDICT_FALSE(TableEntryIsTooLong(b))) {
TreeConvert(b);
result = InsertUniqueInTree(b, node);
GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast<size_type>(1));
@@ -734,13 +740,13 @@ class Map {
// We don't care how many elements are in trees. If a lot are,
// we may resize even though there are many empty buckets. In
// practice, this seems fine.
- if (GOOGLE_PREDICT_FALSE(new_size >= hi_cutoff)) {
+ if (PROTOBUF_PREDICT_FALSE(new_size >= hi_cutoff)) {
if (num_buckets_ <= max_size() / 2) {
Resize(num_buckets_ * 2);
return true;
}
- } else if (GOOGLE_PREDICT_FALSE(new_size <= lo_cutoff &&
- num_buckets_ > kMinTableSize)) {
+ } else if (PROTOBUF_PREDICT_FALSE(new_size <= lo_cutoff &&
+ num_buckets_ > kMinTableSize)) {
size_type lg2_of_size_reduction_factor = 1;
// It's possible we want to shrink a lot here... size() could even be 0.
// So, estimate how much to shrink by making sure we don't shrink so
@@ -1047,9 +1053,8 @@ class Map {
value_type** value = &(*elements_)[key];
if (*value == NULL) {
*value = CreateValueTypeInternal(key);
- internal::MapValueInitializer<google::protobuf::is_proto_enum<T>::value,
- T>::Initialize((*value)->second,
- default_enum_value_);
+ internal::MapValueInitializer<is_proto_enum<T>::value, T>::Initialize(
+ (*value)->second, default_enum_value_);
}
return (*value)->second;
}
@@ -1203,7 +1208,7 @@ class Map {
int default_enum_value_;
InnerMap* elements_;
- friend class ::google::protobuf::Arena;
+ friend class Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
template <typename Derived, typename K, typename V,
@@ -1214,6 +1219,8 @@ class Map {
};
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MAP_H__
diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h
index 801def97..fbc792f3 100644
--- a/src/google/protobuf/map_entry.h
+++ b/src/google/protobuf/map_entry.h
@@ -35,10 +35,17 @@
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/metadata.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
class Arena;
@@ -48,8 +55,10 @@ template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kValueFieldType, int default_enum_value>
class MapField;
}
-}
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace internal {
@@ -95,10 +104,24 @@ class MapEntry
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
+ typedef
+ typename MapEntryImpl<Derived, Message, Key, Value, kKeyFieldType,
+ kValueFieldType, default_enum_value>::KeyTypeHandler
+ KeyTypeHandler;
+ typedef typename MapEntryImpl<
+ Derived, Message, Key, Value, kKeyFieldType, kValueFieldType,
+ default_enum_value>::ValueTypeHandler ValueTypeHandler;
+ size_t SpaceUsedLong() const override {
+ size_t size = sizeof(Derived);
+ size += KeyTypeHandler::SpaceUsedInMapEntryLong(this->key_);
+ size += ValueTypeHandler::SpaceUsedInMapEntryLong(this->value_);
+ return size;
+ }
+
InternalMetadataWithArena _internal_metadata_;
private:
- friend class ::google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
template <typename C, typename K, typename V,
WireFormatLite::FieldType k_wire_type, WireFormatLite::FieldType,
int default_enum>
@@ -135,6 +158,8 @@ struct DeconstructMapEntry<MapEntry<Derived, K, V, key, value, default_enum> > {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MAP_ENTRY_H__
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index 85a0bed7..98b2acae 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -32,15 +32,26 @@
#define GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
#include <assert.h>
+#include <string>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_type_handler.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
+#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/wire_format_lite_inl.h>
+#include <google/protobuf/port_def.inc>
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -54,7 +65,9 @@ template <typename Derived, typename Key, typename Value,
class MapFieldLite;
} // namespace internal
} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace internal {
@@ -177,13 +190,13 @@ class MapEntryImpl : public Base {
// MapEntryImpl is for implementation only and this function isn't called
// anywhere. Just provide a fake implementation here for MessageLite.
- string GetTypeName() const { return ""; }
+ std::string GetTypeName() const override { return ""; }
- void CheckTypeAndMergeFrom(const MessageLite& other) {
+ void CheckTypeAndMergeFrom(const MessageLite& other) override {
MergeFromInternal(*::google::protobuf::down_cast<const Derived*>(&other));
}
- bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) {
+ bool MergePartialFromCodedStream(io::CodedInputStream* input) override {
uint32 tag;
for (;;) {
@@ -224,7 +237,7 @@ class MapEntryImpl : public Base {
}
}
- size_t ByteSizeLong() const {
+ size_t ByteSizeLong() const override {
size_t size = 0;
size += has_key() ?
kTagSize + static_cast<size_t>(KeyTypeHandler::ByteSize(key())) : 0;
@@ -233,13 +246,13 @@ class MapEntryImpl : public Base {
return size;
}
- void SerializeWithCachedSizes(::google::protobuf::io::CodedOutputStream* output) const {
+ void SerializeWithCachedSizes(io::CodedOutputStream* output) const override {
KeyTypeHandler::Write(kKeyFieldNumber, key(), output);
ValueTypeHandler::Write(kValueFieldNumber, value(), output);
}
- ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
- ::google::protobuf::uint8* output) const {
+ ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
+ bool deterministic, ::google::protobuf::uint8* output) const override {
output = KeyTypeHandler::InternalWriteToArray(kKeyFieldNumber, key(),
deterministic, output);
output = ValueTypeHandler::InternalWriteToArray(kValueFieldNumber, value(),
@@ -249,7 +262,7 @@ class MapEntryImpl : public Base {
// Don't override SerializeWithCachedSizesToArray. Use MessageLite's.
- int GetCachedSize() const {
+ int GetCachedSize() const override {
int size = 0;
size += has_key()
? static_cast<int>(kTagSize) + KeyTypeHandler::GetCachedSize(key())
@@ -260,25 +273,20 @@ class MapEntryImpl : public Base {
return size;
}
- bool IsInitialized() const { return ValueTypeHandler::IsInitialized(value_); }
+ bool IsInitialized() const override {
+ return ValueTypeHandler::IsInitialized(value_);
+ }
- Base* New() const {
+ Base* New() const override {
Derived* entry = new Derived;
return entry;
}
- Base* New(Arena* arena) const {
+ Base* New(Arena* arena) const override {
Derived* entry = Arena::CreateMessage<Derived>(arena);
return entry;
}
- size_t SpaceUsedLong() const {
- size_t size = sizeof(Derived);
- size += KeyTypeHandler::SpaceUsedInMapEntryLong(key_);
- size += ValueTypeHandler::SpaceUsedInMapEntryLong(value_);
- return size;
- }
-
protected:
// We can't declare this function directly here as it would hide the other
// overload (const Message&).
@@ -298,7 +306,7 @@ class MapEntryImpl : public Base {
}
public:
- void Clear() {
+ void Clear() override {
KeyTypeHandler::Clear(&key_, GetArenaNoVirtual());
ValueTypeHandler::ClearMaybeByDefaultEnum(
&value_, GetArenaNoVirtual(), default_enum_value);
@@ -312,20 +320,18 @@ class MapEntryImpl : public Base {
ValueTypeHandler::AssignDefaultValue(&d->value_);
}
- Arena* GetArena() const {
- return GetArenaNoVirtual();
- }
+ Arena* GetArena() const override { return GetArenaNoVirtual(); }
- // Create a MapEntryImpl for given key and value from google::protobuf::Map in
+ // Create a MapEntryImpl for given key and value from 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.
+ // Map is enum. We cannot create a reference to int from an enum.
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
- // MapEntryImpl from google::protobuf::Map in serialization.
+ // MapEntryImpl from Map in serialization.
static Derived* Wrap(const Key& key, const Value& value, Arena* arena) {
return Arena::CreateMessage<MapEntryWrapper>(arena, key, value);
}
@@ -336,11 +342,14 @@ class MapEntryImpl : public Base {
class Parser {
public:
explicit Parser(MapField* mf) : mf_(mf), map_(mf->MutableMap()) {}
+ ~Parser() {
+ if (entry_ != nullptr && entry_->GetArena() == nullptr) delete entry_;
+ }
// This does what the typical MergePartialFromCodedStream() is expected to
// do, with the additional side-effect that if successful (i.e., if true is
// going to be its return value) it inserts the key-value pair into map_.
- bool MergePartialFromCodedStream(::google::protobuf::io::CodedInputStream* input) {
+ bool MergePartialFromCodedStream(io::CodedInputStream* input) {
// Look for the expected thing: a key and then a value. If it fails,
// invoke the enclosing class's MergePartialFromCodedStream, or return
// false if that would be pointless.
@@ -353,11 +362,11 @@ class MapEntryImpl : public Base {
int size;
input->GetDirectBufferPointerInline(&data, &size);
// We could use memcmp here, but we don't bother. The tag is one byte.
- GOOGLE_COMPILE_ASSERT(kTagSize == 1, tag_size_error);
+ static_assert(kTagSize == 1, "tag size must be 1");
if (size > 0 && *reinterpret_cast<const char*>(data) == kValueTag) {
typename Map::size_type map_size = map_->size();
value_ptr_ = &(*map_)[key_];
- if (GOOGLE_PREDICT_TRUE(map_size != map_->size())) {
+ if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) {
// We created a new key-value pair. Fill in the value.
typedef
typename MapIf<ValueTypeHandler::kIsEnum, int*, Value*>::type T;
@@ -375,19 +384,53 @@ class MapEntryImpl : public Base {
key_ = Key();
}
- entry_.reset(mf_->NewEntry());
+ NewEntry();
*entry_->mutable_key() = key_;
const bool result = entry_->MergePartialFromCodedStream(input);
if (result) UseKeyAndValueFromEntry();
- if (entry_->GetArena() != NULL) entry_.release();
return result;
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ bool ParseMap(const char* begin, const char* end) {
+ io::CodedInputStream input(reinterpret_cast<const uint8*>(begin),
+ end - begin);
+ return MergePartialFromCodedStream(&input) &&
+ input.ConsumedEntireMessage();
+ }
+ template <typename Metadata>
+ bool ParseMapEnumValidation(const char* begin, const char* end, uint32 num,
+ Metadata* metadata,
+ bool (*validate_enum)(int)) {
+ io::CodedInputStream input(reinterpret_cast<const uint8*>(begin),
+ end - begin);
+ auto entry = NewEntry();
+ // TODO(gerbens) implement _InternalParse for maps. We can't use
+ // ParseFromString as this will call _InternalParse
+ if (!(entry->MergePartialFromCodedStream(&input) &&
+ input.ConsumedEntireMessage()))
+ return false;
+ if (!validate_enum(entry->value())) {
+ auto unknown_fields = metadata->mutable_unknown_fields();
+ WriteLengthDelimited(num, StringPiece(begin, end - begin),
+ unknown_fields);
+ return true;
+ }
+ (*map_)[entry->key()] = static_cast<Value>(entry->value());
+ return true;
+ }
+#endif
+
+ MapEntryImpl* NewEntry() { return entry_ = mf_->NewEntry(); }
+
const Key& key() const { return key_; }
const Value& value() const { return *value_ptr_; }
+ const Key& entry_key() const { return entry_->key(); }
+ const Value& entry_value() const { return entry_->value(); }
+
private:
- void UseKeyAndValueFromEntry() GOOGLE_PROTOBUF_ATTRIBUTE_COLD {
+ void UseKeyAndValueFromEntry() PROTOBUF_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
@@ -404,8 +447,7 @@ class MapEntryImpl : public Base {
// After reading a key and value successfully, and inserting that data
// 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_PROTOBUF_ATTRIBUTE_COLD {
+ bool ReadBeyondKeyValuePair(io::CodedInputStream* input) PROTOBUF_COLD {
typedef MoveHelper<KeyTypeHandler::kIsEnum,
KeyTypeHandler::kIsMessage,
KeyTypeHandler::kWireType ==
@@ -416,13 +458,12 @@ class MapEntryImpl : public Base {
ValueTypeHandler::kWireType ==
WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
Value> ValueMover;
- entry_.reset(mf_->NewEntry());
+ NewEntry();
ValueMover::Move(value_ptr_, entry_->mutable_value());
map_->erase(key_);
KeyMover::Move(&key_, entry_->mutable_key());
const bool result = entry_->MergePartialFromCodedStream(input);
if (result) UseKeyAndValueFromEntry();
- if (entry_->GetArena() != NULL) entry_.release();
return result;
}
@@ -430,9 +471,7 @@ class MapEntryImpl : public Base {
Map* const map_;
Key key_;
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.
- std::unique_ptr<MapEntryImpl> entry_;
+ MapEntryImpl* entry_ = nullptr;
};
protected:
@@ -445,9 +484,9 @@ class MapEntryImpl : public Base {
private:
// Serializing a generated message containing map field involves serializing
- // key-value pairs from google::protobuf::Map. The wire format of each key-value pair
+ // key-value pairs from Map. The wire format of each key-value pair
// after serialization should be the same as that of a MapEntry message
- // containing the same key and value inside it. However, google::protobuf::Map doesn't
+ // containing the same key and value inside it. However, Map doesn't
// store key and value as MapEntry message, which disables us to use existing
// code to serialize message. In order to use existing code to serialize
// message, we need to construct a MapEntry from key-value pair. But it
@@ -466,14 +505,16 @@ class MapEntryImpl : public Base {
BaseClass::set_has_key();
BaseClass::set_has_value();
}
- inline const KeyMapEntryAccessorType& key() const { return key_; }
- inline const ValueMapEntryAccessorType& value() const { return value_; }
+ inline const KeyMapEntryAccessorType& key() const override { return key_; }
+ inline const ValueMapEntryAccessorType& value() const override {
+ return value_;
+ }
private:
const Key& key_;
const Value& value_;
- friend class ::google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
};
@@ -503,7 +544,7 @@ class MapEntryImpl : public Base {
const KeyMapEntryAccessorType& key_;
const ValueMapEntryAccessorType value_;
- friend class google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
typedef void DestructorSkippable_;
};
@@ -518,7 +559,7 @@ class MapEntryImpl : public Base {
uint32 _has_bits_[1];
private:
- friend class ::google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
template <typename C, typename K, typename V, WireFormatLite::FieldType,
@@ -602,20 +643,20 @@ struct FromHelper {
template <>
struct FromHelper<WireFormatLite::TYPE_STRING> {
- static ArenaStringPtr From(const string& x) {
+ static ArenaStringPtr From(const std::string& x) {
ArenaStringPtr res;
TaggedPtr<::std::string> ptr;
- ptr.Set(const_cast<string*>(&x));
+ ptr.Set(const_cast<std::string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
}
};
template <>
struct FromHelper<WireFormatLite::TYPE_BYTES> {
- static ArenaStringPtr From(const string& x) {
+ static ArenaStringPtr From(const std::string& x) {
ArenaStringPtr res;
TaggedPtr<::std::string> ptr;
- ptr.Set(const_cast<string*>(&x));
+ ptr.Set(const_cast<std::string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
}
@@ -666,6 +707,8 @@ struct MapEntryHelper<MapEntryLite<T, Key, Value, kKeyFieldType,
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
diff --git a/src/google/protobuf/map_field.cc b/src/google/protobuf/map_field.cc
index ac29c7e9..2ce54cb3 100644
--- a/src/google/protobuf/map_field.cc
+++ b/src/google/protobuf/map_field.cc
@@ -43,15 +43,13 @@ MapFieldBase::~MapFieldBase() {
const RepeatedPtrFieldBase& MapFieldBase::GetRepeatedField() const {
SyncRepeatedFieldWithMap();
- return *reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
- repeated_field_);
+ return *reinterpret_cast<RepeatedPtrFieldBase*>(repeated_field_);
}
RepeatedPtrFieldBase* MapFieldBase::MutableRepeatedField() {
SyncRepeatedFieldWithMap();
SetRepeatedDirty();
- return reinterpret_cast<::google::protobuf::internal::RepeatedPtrFieldBase*>(
- repeated_field_);
+ return reinterpret_cast<RepeatedPtrFieldBase*>(repeated_field_);
}
size_t MapFieldBase::SpaceUsedExcludingSelfLong() const {
@@ -179,12 +177,12 @@ bool DynamicMapField::InsertOrLookupMapValue(
// Allocate memory for the inserted MapValueRef, and initialize to
// default value.
switch (val_des->cpp_type()) {
-#define HANDLE_TYPE(CPPTYPE, TYPE) \
- case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \
- TYPE * value = new TYPE(); \
- map_val.SetValue(value); \
- break; \
- }
+#define HANDLE_TYPE(CPPTYPE, TYPE) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
+ TYPE* value = new TYPE(); \
+ map_val.SetValue(value); \
+ break; \
+ }
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
@@ -195,7 +193,7 @@ bool DynamicMapField::InsertOrLookupMapValue(
HANDLE_TYPE(STRING, string);
HANDLE_TYPE(ENUM, int32);
#undef HANDLE_TYPE
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message = default_entry_->GetReflection()->GetMessage(
*default_entry_, val_des);
Message* value = message.New();
@@ -245,6 +243,17 @@ void DynamicMapField::SetMapIteratorValue(MapIterator* map_iter) const {
map_iter->value_.CopyFrom(iter->second);
}
+void DynamicMapField::Swap(MapFieldBase* other) {
+ DynamicMapField* other_field = down_cast<DynamicMapField*>(other);
+ std::swap(this->MapFieldBase::repeated_field_, other_field->repeated_field_);
+ map_.swap(other_field->map_);
+ // a relaxed swap of the atomic
+ auto other_state = other_field->state_.load(std::memory_order_relaxed);
+ auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed);
+ other_field->state_.store(this_state, std::memory_order_relaxed);
+ this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed);
+}
+
void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const {
const Reflection* reflection = default_entry_->GetReflection();
const FieldDescriptor* key_des =
@@ -269,61 +278,61 @@ void DynamicMapField::SyncRepeatedFieldWithMapNoLock() const {
MapFieldBase::repeated_field_->AddAllocated(new_entry);
const MapKey& map_key = it->first;
switch (key_des->cpp_type()) {
- case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
+ case FieldDescriptor::CPPTYPE_STRING:
reflection->SetString(new_entry, key_des, map_key.GetStringValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
+ case FieldDescriptor::CPPTYPE_INT64:
reflection->SetInt64(new_entry, key_des, map_key.GetInt64Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
+ case FieldDescriptor::CPPTYPE_INT32:
reflection->SetInt32(new_entry, key_des, map_key.GetInt32Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
+ case FieldDescriptor::CPPTYPE_UINT64:
reflection->SetUInt64(new_entry, key_des, map_key.GetUInt64Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
+ case FieldDescriptor::CPPTYPE_UINT32:
reflection->SetUInt32(new_entry, key_des, map_key.GetUInt32Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
+ case FieldDescriptor::CPPTYPE_BOOL:
reflection->SetBool(new_entry, key_des, map_key.GetBoolValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
- case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
- case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Can't get here.";
break;
}
const MapValueRef& map_val = it->second;
switch (val_des->cpp_type()) {
- case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
+ case FieldDescriptor::CPPTYPE_STRING:
reflection->SetString(new_entry, val_des, map_val.GetStringValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
+ case FieldDescriptor::CPPTYPE_INT64:
reflection->SetInt64(new_entry, val_des, map_val.GetInt64Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
+ case FieldDescriptor::CPPTYPE_INT32:
reflection->SetInt32(new_entry, val_des, map_val.GetInt32Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
+ case FieldDescriptor::CPPTYPE_UINT64:
reflection->SetUInt64(new_entry, val_des, map_val.GetUInt64Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
+ case FieldDescriptor::CPPTYPE_UINT32:
reflection->SetUInt32(new_entry, val_des, map_val.GetUInt32Value());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
+ case FieldDescriptor::CPPTYPE_BOOL:
reflection->SetBool(new_entry, val_des, map_val.GetBoolValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_DOUBLE:
reflection->SetDouble(new_entry, val_des, map_val.GetDoubleValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_FLOAT:
reflection->SetFloat(new_entry, val_des, map_val.GetFloatValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_ENUM:
reflection->SetEnumValue(new_entry, val_des, map_val.GetEnumValue());
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message = map_val.GetMessageValue();
reflection->MutableMessage(new_entry, val_des)->CopyFrom(message);
break;
@@ -351,28 +360,28 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
it != MapFieldBase::repeated_field_->end(); ++it) {
MapKey map_key;
switch (key_des->cpp_type()) {
- case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
+ case FieldDescriptor::CPPTYPE_STRING:
map_key.SetStringValue(reflection->GetString(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
+ case FieldDescriptor::CPPTYPE_INT64:
map_key.SetInt64Value(reflection->GetInt64(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
+ case FieldDescriptor::CPPTYPE_INT32:
map_key.SetInt32Value(reflection->GetInt32(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
+ case FieldDescriptor::CPPTYPE_UINT64:
map_key.SetUInt64Value(reflection->GetUInt64(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
+ case FieldDescriptor::CPPTYPE_UINT32:
map_key.SetUInt32Value(reflection->GetUInt32(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
+ case FieldDescriptor::CPPTYPE_BOOL:
map_key.SetBoolValue(reflection->GetBool(*it, key_des));
break;
- case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
- case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
- case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Can't get here.";
break;
}
@@ -386,13 +395,13 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
MapValueRef& map_val = (*map)[map_key];
map_val.SetType(val_des->cpp_type());
switch (val_des->cpp_type()) {
-#define HANDLE_TYPE(CPPTYPE, TYPE, METHOD) \
- case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \
- TYPE * value = new TYPE; \
- *value = reflection->Get##METHOD(*it, val_des); \
- map_val.SetValue(value); \
- break; \
- }
+#define HANDLE_TYPE(CPPTYPE, TYPE, METHOD) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
+ TYPE* value = new TYPE; \
+ *value = reflection->Get##METHOD(*it, val_des); \
+ map_val.SetValue(value); \
+ break; \
+ }
HANDLE_TYPE(INT32, int32, Int32);
HANDLE_TYPE(INT64, int64, Int64);
HANDLE_TYPE(UINT32, uint32, UInt32);
@@ -403,7 +412,7 @@ void DynamicMapField::SyncMapWithRepeatedFieldNoLock() const {
HANDLE_TYPE(STRING, string, String);
HANDLE_TYPE(ENUM, int32, EnumValue);
#undef HANDLE_TYPE
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
const Message& message = reflection->GetMessage(*it, val_des);
Message* value = message.New();
value->CopyFrom(message);
@@ -426,16 +435,16 @@ size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
size += sizeof(it->first) * map_size;
size += sizeof(it->second) * map_size;
// If key is string, add the allocated space.
- if (it->first.type() == google::protobuf::FieldDescriptor::CPPTYPE_STRING) {
+ if (it->first.type() == FieldDescriptor::CPPTYPE_STRING) {
size += sizeof(string) * map_size;
}
// Add the allocated space in MapValueRef.
switch (it->second.type()) {
-#define HANDLE_TYPE(CPPTYPE, TYPE) \
- case google::protobuf::FieldDescriptor::CPPTYPE_##CPPTYPE: { \
- size += sizeof(TYPE) * map_size; \
- break; \
- }
+#define HANDLE_TYPE(CPPTYPE, TYPE) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
+ size += sizeof(TYPE) * map_size; \
+ break; \
+ }
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
@@ -446,7 +455,7 @@ size_t DynamicMapField::SpaceUsedExcludingSelfNoLock() const {
HANDLE_TYPE(STRING, string);
HANDLE_TYPE(ENUM, int32);
#undef HANDLE_TYPE
- case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
while (it != map_.end()) {
const Message& message = it->second.GetMessageValue();
size += message.GetReflection()->SpaceUsedLong(message);
diff --git a/src/google/protobuf/map_field.h b/src/google/protobuf/map_field.h
index 494401e1..38dd35d9 100644
--- a/src/google/protobuf/map_field.h
+++ b/src/google/protobuf/map_field.h
@@ -33,23 +33,30 @@
#include <atomic>
-#include <google/protobuf/stubs/mutex.h>
-#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/generated_message_reflection.h>
#include <google/protobuf/map_entry.h>
#include <google/protobuf/map_field_lite.h>
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/stubs/mutex.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/unknown_field_set.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
class DynamicMessage;
class MapKey;
+class MapIterator;
namespace internal {
class ContendedMapCleanTest;
@@ -59,7 +66,7 @@ class MapFieldAccessor;
// This class provides access to map field using reflection, which is the same
// as those provided for RepeatedPtrField<Message>. It is used for internal
// reflection implentation only. Users should never use this directly.
-class LIBPROTOBUF_EXPORT MapFieldBase {
+class PROTOBUF_EXPORT MapFieldBase {
public:
MapFieldBase()
: arena_(NULL),
@@ -76,7 +83,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
virtual ~MapFieldBase();
// Returns reference to internal repeated field. Data written using
- // google::protobuf::Map's api prior to calling this function is guarantted to be
+ // Map's api prior to calling this function is guarantted to be
// included in repeated field.
const RepeatedPtrFieldBase& GetRepeatedField() const;
@@ -96,6 +103,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
const MapIterator& b) const = 0;
virtual void MapBegin(MapIterator* map_iter) const = 0;
virtual void MapEnd(MapIterator* map_iter) const = 0;
+ virtual void Swap(MapFieldBase* other) = 0;
// Sync Map with repeated field and returns the size of map.
virtual int size() const = 0;
@@ -141,7 +149,7 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
Arena* arena_;
mutable RepeatedPtrField<Message>* repeated_field_;
- mutable Mutex mutex_; // The thread to synchronize map and repeated field
+ mutable internal::WrappedMutex mutex_; // The thread to synchronize map and repeated field
// needs to get lock first;
mutable std::atomic<State> state_;
@@ -149,13 +157,13 @@ class LIBPROTOBUF_EXPORT MapFieldBase {
friend class ContendedMapCleanTest;
friend class GeneratedMessageReflection;
friend class MapFieldAccessor;
- friend class ::google::protobuf::DynamicMessage;
+ friend class DynamicMessage;
// Virtual helper methods for MapIterator. MapIterator doesn't have the
// type helper for key and value. Call these help methods to deal with
// different types. Real helper methods are implemented in
// TypeDefinedMapFieldBase.
- friend class ::google::protobuf::MapIterator;
+ friend class ::PROTOBUF_NAMESPACE_ID::MapIterator;
// Allocate map<...>::iterator for MapIterator.
virtual void InitializeIterator(MapIterator* map_iter) const = 0;
@@ -181,10 +189,10 @@ class TypeDefinedMapFieldBase : public MapFieldBase {
public:
TypeDefinedMapFieldBase() {}
explicit TypeDefinedMapFieldBase(Arena* arena) : MapFieldBase(arena) {}
- ~TypeDefinedMapFieldBase() {}
- void MapBegin(MapIterator* map_iter) const;
- void MapEnd(MapIterator* map_iter) const;
- bool EqualIterator(const MapIterator& a, const MapIterator& b) const;
+ ~TypeDefinedMapFieldBase() override {}
+ void MapBegin(MapIterator* map_iter) const override;
+ void MapEnd(MapIterator* map_iter) const override;
+ bool EqualIterator(const MapIterator& a, const MapIterator& b) const override;
virtual const Map<Key, T>& GetMap() const = 0;
virtual Map<Key, T>* MutableMap() = 0;
@@ -194,11 +202,11 @@ class TypeDefinedMapFieldBase : public MapFieldBase {
const MapIterator* map_iter) const;
private:
- void InitializeIterator(MapIterator* map_iter) const;
- void DeleteIterator(MapIterator* map_iter) const;
+ void InitializeIterator(MapIterator* map_iter) const override;
+ void DeleteIterator(MapIterator* map_iter) const override;
void CopyIterator(MapIterator* this_iteratorm,
- const MapIterator& that_iterator) const;
- void IncreaseIterator(MapIterator* map_iter) const;
+ const MapIterator& that_iterator) const override;
+ void IncreaseIterator(MapIterator* map_iter) const override;
virtual void SetMapIteratorValue(MapIterator* map_iter) const = 0;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeDefinedMapFieldBase);
@@ -228,7 +236,7 @@ class MapField : public TypeDefinedMapFieldBase<Key, T> {
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
+ // different exposed type in Map's api and repeated field's api. For
// details see the comment in the implementation of
// SyncMapWithRepeatedFieldNoLock.
static const bool kIsValueEnum = ValueTypeHandler::kIsEnum;
@@ -243,16 +251,16 @@ class MapField : public TypeDefinedMapFieldBase<Key, T> {
: 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);
+ bool ContainsMapKey(const MapKey& map_key) const override;
+ bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
+ bool DeleteMapValue(const MapKey& map_key) override;
- const Map<Key, T>& GetMap() const {
+ const Map<Key, T>& GetMap() const override {
MapFieldBase::SyncMapWithRepeatedField();
return impl_.GetMap();
}
- Map<Key, T>* MutableMap() {
+ Map<Key, T>* MutableMap() override {
MapFieldBase::SyncMapWithRepeatedField();
Map<Key, T>* result = impl_.MutableMap();
MapFieldBase::SetMapDirty();
@@ -260,10 +268,10 @@ class MapField : public TypeDefinedMapFieldBase<Key, T> {
}
// Convenient methods for generated message implementation.
- int size() const;
+ int size() const override;
void Clear();
void MergeFrom(const MapField& other);
- void Swap(MapField* other);
+ void Swap(MapFieldBase* other) override;
// Used in the implementation of parsing. Caller should take the ownership iff
// arena_ is NULL.
@@ -286,13 +294,13 @@ class MapField : public TypeDefinedMapFieldBase<Key, T> {
typedef void DestructorSkippable_;
// Implements MapFieldBase
- void SyncRepeatedFieldWithMapNoLock() const;
- void SyncMapWithRepeatedFieldNoLock() const;
- size_t SpaceUsedExcludingSelfNoLock() const;
+ void SyncRepeatedFieldWithMapNoLock() const override;
+ void SyncMapWithRepeatedFieldNoLock() const override;
+ size_t SpaceUsedExcludingSelfNoLock() const override;
- void SetMapIteratorValue(MapIterator* map_iter) const;
+ void SetMapIteratorValue(MapIterator* map_iter) const override;
- friend class ::google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
friend class MapFieldStateTest; // For testing, it needs raw access to impl_
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapField);
};
@@ -307,31 +315,33 @@ struct MapEntryToMapField<MapEntry<T, Key, Value, kKeyFieldType,
MapFieldType;
};
-class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey, MapValueRef> {
+class PROTOBUF_EXPORT DynamicMapField
+ : public TypeDefinedMapFieldBase<MapKey, MapValueRef> {
public:
explicit DynamicMapField(const Message* default_entry);
DynamicMapField(const Message* default_entry, Arena* arena);
- ~DynamicMapField();
+ ~DynamicMapField() override;
// Implement MapFieldBase
- bool ContainsMapKey(const MapKey& map_key) const;
- bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val);
- bool DeleteMapValue(const MapKey& map_key);
+ bool ContainsMapKey(const MapKey& map_key) const override;
+ bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) override;
+ bool DeleteMapValue(const MapKey& map_key) override;
+ void Swap(MapFieldBase* other) override;
- const Map<MapKey, MapValueRef>& GetMap() const;
- Map<MapKey, MapValueRef>* MutableMap();
+ const Map<MapKey, MapValueRef>& GetMap() const override;
+ Map<MapKey, MapValueRef>* MutableMap() override;
- int size() const;
+ int size() const override;
private:
Map<MapKey, MapValueRef> map_;
const Message* default_entry_;
// Implements MapFieldBase
- void SyncRepeatedFieldWithMapNoLock() const;
- void SyncMapWithRepeatedFieldNoLock() const;
- size_t SpaceUsedExcludingSelfNoLock() const;
- void SetMapIteratorValue(MapIterator* map_iter) const;
+ void SyncRepeatedFieldWithMapNoLock() const override;
+ void SyncMapWithRepeatedFieldNoLock() const override;
+ size_t SpaceUsedExcludingSelfNoLock() const override;
+ void SetMapIteratorValue(MapIterator* map_iter) const override;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMapField);
};
@@ -350,7 +360,7 @@ class LIBPROTOBUF_EXPORT DynamicMapField: public TypeDefinedMapFieldBase<MapKey,
// MapKey is an union type for representing any possible
// map key.
-class LIBPROTOBUF_EXPORT MapKey {
+class PROTOBUF_EXPORT MapKey {
public:
MapKey() : type_(0) {
}
@@ -398,7 +408,7 @@ class LIBPROTOBUF_EXPORT MapKey {
SetType(FieldDescriptor::CPPTYPE_BOOL);
val_.bool_value_ = value;
}
- void SetStringValue(const string& val) {
+ void SetStringValue(const std::string& val) {
SetType(FieldDescriptor::CPPTYPE_STRING);
*val_.string_value_ = val;
}
@@ -428,7 +438,7 @@ class LIBPROTOBUF_EXPORT MapKey {
"MapKey::GetBoolValue");
return val_.bool_value_;
}
- const string& GetStringValue() const {
+ const std::string& GetStringValue() const {
TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
"MapKey::GetStringValue");
return *val_.string_value_;
@@ -525,12 +535,12 @@ class LIBPROTOBUF_EXPORT MapKey {
private:
template <typename K, typename V>
friend class internal::TypeDefinedMapFieldBase;
- friend class MapIterator;
+ friend class ::PROTOBUF_NAMESPACE_ID::MapIterator;
friend class internal::DynamicMapField;
union KeyValue {
KeyValue() {}
- string* string_value_;
+ std::string* string_value_;
int64 int64_value_;
int32 int32_value_;
uint64 uint64_value_;
@@ -545,7 +555,7 @@ class LIBPROTOBUF_EXPORT MapKey {
}
type_ = type;
if (type_ == FieldDescriptor::CPPTYPE_STRING) {
- val_.string_value_ = new string;
+ val_.string_value_ = new std::string;
}
}
@@ -554,7 +564,7 @@ class LIBPROTOBUF_EXPORT MapKey {
};
// MapValueRef points to a map value.
-class LIBPROTOBUF_EXPORT MapValueRef {
+class PROTOBUF_EXPORT MapValueRef {
public:
MapValueRef() : data_(NULL), type_(0) {}
@@ -589,10 +599,10 @@ class LIBPROTOBUF_EXPORT MapValueRef {
"MapValueRef::SetEnumValue");
*reinterpret_cast<int*>(data_) = value;
}
- void SetStringValue(const string& value) {
+ void SetStringValue(const std::string& value) {
TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
"MapValueRef::SetStringValue");
- *reinterpret_cast<string*>(data_) = value;
+ *reinterpret_cast<std::string*>(data_) = value;
}
void SetFloatValue(float value) {
TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
@@ -635,10 +645,10 @@ class LIBPROTOBUF_EXPORT MapValueRef {
"MapValueRef::GetEnumValue");
return *reinterpret_cast<int*>(data_);
}
- const string& GetStringValue() const {
+ const std::string& GetStringValue() const {
TYPE_CHECK(FieldDescriptor::CPPTYPE_STRING,
"MapValueRef::GetStringValue");
- return *reinterpret_cast<string*>(data_);
+ return *reinterpret_cast<std::string*>(data_);
}
float GetFloatValue() const {
TYPE_CHECK(FieldDescriptor::CPPTYPE_FLOAT,
@@ -671,7 +681,7 @@ class LIBPROTOBUF_EXPORT MapValueRef {
friend class internal::MapField;
template <typename K, typename V>
friend class internal::TypeDefinedMapFieldBase;
- friend class MapIterator;
+ friend class ::PROTOBUF_NAMESPACE_ID::MapIterator;
friend class internal::GeneratedMessageReflection;
friend class internal::DynamicMapField;
@@ -697,11 +707,11 @@ class LIBPROTOBUF_EXPORT MapValueRef {
// 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; \
- }
+#define HANDLE_TYPE(CPPTYPE, TYPE) \
+ case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
+ delete reinterpret_cast<TYPE*>(data_); \
+ break; \
+ }
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
@@ -709,7 +719,7 @@ class LIBPROTOBUF_EXPORT MapValueRef {
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
- HANDLE_TYPE(STRING, string);
+ HANDLE_TYPE(STRING, std::string);
HANDLE_TYPE(ENUM, int32);
HANDLE_TYPE(MESSAGE, Message);
#undef HANDLE_TYPE
@@ -720,12 +730,11 @@ class LIBPROTOBUF_EXPORT MapValueRef {
void* data_;
// type_ is 0 or a valid FieldDescriptor::CppType.
int type_;
- GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapValueRef);
};
#undef TYPE_CHECK
-class LIBPROTOBUF_EXPORT MapIterator {
+class PROTOBUF_EXPORT MapIterator {
public:
MapIterator(Message* message, const FieldDescriptor* field) {
const Reflection* reflection = message->GetReflection();
@@ -801,39 +810,39 @@ class LIBPROTOBUF_EXPORT MapIterator {
} // namespace google
GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START
-template<>
-struct hash<google::protobuf::MapKey> {
- size_t
- operator()(const google::protobuf::MapKey& map_key) const {
+template <>
+struct hash<::PROTOBUF_NAMESPACE_ID::MapKey> {
+ size_t operator()(const ::PROTOBUF_NAMESPACE_ID::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:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_DOUBLE:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_FLOAT:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_ENUM:
+ case ::PROTOBUF_NAMESPACE_ID::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:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_STRING:
+ return hash<std::string>()(map_key.GetStringValue());
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT64:
return hash<::google::protobuf::int64>()(map_key.GetInt64Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_INT32:
return hash<::google::protobuf::int32>()(map_key.GetInt32Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT64:
return hash<::google::protobuf::uint64>()(map_key.GetUInt64Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
+ case ::PROTOBUF_NAMESPACE_ID::FieldDescriptor::CPPTYPE_UINT32:
return hash<::google::protobuf::uint32>()(map_key.GetUInt32Value());
- case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
+ case ::PROTOBUF_NAMESPACE_ID::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 {
+ bool operator()(const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key1,
+ const ::PROTOBUF_NAMESPACE_ID::MapKey& map_key2) const {
return map_key1 < map_key2;
}
};
GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END
+#include <google/protobuf/port_undef.inc>
+
#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 d0517792..0e78342c 100644
--- a/src/google/protobuf/map_field_inl.h
+++ b/src/google/protobuf/map_field_inl.h
@@ -38,6 +38,10 @@
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_type_handler.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -65,7 +69,7 @@ inline bool UnwrapMapKey<bool>(const MapKey& map_key) {
return map_key.GetBoolValue();
}
template<>
-inline string UnwrapMapKey<string>(const MapKey& map_key) {
+inline std::string UnwrapMapKey<std::string>(const MapKey& map_key) {
return map_key.GetStringValue();
}
@@ -93,7 +97,7 @@ inline void SetMapKey<bool>(MapKey* map_key, const bool& value) {
map_key->SetBoolValue(value);
}
template<>
-inline void SetMapKey<string>(MapKey* map_key, const string& value) {
+inline void SetMapKey<std::string>(MapKey* map_key, const std::string& value) {
map_key->SetStringValue(value);
}
@@ -249,13 +253,14 @@ template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType kKeyFieldType,
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_);
+ default_enum_value>::Swap(MapFieldBase* other) {
+ MapField* other_field = down_cast<MapField*>(other);
+ std::swap(this->MapFieldBase::repeated_field_, other_field->repeated_field_);
+ impl_.Swap(&other_field->impl_);
// a relaxed swap of the atomic
- auto other_state = other->state_.load(std::memory_order_relaxed);
+ auto other_state = other_field->state_.load(std::memory_order_relaxed);
auto this_state = this->MapFieldBase::state_.load(std::memory_order_relaxed);
- other->state_.store(this_state, std::memory_order_relaxed);
+ other_field->state_.store(this_state, std::memory_order_relaxed);
this->MapFieldBase::state_.store(other_state, std::memory_order_relaxed);
}
@@ -338,6 +343,6 @@ size_t MapField<Derived, Key, T, kKeyFieldType, kValueFieldType,
}
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_MAP_FIELD_INL_H__
diff --git a/src/google/protobuf/map_field_lite.h b/src/google/protobuf/map_field_lite.h
index f648b430..5b8d2e48 100644
--- a/src/google/protobuf/map_field_lite.h
+++ b/src/google/protobuf/map_field_lite.h
@@ -31,10 +31,19 @@
#ifndef GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
#define GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
+#include <type_traits>
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_entry_lite.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -105,7 +114,7 @@ class MapFieldLite {
Arena* arena_;
Map<Key, T> map_;
- friend class ::google::protobuf::Arena;
+ friend class ::PROTOBUF_NAMESPACE_ID::Arena;
};
// True if IsInitialized() is true for value field in all elements of t. T is
@@ -138,6 +147,8 @@ struct MapEntryToMapField<MapEntryLite<T, Key, Value, kKeyFieldType,
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc
index f58d59e5..dcfcca76 100644
--- a/src/google/protobuf/map_field_test.cc
+++ b/src/google/protobuf/map_field_test.cc
@@ -30,22 +30,23 @@
#include <map>
#include <memory>
+#include <unordered_map>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/map.h>
#include <google/protobuf/arena_test_util.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/unittest.pb.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/map.h>
#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <gtest/gtest.h>
-namespace google {
+namespace google {
namespace protobuf {
namespace internal {
@@ -95,6 +96,7 @@ class MapFieldBaseStub : public MapFieldBase {
int size() const { return 0; }
void MapBegin(MapIterator* map_iter) const {}
void MapEnd(MapIterator* map_iter) const {}
+ void Swap(MapFieldBase* other) {}
void InitializeIterator(MapIterator* map_iter) const {}
void DeleteIterator(MapIterator* map_iter) const {}
void CopyIterator(MapIterator* this_iterator,
diff --git a/src/google/protobuf/map_lite_test_util.h b/src/google/protobuf/map_lite_test_util.h
index 66dedde5..573de7b2 100644
--- a/src/google/protobuf/map_lite_test_util.h
+++ b/src/google/protobuf/map_lite_test_util.h
@@ -75,6 +75,6 @@ class MapLiteTestUtil {
};
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_MAP_LITE_TEST_UTIL_H__
diff --git a/src/google/protobuf/map_test.cc b/src/google/protobuf/map_test.cc
index 829a60ff..080b9dfc 100644
--- a/src/google/protobuf/map_test.cc
+++ b/src/google/protobuf/map_test.cc
@@ -37,14 +37,13 @@
#endif // _WIN32
#include <algorithm>
-#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#include <set>
#include <sstream>
+#include <unordered_map>
#include <vector>
-#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
@@ -54,6 +53,7 @@
#include <google/protobuf/map_test_util.h>
#include <google/protobuf/map_unittest.pb.h>
#include <google/protobuf/test_util.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/tokenizer.h>
@@ -76,19 +76,23 @@
#include <gmock/gmock.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/casts.h>
-namespace google {
-using google::protobuf::unittest::ForeignMessage;
-using google::protobuf::unittest::TestAllTypes;
-using google::protobuf::unittest::TestMap;
-using google::protobuf::unittest::TestRecursiveMapMessage;
+#include <google/protobuf/port_def.inc>
+namespace google {
namespace protobuf {
+
+using unittest::ForeignMessage;
+using unittest::TestAllTypes;
+using unittest::TestMap;
+using unittest::TestRecursiveMapMessage;
+
namespace internal {
void MapTestForceDeterministic() {
- ::google::protobuf::io::CodedOutputStream::SetDefaultSerializationDeterministic();
+ io::CodedOutputStream::SetDefaultSerializationDeterministic();
}
// Map API Test =====================================================
@@ -309,8 +313,8 @@ static int64 median(Iterator i0, Iterator i1) {
}
static int64 Now() {
- return google::protobuf::util::TimeUtil::TimestampToNanoseconds(
- google::protobuf::util::TimeUtil::GetCurrentTime());
+ return util::TimeUtil::TimestampToNanoseconds(
+ util::TimeUtil::GetCurrentTime());
}
// Arbitrary odd integers for creating test data.
@@ -505,8 +509,8 @@ static void StressTestIterators(int n) {
ASSERT_EQ(n, m.size());
// Create maps of pointers and iterators.
// These should remain valid even if we modify m.
- hash_map<int, Map<int, int>::value_type*> mp(n);
- hash_map<int, Map<int, int>::iterator> mi(n);
+ std::unordered_map<int, Map<int, int>::value_type*> mp(n);
+ std::unordered_map<int, Map<int, int>::iterator> mi(n);
for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
mp[it->first] = &*it;
mi[it->first] = it;
@@ -868,7 +872,7 @@ TEST_F(MapImplTest, Assigner) {
EXPECT_TRUE(other.find(key_other) == other.end());
// Self assign
- other = other;
+ other = *&other; // Avoid -Wself-assign.
EXPECT_EQ(2, other.size());
EXPECT_EQ(value1, other.at(key1));
EXPECT_EQ(value2, other.at(key2));
@@ -895,8 +899,8 @@ TEST_F(MapImplTest, EqualRange) {
int key = 100, key_missing = 101;
map_[key] = 100;
- std::pair<google::protobuf::Map<int32, int32>::iterator,
- google::protobuf::Map<int32, int32>::iterator> range = map_.equal_range(key);
+ std::pair<Map<int32, int32>::iterator, Map<int32, int32>::iterator> range =
+ map_.equal_range(key);
EXPECT_TRUE(map_.find(key) == range.first);
EXPECT_TRUE(++map_.find(key) == range.second);
@@ -904,9 +908,9 @@ TEST_F(MapImplTest, EqualRange) {
EXPECT_TRUE(map_.end() == range.first);
EXPECT_TRUE(map_.end() == range.second);
- std::pair<google::protobuf::Map<int32, int32>::const_iterator,
- google::protobuf::Map<int32, int32>::const_iterator> const_range =
- const_map_.equal_range(key);
+ std::pair<Map<int32, int32>::const_iterator,
+ Map<int32, int32>::const_iterator>
+ const_range = const_map_.equal_range(key);
EXPECT_TRUE(const_map_.find(key) == const_range.first);
EXPECT_TRUE(++const_map_.find(key) == const_range.second);
@@ -1436,7 +1440,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
// Test iterators.
{
int index = 0;
- hash_map<int32, int32> result;
+ std::unordered_map<int32, int32> result;
for (RepeatedFieldRef<Message>::iterator it = mf_int32_int32.begin();
it != mf_int32_int32.end(); ++it) {
const Message& message = *it;
@@ -1448,7 +1452,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
++index;
}
EXPECT_EQ(10, index);
- for (hash_map<int32, int32>::const_iterator it = result.begin();
+ for (std::unordered_map<int32, int32>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_int32_int32().at(it->first), it->second);
}
@@ -1456,7 +1460,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
{
int index = 0;
- hash_map<int32, double> result;
+ std::unordered_map<int32, double> result;
for (RepeatedFieldRef<Message>::iterator it = mf_int32_double.begin();
it != mf_int32_double.end(); ++it) {
const Message& message = *it;
@@ -1468,7 +1472,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
++index;
}
EXPECT_EQ(10, index);
- for (hash_map<int32, double>::const_iterator it = result.begin();
+ for (std::unordered_map<int32, double>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_int32_double().at(it->first), it->second);
}
@@ -1476,7 +1480,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
{
int index = 0;
- hash_map<string, string> result;
+ std::unordered_map<string, string> result;
for (RepeatedFieldRef<Message>::iterator it = mf_string_string.begin();
it != mf_string_string.end(); ++it) {
const Message& message = *it;
@@ -1488,7 +1492,7 @@ TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
++index;
}
EXPECT_EQ(10, index);
- for (hash_map<string, string>::const_iterator it = result.begin();
+ for (std::unordered_map<string, string>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_string_string().at(it->first), it->second);
}
@@ -1975,8 +1979,7 @@ TEST(GeneratedMapFieldTest, CopyAssignmentOperator) {
MapTestUtil::ExpectMapFieldsSet(message2);
}
-#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
- !defined(GOOGLE_PROTOBUF_NO_RTTI)
+#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI
TEST(GeneratedMapFieldTest, UpcastCopyFrom) {
// Test the CopyFrom method that takes in the generic const Message&
// parameter.
@@ -1984,7 +1987,7 @@ TEST(GeneratedMapFieldTest, UpcastCopyFrom) {
MapTestUtil::SetMapFields(&message1);
- const Message* source = implicit_cast<const Message*>(&message1);
+ const Message* source = ::google::protobuf::implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
MapTestUtil::ExpectMapFieldsSet(message2);
@@ -2116,7 +2119,7 @@ TEST(GeneratedMapFieldTest, SerializationToArray) {
MapTestUtil::SetMapFields(&message1);
int size = message1.ByteSize();
data.resize(size);
- uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
+ uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
@@ -2132,7 +2135,7 @@ TEST(GeneratedMapFieldTest, SerializationToStream) {
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
- io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
@@ -2204,6 +2207,7 @@ TEST(GeneratedMapFieldTest, UnorderedWireFormat) {
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(2), message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
@@ -2279,10 +2283,21 @@ TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) {
wire_format.push_back(c);
if (is_key) expected_key = static_cast<int>(c);
if (is_value) expected_value = static_cast<int>(c);
- ASSERT_TRUE(message.ParseFromString(wire_format));
- ASSERT_EQ(1, message.map_int32_int32().size());
- ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first);
- ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second);
+ bool res = message.ParseFromString(wire_format);
+ bool expect_success = true;
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ // Unfortunately the old map parser accepts malformed input, the new
+ // parser accepts only correct input.
+ if (j != items - 1) expect_success = false;
+#endif
+ if (expect_success) {
+ ASSERT_TRUE(res);
+ ASSERT_EQ(1, message.map_int32_int32().size());
+ ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first);
+ ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second);
+ } else {
+ ASSERT_FALSE(res);
+ }
}
}
}
@@ -2307,6 +2322,7 @@ TEST(GeneratedMapFieldTest, MissedKeyWireFormat) {
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(0), message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(0));
}
@@ -2318,6 +2334,7 @@ TEST(GeneratedMapFieldTest, MissedValueWireFormat) {
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
+ ASSERT_NE(message.map_int32_int32().find(1), message.map_int32_int32().end());
EXPECT_EQ(0, message.map_int32_int32().at(1));
}
@@ -2330,7 +2347,7 @@ TEST(GeneratedMapFieldTest, MissedValueTextFormat) {
" key: 1234567890\n"
"}";
- EXPECT_TRUE(google::protobuf::TextFormat::ParseFromString(text, &message));
+ EXPECT_TRUE(TextFormat::ParseFromString(text, &message));
EXPECT_EQ(1, message.map_int32_foreign_message().size());
EXPECT_EQ(11, message.ByteSize());
}
@@ -3041,7 +3058,7 @@ static string DeterministicSerializationWithSerializePartialToCodedStream(
const T& t) {
const int size = t.ByteSize();
string result(size, '\0');
- io::ArrayOutputStream array_stream(string_as_array(&result), size);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializePartialToCodedStream(&output_stream);
@@ -3054,7 +3071,7 @@ template <typename T>
static string DeterministicSerializationWithSerializeToCodedStream(const T& t) {
const int size = t.ByteSize();
string result(size, '\0');
- io::ArrayOutputStream array_stream(string_as_array(&result), size);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializeToCodedStream(&output_stream);
@@ -3067,7 +3084,7 @@ template <typename T>
static string DeterministicSerialization(const T& t) {
const int size = t.ByteSize();
string result(size, '\0');
- io::ArrayOutputStream array_stream(string_as_array(&result), size);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializeWithCachedSizes(&output_stream);
@@ -3084,13 +3101,13 @@ static void TestDeterministicSerialization(const protobuf_unittest::TestMaps& t,
const string& filename) {
string expected;
GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() + "/google/protobuf/testdata/" + filename,
+ TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename),
&expected, true));
const string actual = DeterministicSerialization(t);
EXPECT_EQ(expected, actual);
protobuf_unittest::TestMaps u;
EXPECT_TRUE(u.ParseFromString(actual));
- EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals(u, t));
+ EXPECT_TRUE(util::MessageDifferencer::Equals(u, t));
}
// Helper for MapSerializationTest. Return a 7-bit ASCII string.
@@ -3146,7 +3163,7 @@ TEST(MapSerializationTest, DeterministicSubmessage) {
const string filename = "golden_message_maps";
string golden;
GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() + "/google/protobuf/testdata/" + filename,
+ TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename),
&golden, true));
t.ParseFromString(golden);
*(p.mutable_m()) = t;
@@ -3177,18 +3194,35 @@ TEST(TextFormatMapTest, SerializeAndParse) {
MapTestUtil::ExpectMapFieldsSet(dest);
}
+TEST(TextFormatMapTest, DynamicMessage) {
+ TestMap prototype;
+ DynamicMessageFactory factory;
+ std::unique_ptr<Message> message(
+ factory.GetPrototype(prototype.GetDescriptor())->New());
+ MapReflectionTester tester(message->GetDescriptor());
+ tester.SetMapFieldsViaReflection(message.get());
+
+ string expected_text;
+ GOOGLE_CHECK_OK(File::GetContents(
+ TestUtil::GetTestDataPath("net/proto2/internal/"
+ "testdata/map_test_data.txt"),
+ &expected_text, true));
+
+ EXPECT_EQ(message->DebugString(), expected_text);
+}
+
TEST(TextFormatMapTest, Sorted) {
unittest::TestMap message;
MapReflectionTester tester(message.GetDescriptor());
tester.SetMapFieldsViaReflection(&message);
string expected_text;
- GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() +
- "/google/protobuf/"
- "testdata/map_test_data.txt",
- &expected_text, true));
+ GOOGLE_CHECK_OK(
+ File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/"
+ "testdata/map_test_data.txt"),
+ &expected_text, true));
+ CleanStringLineEndings(&expected_text, false);
EXPECT_EQ(message.DebugString(), expected_text);
// Test again on the reverse order.
@@ -3200,16 +3234,88 @@ TEST(TextFormatMapTest, Sorted) {
TEST(TextFormatMapTest, ParseCorruptedString) {
string serialized_message;
- GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() +
- "/google/protobuf/testdata/golden_message_maps",
- &serialized_message, true));
+ GOOGLE_CHECK_OK(
+ File::GetContents(TestUtil::GetTestDataPath(
+ "net/proto2/internal/testdata/golden_message_maps"),
+ &serialized_message, true));
protobuf_unittest::TestMaps message;
GOOGLE_CHECK(message.ParseFromString(serialized_message));
TestParseCorruptedString<protobuf_unittest::TestMaps, true>(message);
TestParseCorruptedString<protobuf_unittest::TestMaps, false>(message);
}
+// Previously, serializing to text format will disable iterator from generated
+// API. Now, the iterator can be still used even after serializing to text
+// format.
+TEST(TextFormatMapTest, NoDisableIterator) {
+ unittest::TestMap source;
+ (*source.mutable_map_int32_int32())[1] = 1;
+
+ // Get iterator.
+ Map<int32, int32>::iterator iter =
+ source.mutable_map_int32_int32()->find(1);
+
+ // Serialize message to text format, which will invalidate the previous
+ // iterator previously.
+ string output;
+ TextFormat::Printer printer;
+ printer.PrintToString(source, &output);
+
+ // Modify map via the iterator (invalidated in prvious implementation.).
+ iter->second = 2;
+
+ // In previous implementation, the new change won't be reflected in text
+ // format, because the previous iterator has been invalidated.
+ output.clear();
+ printer.PrintToString(source, &output);
+ string expected =
+ "map_int32_int32 {\n"
+ " key: 1\n"
+ " value: 2\n"
+ "}\n";
+ EXPECT_EQ(output, expected);
+}
+
+// Previously, serializing to text format will disable iterator from reflection
+// API.
+TEST(TextFormatMapTest, NoDisableReflectionIterator) {
+ unittest::TestMap source;
+ (*source.mutable_map_int32_int32())[1] = 1;
+
+ // Get iterator. This will also sync internal repeated field with map inside
+ // of MapField.
+ const Reflection* reflection = source.GetReflection();
+ const FieldDescriptor* field_desc =
+ source.GetDescriptor()->FindFieldByName("map_int32_int32");
+ RepeatedPtrField<Message>* map_field =
+ reflection->MutableRepeatedPtrField<Message>(&source, field_desc);
+ RepeatedPtrField<Message>::iterator iter = map_field->begin();
+
+ // Serialize message to text format, which will invalidate the prvious
+ // iterator previously.
+ string output;
+ TextFormat::Printer printer;
+ printer.PrintToString(source, &output);
+
+ // Modify map via the iterator (invalidated in prvious implementation.).
+ const Reflection* map_entry_reflection = iter->GetReflection();
+ const FieldDescriptor* value_field_desc =
+ iter->GetDescriptor()->FindFieldByName("value");
+ map_entry_reflection->SetInt32(&(*iter), value_field_desc, 2);
+ GOOGLE_LOG(INFO) << iter->DebugString();
+
+ // In previous implementation, the new change won't be reflected in text
+ // format, because the previous iterator has been invalidated.
+ output.clear();
+ printer.PrintToString(source, &output);
+ string expected =
+ "map_int32_int32 {\n"
+ " key: 1\n"
+ " value: 2\n"
+ "}\n";
+ EXPECT_EQ(output, expected);
+}
+
// arena support =================================================
TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) {
diff --git a/src/google/protobuf/map_test_util.h b/src/google/protobuf/map_test_util.h
index dd397619..105313d4 100644
--- a/src/google/protobuf/map_test_util.h
+++ b/src/google/protobuf/map_test_util.h
@@ -107,15 +107,15 @@ class MapReflectionTester {
void ExpectClearViaReflectionIterator(Message* message);
void ExpectMapEntryClearViaReflection(Message* message);
void GetMapValueViaMapReflection(Message* message,
- const string& field_name,
+ const std::string& field_name,
const MapKey& map_key, MapValueRef* map_val);
- Message* GetMapEntryViaReflection(Message* message, const string& field_name,
+ Message* GetMapEntryViaReflection(Message* message, const std::string& field_name,
int index);
- MapIterator MapBegin(Message* message, const string& field_name);
- MapIterator MapEnd(Message* message, const string& field_name);
+ MapIterator MapBegin(Message* message, const std::string& field_name);
+ MapIterator MapEnd(Message* message, const std::string& field_name);
private:
- const FieldDescriptor* F(const string& name);
+ const FieldDescriptor* F(const std::string& name);
const Descriptor* base_descriptor_;
@@ -161,6 +161,6 @@ class MapReflectionTester {
};
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_MAP_TEST_UTIL_H__
diff --git a/src/google/protobuf/map_test_util_impl.h b/src/google/protobuf/map_test_util_impl.h
index ad4d1a3d..2e8b4ba4 100644
--- a/src/google/protobuf/map_test_util_impl.h
+++ b/src/google/protobuf/map_test_util_impl.h
@@ -36,9 +36,9 @@
#include <gtest/gtest.h>
-namespace google {
namespace protobuf_unittest {} // forward declaration
+namespace google {
namespace protobuf {
namespace unittest = ::protobuf_unittest;
@@ -480,6 +480,6 @@ void MapTestUtilImpl::ExpectMapFieldsModified(
}
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_MAP_TEST_UTIL_IMPL_H__
diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h
index 7f7b1e0e..2db3dc6c 100644
--- a/src/google/protobuf/map_type_handler.h
+++ b/src/google/protobuf/map_type_handler.h
@@ -34,6 +34,10 @@
#include <google/protobuf/arena.h>
#include <google/protobuf/wire_format_lite_inl.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -241,7 +245,7 @@ class MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type> {
int default_enum); \
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 size_t SpaceUsedInMapLong(const std::string& value); \
static inline void AssignDefaultValue(TypeOnMemory* value); \
static inline const MapEntryAccessorType& DefaultIfNotInitialized( \
const TypeOnMemory& value, const TypeOnMemory& default_value); \
@@ -548,92 +552,89 @@ inline bool MapTypeHandler<WireFormatLite::TYPE_MESSAGE,
// Definition for string/bytes handler
-#define STRING_OR_BYTES_HANDLER_FUNCTIONS(FieldType) \
- template <typename Type> \
- inline const typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::MapEntryAccessorType& \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::GetExternalReference(const TypeOnMemory& value) { \
- return value.Get(); \
- } \
- template <typename Type> \
- inline size_t \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::SpaceUsedInMapEntryLong(const TypeOnMemory& value) { \
- return sizeof(value); \
- } \
- template <typename Type> \
- inline size_t \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
- const TypeOnMemory& value) { \
- return sizeof(value); \
- } \
- template <typename Type> \
- inline size_t \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
- const string& value) { \
- return sizeof(value); \
- } \
- template <typename Type> \
- inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Clear( \
- TypeOnMemory* value, Arena* arena) { \
- value->ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), \
- arena); \
- } \
- template <typename Type> \
- inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
- ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* arena, \
- int /* default_enum */) { \
- Clear(value, arena); \
- } \
- template <typename Type> \
- inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Merge( \
- const MapEntryAccessorType& from, TypeOnMemory* to, Arena* arena) { \
- to->Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from, arena); \
- } \
- template <typename Type> \
- void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::DeleteNoArena( \
- TypeOnMemory& value) { \
- value.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); \
- } \
- template <typename Type> \
- inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::AssignDefaultValue(TypeOnMemory* /* value */) {} \
- template <typename Type> \
- inline void \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Initialize( \
- 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) { \
- Initialize(value, arena); \
- } \
- template <typename Type> \
- inline typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::MapEntryAccessorType* \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::EnsureMutable( \
- TypeOnMemory* value, Arena* arena) { \
- return value->Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), \
- arena); \
- } \
- template <typename Type> \
- inline const typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::MapEntryAccessorType& \
- MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::DefaultIfNotInitialized(const TypeOnMemory& value, \
- const TypeOnMemory& \
- /* default_value */) { \
- return value.Get(); \
- } \
- template <typename Type> \
- inline bool MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
- Type>::IsInitialized(const TypeOnMemory& /* value */) { \
- return true; \
+#define STRING_OR_BYTES_HANDLER_FUNCTIONS(FieldType) \
+ template <typename Type> \
+ inline const typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::MapEntryAccessorType& \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::GetExternalReference(const TypeOnMemory& value) { \
+ return value.Get(); \
+ } \
+ template <typename Type> \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::SpaceUsedInMapEntryLong(const TypeOnMemory& value) { \
+ return sizeof(value); \
+ } \
+ template <typename Type> \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
+ const TypeOnMemory& value) { \
+ return sizeof(value); \
+ } \
+ template <typename Type> \
+ inline size_t \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::SpaceUsedInMapLong( \
+ const std::string& value) { \
+ return sizeof(value); \
+ } \
+ template <typename Type> \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Clear( \
+ TypeOnMemory* value, Arena* arena) { \
+ value->ClearToEmpty(&internal::GetEmptyStringAlreadyInited(), arena); \
+ } \
+ template <typename Type> \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
+ ClearMaybeByDefaultEnum(TypeOnMemory* value, Arena* arena, \
+ int /* default_enum */) { \
+ Clear(value, arena); \
+ } \
+ template <typename Type> \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Merge( \
+ const MapEntryAccessorType& from, TypeOnMemory* to, Arena* arena) { \
+ to->Set(&internal::GetEmptyStringAlreadyInited(), from, arena); \
+ } \
+ template <typename Type> \
+ void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::DeleteNoArena( \
+ TypeOnMemory& value) { \
+ value.DestroyNoArena(&internal::GetEmptyStringAlreadyInited()); \
+ } \
+ template <typename Type> \
+ inline void \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::AssignDefaultValue( \
+ TypeOnMemory* /* value */) {} \
+ template <typename Type> \
+ inline void \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::Initialize( \
+ TypeOnMemory* value, Arena* /* arena */) { \
+ value->UnsafeSetDefault(&internal::GetEmptyStringAlreadyInited()); \
+ } \
+ template <typename Type> \
+ inline void MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
+ InitializeMaybeByDefaultEnum( \
+ TypeOnMemory* value, int /* default_enum_value */, Arena* arena) { \
+ Initialize(value, arena); \
+ } \
+ template <typename Type> \
+ inline typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::MapEntryAccessorType* \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::EnsureMutable( \
+ TypeOnMemory* value, Arena* arena) { \
+ return value->Mutable(&internal::GetEmptyStringAlreadyInited(), arena); \
+ } \
+ template <typename Type> \
+ inline const typename MapTypeHandler<WireFormatLite::TYPE_##FieldType, \
+ Type>::MapEntryAccessorType& \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>:: \
+ DefaultIfNotInitialized(const TypeOnMemory& value, \
+ const TypeOnMemory& /* default_value */) { \
+ return value.Get(); \
+ } \
+ template <typename Type> \
+ inline bool \
+ MapTypeHandler<WireFormatLite::TYPE_##FieldType, Type>::IsInitialized( \
+ const TypeOnMemory& /* value */) { \
+ return true; \
}
STRING_OR_BYTES_HANDLER_FUNCTIONS(STRING)
STRING_OR_BYTES_HANDLER_FUNCTIONS(BYTES)
@@ -734,6 +735,6 @@ PRIMITIVE_HANDLER_FUNCTIONS(BOOL)
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_TYPE_HANDLER_H__
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index 9b758080..5a9acaf6 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -34,15 +34,14 @@
#include <iostream>
#include <stack>
-#include <google/protobuf/stubs/hash.h>
+#include <unordered_map>
+#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/mutex.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/reflection_internal.h>
#include <google/protobuf/io/coded_stream.h>
@@ -50,26 +49,37 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map_field.h>
+#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.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/singleton.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/hash.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
-using internal::WireFormat;
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+using internal::ParseClosure;
+#endif
using internal::ReflectionOps;
+using internal::WireFormat;
+using internal::WireFormatLite;
void Message::MergeFrom(const Message& from) {
const Descriptor* descriptor = GetDescriptor();
GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
- << ": Tried to merge from a message with a different type. "
- "to: " << descriptor->full_name() << ", "
- "from: " << from.GetDescriptor()->full_name();
+ << ": Tried to merge from a message with a different type. "
+ "to: "
+ << descriptor->full_name()
+ << ", "
+ "from: "
+ << from.GetDescriptor()->full_name();
ReflectionOps::Merge(from, this);
}
@@ -80,19 +90,18 @@ void Message::CheckTypeAndMergeFrom(const MessageLite& other) {
void Message::CopyFrom(const Message& from) {
const Descriptor* descriptor = GetDescriptor();
GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
- << ": Tried to copy from a message with a different type. "
- "to: " << descriptor->full_name() << ", "
- "from: " << from.GetDescriptor()->full_name();
+ << ": Tried to copy from a message with a different type. "
+ "to: "
+ << descriptor->full_name()
+ << ", "
+ "from: "
+ << from.GetDescriptor()->full_name();
ReflectionOps::Copy(from, this);
}
-string Message::GetTypeName() const {
- return GetDescriptor()->full_name();
-}
+string Message::GetTypeName() const { return GetDescriptor()->full_name(); }
-void Message::Clear() {
- ReflectionOps::Clear(this);
-}
+void Message::Clear() { ReflectionOps::Clear(this); }
bool Message::IsInitialized() const {
return ReflectionOps::IsInitialized(*this);
@@ -109,18 +118,20 @@ string Message::InitializationErrorString() const {
}
void Message::CheckInitialized() const {
- GOOGLE_CHECK(IsInitialized())
- << "Message of type \"" << GetDescriptor()->full_name()
- << "\" is missing required fields: " << InitializationErrorString();
+ GOOGLE_CHECK(IsInitialized()) << "Message of type \"" << GetDescriptor()->full_name()
+ << "\" is missing required fields: "
+ << InitializationErrorString();
}
void Message::DiscardUnknownFields() {
return ReflectionOps::DiscardUnknownFields(this);
}
+#if !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Message::MergePartialFromCodedStream(io::CodedInputStream* input) {
return WireFormat::ParseAndMergePartial(input, this);
}
+#endif
bool Message::ParseFromFileDescriptor(int file_descriptor) {
io::FileInputStream input(file_descriptor);
@@ -142,9 +153,461 @@ bool Message::ParsePartialFromIstream(std::istream* input) {
return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+namespace internal {
+
+class ReflectionAccessor {
+ public:
+ static void* GetOffset(void* msg, const google::protobuf::FieldDescriptor* f,
+ const google::protobuf::Reflection* r) {
+ return static_cast<char*>(msg) + CheckedCast(r)->schema_.GetFieldOffset(f);
+ }
+
+ static ExtensionSet* GetExtensionSet(void* msg, const google::protobuf::Reflection* r) {
+ return reinterpret_cast<ExtensionSet*>(
+ static_cast<char*>(msg) +
+ CheckedCast(r)->schema_.GetExtensionSetOffset());
+ }
+ static InternalMetadataWithArena* GetMetadata(void* msg,
+ const google::protobuf::Reflection* r) {
+ return reinterpret_cast<InternalMetadataWithArena*>(
+ static_cast<char*>(msg) + CheckedCast(r)->schema_.GetMetadataOffset());
+ }
+ static void* GetRepeatedEnum(const Reflection* reflection,
+ const FieldDescriptor* field, Message* msg) {
+ return reflection->MutableRawRepeatedField(
+ msg, field, FieldDescriptor::CPPTYPE_ENUM, 0, nullptr);
+ }
+
+ private:
+ static const GeneratedMessageReflection* CheckedCast(const Reflection* r) {
+ auto gr = dynamic_cast<const GeneratedMessageReflection*>(r);
+ GOOGLE_CHECK(gr != nullptr);
+ return gr;
+ }
+};
+
+} // namespace internal
+
+void SetField(uint64 val, const FieldDescriptor* field, Message* msg,
+ const Reflection* reflection) {
+#define STORE_TYPE(CPPTYPE_METHOD) \
+ do \
+ if (field->is_repeated()) { \
+ reflection->Add##CPPTYPE_METHOD(msg, field, value); \
+ } else { \
+ reflection->Set##CPPTYPE_METHOD(msg, field, value); \
+ } \
+ while (0)
+
+ switch (field->type()) {
+#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
+ case FieldDescriptor::TYPE_##TYPE: { \
+ CPPTYPE value = val; \
+ STORE_TYPE(CPPTYPE_METHOD); \
+ break; \
+ }
+
+ // Varints
+ HANDLE_TYPE(INT32, int32, Int32)
+ HANDLE_TYPE(INT64, int64, Int64)
+ HANDLE_TYPE(UINT32, uint32, UInt32)
+ HANDLE_TYPE(UINT64, uint64, UInt64)
+ case FieldDescriptor::TYPE_SINT32: {
+ int32 value = WireFormatLite::ZigZagDecode32(val);
+ STORE_TYPE(Int32);
+ break;
+ }
+ case FieldDescriptor::TYPE_SINT64: {
+ int64 value = WireFormatLite::ZigZagDecode64(val);
+ STORE_TYPE(Int64);
+ break;
+ }
+ HANDLE_TYPE(BOOL, bool, Bool)
+
+ // Fixed
+ HANDLE_TYPE(FIXED32, uint32, UInt32)
+ HANDLE_TYPE(FIXED64, uint64, UInt64)
+ HANDLE_TYPE(SFIXED32, int32, Int32)
+ HANDLE_TYPE(SFIXED64, int64, Int64)
+
+ case FieldDescriptor::TYPE_FLOAT: {
+ float value;
+ uint32 bit_rep = val;
+ std::memcpy(&value, &bit_rep, sizeof(value));
+ STORE_TYPE(Float);
+ break;
+ }
+ case FieldDescriptor::TYPE_DOUBLE: {
+ double value;
+ uint64 bit_rep = val;
+ std::memcpy(&value, &bit_rep, sizeof(value));
+ STORE_TYPE(Double);
+ break;
+ }
+ case FieldDescriptor::TYPE_ENUM: {
+ int value = val;
+ if (field->is_repeated()) {
+ reflection->AddEnumValue(msg, field, value);
+ } else {
+ reflection->SetEnumValue(msg, field, value);
+ }
+ break;
+ }
+ default:
+ GOOGLE_LOG(FATAL) << "Error in descriptors, primitve field with field type "
+ << field->type();
+ }
+#undef STORE_TYPE
+#undef HANDLE_TYPE
+}
+
+bool ReflectiveValidator(const void* arg, int val) {
+ auto d = static_cast<const EnumDescriptor*>(arg);
+ return d->FindValueByNumber(val) != nullptr;
+}
+
+ParseClosure GetPackedField(const FieldDescriptor* field, Message* msg,
+ const Reflection* reflection,
+ internal::ParseContext* ctx) {
+ switch (field->type()) {
+#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, METHOD_NAME) \
+ case FieldDescriptor::TYPE_##TYPE: \
+ return {internal::Packed##METHOD_NAME##Parser, \
+ reflection->MutableRepeatedField<CPPTYPE>(msg, field)}
+ HANDLE_PACKED_TYPE(INT32, int32, Int32);
+ HANDLE_PACKED_TYPE(INT64, int64, Int64);
+ HANDLE_PACKED_TYPE(SINT32, int32, SInt32);
+ HANDLE_PACKED_TYPE(SINT64, int64, SInt64);
+ HANDLE_PACKED_TYPE(UINT32, uint32, UInt32);
+ HANDLE_PACKED_TYPE(UINT64, uint64, UInt64);
+ HANDLE_PACKED_TYPE(BOOL, bool, Bool);
+ case FieldDescriptor::TYPE_ENUM: {
+ auto object =
+ internal::ReflectionAccessor::GetRepeatedEnum(reflection, field, msg);
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ return {internal::PackedEnumParser, object};
+ } else {
+ GOOGLE_CHECK_EQ(field->file()->options().cc_api_version(), 2);
+ ctx->extra_parse_data().SetEnumValidatorArg(
+ ReflectiveValidator, field->enum_type(),
+ reflection->MutableUnknownFields(msg), field->number());
+ return {internal::PackedValidEnumParserArg, object};
+ }
+ }
+ HANDLE_PACKED_TYPE(FIXED32, uint32, Fixed32);
+ HANDLE_PACKED_TYPE(FIXED64, uint64, Fixed64);
+ HANDLE_PACKED_TYPE(SFIXED32, int32, SFixed32);
+ HANDLE_PACKED_TYPE(SFIXED64, int64, SFixed64);
+ HANDLE_PACKED_TYPE(FLOAT, float, Float);
+ HANDLE_PACKED_TYPE(DOUBLE, double, Double);
+#undef HANDLE_PACKED_TYPE
+
+ default:
+ GOOGLE_LOG(FATAL) << "Type is not packable " << field->type();
+ }
+}
-void Message::SerializeWithCachedSizes(
- io::CodedOutputStream* output) const {
+ParseClosure GetLenDelim(int field_number, const FieldDescriptor* field,
+ Message* msg, UnknownFieldSet* unknown,
+ const Reflection* reflection,
+ internal::ParseContext* ctx) {
+ if (field == nullptr || WireFormat::WireTypeForFieldType(field->type()) !=
+ WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
+ if (field && field->is_packable()) {
+ return GetPackedField(field, msg, reflection, ctx);
+ }
+ return {internal::StringParser, unknown->AddLengthDelimited(field_number)};
+ }
+ enum { kNone = 0, kVerify, kStrict } utf8_level = kNone;
+ internal::ParseFunc string_parsers[] = {internal::StringParser,
+ internal::StringParserUTF8Verify,
+ internal::StringParserUTF8};
+ internal::ParseFunc cord_parsers[] = {internal::CordParser,
+ internal::CordParserUTF8Verify,
+ internal::CordParserUTF8};
+ internal::ParseFunc string_piece_parsers[] = {
+ internal::StringPieceParser, internal::StringPieceParserUTF8Verify,
+ internal::StringPieceParserUTF8};
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_STRING:
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3
+ ) {
+ ctx->extra_parse_data().SetFieldName(field->full_name().c_str());
+ utf8_level = kStrict;
+ } else if (
+ true) {
+ ctx->extra_parse_data().SetFieldName(field->full_name().c_str());
+ utf8_level = kVerify;
+ }
+ FALLTHROUGH_INTENDED;
+ case FieldDescriptor::TYPE_BYTES: {
+ if (field->is_repeated()) {
+ int index = reflection->FieldSize(*msg, field);
+ // Add new empty value.
+ reflection->AddString(msg, field, "");
+ if (field->options().ctype() == FieldOptions::STRING ||
+ field->is_extension()) {
+ auto object = reflection->MutableRepeatedPtrField<string>(msg, field)
+ ->Mutable(index);
+ return {string_parsers[utf8_level], object};
+ } else if (field->options().ctype() == FieldOptions::CORD) {
+ auto object = reflection->MutableRepeatedField<Cord>(msg, field)
+ ->Mutable(index);
+ return {cord_parsers[utf8_level], object};
+ } else if (field->options().ctype() == FieldOptions::STRING_PIECE) {
+ auto object =
+ reflection
+ ->MutableRepeatedPtrField<internal::StringPieceField>(msg,
+ field)
+ ->Mutable(index);
+ return {string_piece_parsers[utf8_level], object};
+ }
+ } else {
+ // Clear value and make sure it's set.
+ reflection->SetString(msg, field, "");
+ if (field->options().ctype() == FieldOptions::STRING ||
+ field->is_extension()) {
+ // HACK around inability to get mutable_string in reflection
+ string* object = &const_cast<string&>(
+ reflection->GetStringReference(*msg, field, nullptr));
+ return {string_parsers[utf8_level], object};
+ } else {
+ void* object =
+ internal::ReflectionAccessor::GetOffset(msg, field, reflection);
+ if (field->containing_oneof()) {
+ object = *static_cast<Cord**>(object);
+ }
+ if (field->options().ctype() == FieldOptions::CORD) {
+ return {cord_parsers[utf8_level], object};
+ } else if (field->options().ctype() == FieldOptions::STRING_PIECE) {
+ return {string_piece_parsers[utf8_level], object};
+ }
+ }
+ }
+ GOOGLE_LOG(FATAL) << "No other type than string supported";
+ }
+ case FieldDescriptor::TYPE_MESSAGE: {
+ Message* object;
+ auto factory = ctx->extra_parse_data().factory;
+ if (field->is_repeated()) {
+ object = reflection->AddMessage(msg, field, factory);
+ } else {
+ object = reflection->MutableMessage(msg, field, factory);
+ }
+ return {object->_ParseFunc(), object};
+ }
+ default:
+ GOOGLE_LOG(FATAL) << "Wrong type for length delim " << field->type();
+ }
+}
+
+const char* ReflectiveParseMessageSetItem(const char* begin, const char* end,
+ void* object,
+ internal::ParseContext* ctx) {
+ ParseClosure child;
+ auto msg = static_cast<Message*>(object);
+ auto reflection = msg->GetReflection();
+ uint32 size;
+ auto ptr = begin;
+ while (ptr < end) {
+ uint32 tag = *ptr++;
+ if (tag == WireFormatLite::kMessageSetTypeIdTag) {
+ uint32 type_id;
+ ptr = Varint::Parse32(ptr, &type_id);
+ if (!ptr) goto error;
+
+ auto field = reflection->FindKnownExtensionByNumber(type_id);
+
+ if (ctx->extra_parse_data().payload.empty()) {
+ tag = *ptr++;
+ if (tag == WireFormatLite::kMessageSetMessageTag) {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ if (!ptr) goto error;
+ child = GetLenDelim(type_id * 8 + 2, field, msg,
+ reflection->MutableUnknownFields(msg), reflection,
+ ctx);
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (!ctx->ParseExactRange(child, ptr, newend)) goto error;
+ ptr = newend;
+ } else {
+ goto error;
+ }
+ } else {
+ GOOGLE_LOG(FATAL) << "Wrong order";
+ }
+ } else if (tag == WireFormatLite::kMessageSetItemEndTag) {
+ if (!ctx->ValidEndGroup(tag)) goto error;
+ break;
+ } else if (tag == WireFormatLite::kMessageSetMessageTag) {
+ uint32 size;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ if (!ptr) goto error;
+ child = {internal::StringParser, &ctx->extra_parse_data().payload};
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (!ctx->ParseExactRange(child, ptr, newend)) goto error;
+ ptr = newend;
+ } else {
+ GOOGLE_LOG(FATAL) << "Unknown message set item tag";
+ }
+ }
+ return ptr;
+error:
+ return nullptr;
+len_delim_till_end:
+ return ctx->StoreAndTailCall(ptr, end, {ReflectiveParseMessageSetItem, msg},
+ child, size);
+}
+
+ParseClosure GetGroup(int field_number, const FieldDescriptor* field,
+ Message* msg, UnknownFieldSet* unknown,
+ const Reflection* reflection) {
+ if (field == nullptr && field_number == 1 &&
+ msg->GetDescriptor()->options().message_set_wire_format()) {
+ return {ReflectiveParseMessageSetItem, msg};
+ }
+ if (field == nullptr || WireFormat::WireTypeForFieldType(field->type()) !=
+ WireFormatLite::WIRETYPE_START_GROUP) {
+ return {internal::UnknownGroupParse, unknown->AddGroup(field_number)};
+ }
+
+ Message* object;
+ if (field->is_repeated()) {
+ object = reflection->AddMessage(msg, field, nullptr);
+ } else {
+ object = reflection->MutableMessage(msg, field, nullptr);
+ }
+ return {object->_ParseFunc(), object};
+}
+
+const char* Message::_InternalParse(const char* begin, const char* end,
+ void* object, internal::ParseContext* ctx) {
+ auto msg = static_cast<Message*>(object);
+ const Descriptor* descriptor = msg->GetDescriptor();
+ const Reflection* reflection = msg->GetReflection();
+ auto unknown = reflection->MutableUnknownFields(msg);
+ GOOGLE_DCHECK(descriptor);
+ GOOGLE_DCHECK(reflection);
+
+ GOOGLE_DCHECK(begin <= end);
+ uint32 size;
+ internal::ParseFunc parser_till_end;
+ uint32 tag;
+ int depth;
+ auto ptr = begin;
+ while (ptr < end) {
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ if (ptr == nullptr) return nullptr;
+ if (tag == 0) {
+ if (ctx->ValidEndGroup(0)) return ptr;
+ return nullptr;
+ }
+ if ((tag >> 3) == 0) return nullptr;
+ const FieldDescriptor* field = nullptr;
+
+ int field_number = WireFormatLite::GetTagFieldNumber(tag);
+ field = descriptor->FindFieldByNumber(field_number);
+
+ // If that failed, check if the field is an extension.
+ if (field == nullptr && descriptor->IsExtensionNumber(field_number)) {
+ auto pool = ctx->extra_parse_data().pool;
+ if (pool == NULL) {
+ field = reflection->FindKnownExtensionByNumber(field_number);
+ } else {
+ field = pool->FindExtensionByNumber(descriptor, field_number);
+ }
+ }
+
+ switch (tag & 7) {
+ case 0: {
+ uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ if (!ptr) goto error;
+ if (field == nullptr ||
+ WireFormat::WireTypeForFieldType(field->type()) != 0) {
+ unknown->AddVarint(field_number, val);
+ break;
+ }
+ SetField(val, field, msg, reflection);
+ break;
+ }
+ case 1: {
+ uint64 val = UNALIGNED_LOAD64(ptr);
+ ptr = ptr + 8;
+ if (field == nullptr ||
+ WireFormat::WireTypeForFieldType(field->type()) != 1) {
+ unknown->AddFixed64(field_number, val);
+ break;
+ }
+ SetField(val, field, msg, reflection);
+ break;
+ }
+ case 2: {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ if (!ptr) goto error;
+ ParseClosure child =
+ GetLenDelim(field_number, field, msg, unknown, reflection, ctx);
+ parser_till_end = child.func;
+ object = child.object;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (!ctx->ParseExactRange(child, ptr, newend)) goto error;
+ ptr = newend;
+ break;
+ }
+ case 3: {
+ if (!ctx->PrepareGroup(tag, &depth)) goto error;
+
+ ParseClosure child =
+ GetGroup(field_number, field, msg, unknown, reflection);
+ parser_till_end = child.func;
+ object = child.object;
+
+ if (ptr < end) ptr = child(ptr, end, ctx);
+ if (!ptr) goto error;
+ if (ctx->GroupContinues(depth)) goto group_continues;
+ break;
+ }
+ case 4: {
+ if (!ctx->ValidEndGroup(tag)) goto error;
+ return ptr;
+ }
+ case 5: {
+ uint32 val = UNALIGNED_LOAD32(ptr);
+ ptr = ptr + 4;
+ if (field == nullptr ||
+ WireFormat::WireTypeForFieldType(field->type()) != 5) {
+ unknown->AddFixed32(field_number, val);
+ break;
+ }
+ SetField(val, field, msg, reflection);
+ break;
+ }
+ default:
+ goto error;
+ }
+ }
+ return ptr;
+error:
+ return nullptr;
+len_delim_till_end:
+ // Length delimited field crosses end
+ return ctx->StoreAndTailCall(ptr, end, {Message::_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues:
+ GOOGLE_DCHECK(ptr >= end);
+ // Group crossed end and must be continued. Either this a parse failure
+ // or we need to resume on the next chunk and thus save the state.
+ ctx->StoreGroup({Message::_InternalParse, msg}, {parser_till_end, object},
+ depth);
+ return ptr;
+}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
+
+void Message::SerializeWithCachedSizes(io::CodedOutputStream* output) const {
const internal::SerializationTable* table =
static_cast<const internal::SerializationTable*>(InternalGetTable());
if (table == 0) {
@@ -203,51 +666,50 @@ 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>( \
- const Message& message, const FieldDescriptor* field) const { \
- return *static_cast<RepeatedField<TYPE>* >( \
- MutableRawRepeatedField(const_cast<Message*>(&message), \
- field, CPPTYPE, CTYPE, NULL)); \
-} \
- \
-template<> \
-RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>( \
- Message* message, const FieldDescriptor* field) const { \
- return static_cast<RepeatedField<TYPE>* >( \
- MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \
-}
-
-HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1);
-HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1);
+#define HANDLE_TYPE(TYPE, CPPTYPE, CTYPE) \
+ template <> \
+ const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>( \
+ const Message& message, const FieldDescriptor* field) const { \
+ return *static_cast<RepeatedField<TYPE>*>(MutableRawRepeatedField( \
+ const_cast<Message*>(&message), field, CPPTYPE, CTYPE, NULL)); \
+ } \
+ \
+ template <> \
+ RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>( \
+ Message * message, const FieldDescriptor* field) const { \
+ return static_cast<RepeatedField<TYPE>*>( \
+ MutableRawRepeatedField(message, field, CPPTYPE, CTYPE, NULL)); \
+ }
+
+HANDLE_TYPE(int32, FieldDescriptor::CPPTYPE_INT32, -1);
+HANDLE_TYPE(int64, FieldDescriptor::CPPTYPE_INT64, -1);
HANDLE_TYPE(uint32, FieldDescriptor::CPPTYPE_UINT32, -1);
HANDLE_TYPE(uint64, FieldDescriptor::CPPTYPE_UINT64, -1);
-HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1);
+HANDLE_TYPE(float, FieldDescriptor::CPPTYPE_FLOAT, -1);
HANDLE_TYPE(double, FieldDescriptor::CPPTYPE_DOUBLE, -1);
-HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1);
+HANDLE_TYPE(bool, FieldDescriptor::CPPTYPE_BOOL, -1);
#undef HANDLE_TYPE
-void* Reflection::MutableRawRepeatedString(
- Message* message, const FieldDescriptor* field, bool is_string) const {
+void* Reflection::MutableRawRepeatedString(Message* message,
+ const FieldDescriptor* field,
+ bool is_string) const {
return MutableRawRepeatedField(message, field,
- FieldDescriptor::CPPTYPE_STRING, FieldOptions::STRING, NULL);
+ FieldDescriptor::CPPTYPE_STRING,
+ FieldOptions::STRING, NULL);
}
-MapIterator Reflection::MapBegin(
- Message* message,
- const FieldDescriptor* field) const {
+MapIterator Reflection::MapBegin(Message* message,
+ const FieldDescriptor* field) const {
GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API.";
MapIterator iter(message, field);
return iter;
}
-MapIterator Reflection::MapEnd(
- Message* message,
- const FieldDescriptor* field) const {
+MapIterator Reflection::MapEnd(Message* message,
+ const FieldDescriptor* field) const {
GOOGLE_LOG(FATAL) << "Unimplemented Map Reflection API.";
MapIterator iter(message, field);
return iter;
@@ -258,37 +720,57 @@ MapIterator Reflection::MapEnd(
MessageFactory::~MessageFactory() {}
+namespace internal {
+
+// TODO(gerbens) make this factorized better. This should not have to hop
+// to reflection. Currently uses GeneratedMessageReflection and thus is
+// defined in generated_message_reflection.cc
+void RegisterFileLevelMetadata(void* assign_descriptors_table);
+
+} // namespace internal
+
namespace {
+void RegisterFileLevelMetadata(void* assign_descriptors_table,
+ const string& filename) {
+ internal::RegisterFileLevelMetadata(assign_descriptors_table);
+}
+
class GeneratedMessageFactory : public MessageFactory {
public:
static GeneratedMessageFactory* singleton();
- typedef void RegistrationFunc(const string&);
- void RegisterFile(const char* file, RegistrationFunc* registration_func);
+ struct RegistrationData {
+ const Metadata* file_level_metadata;
+ int size;
+ };
+
+ void RegisterFile(const char* file, void* registration_data);
void RegisterType(const Descriptor* descriptor, const Message* prototype);
// implements MessageFactory ---------------------------------------
- const Message* GetPrototype(const Descriptor* type);
+ const Message* GetPrototype(const Descriptor* type) override;
private:
// Only written at static init time, so does not require locking.
- hash_map<const char*, RegistrationFunc*,
- hash<const char*>, streq> file_map_;
+ std::unordered_map<const char*, void*, hash<const char*>,
+ streq>
+ file_map_;
- Mutex mutex_;
+ internal::WrappedMutex mutex_;
// Initialized lazily, so requires locking.
- hash_map<const Descriptor*, const Message*> type_map_;
+ std::unordered_map<const Descriptor*, const Message*> type_map_;
};
GeneratedMessageFactory* GeneratedMessageFactory::singleton() {
- static auto instance = internal::OnShutdownDelete(new GeneratedMessageFactory);
+ static auto instance =
+ internal::OnShutdownDelete(new GeneratedMessageFactory);
return instance;
}
-void GeneratedMessageFactory::RegisterFile(
- const char* file, RegistrationFunc* registration_func) {
- if (!InsertIfNotPresent(&file_map_, file, registration_func)) {
+void GeneratedMessageFactory::RegisterFile(const char* file,
+ void* registration_data) {
+ if (!InsertIfNotPresent(&file_map_, file, registration_data)) {
GOOGLE_LOG(FATAL) << "File is already registered: " << file;
}
}
@@ -296,8 +778,8 @@ void GeneratedMessageFactory::RegisterFile(
void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor,
const Message* prototype) {
GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool())
- << "Tried to register a non-generated type with the generated "
- "type registry.";
+ << "Tried to register a non-generated type with the generated "
+ "type registry.";
// This should only be called as a result of calling a file registration
// function during GetPrototype(), in which case we already have locked
@@ -321,11 +803,12 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) {
if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL;
// Apparently the file hasn't been registered yet. Let's do that now.
- RegistrationFunc* registration_func =
+ void* registration_data =
FindPtrOrNull(file_map_, type->file()->name().c_str());
- if (registration_func == NULL) {
+ if (registration_data == NULL) {
GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't "
- "registered: " << type->file()->name();
+ "registered: "
+ << type->file()->name();
return NULL;
}
@@ -335,7 +818,7 @@ const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) {
const Message* result = FindPtrOrNull(type_map_, type);
if (result == NULL) {
// Nope. OK, register everything.
- registration_func(type->file()->name());
+ RegisterFileLevelMetadata(registration_data, type->file()->name());
// Should be here now.
result = FindPtrOrNull(type_map_, type);
}
@@ -355,9 +838,9 @@ MessageFactory* MessageFactory::generated_factory() {
}
void MessageFactory::InternalRegisterGeneratedFile(
- const char* filename, void (*register_messages)(const string&)) {
+ const char* filename, void* assign_descriptors_table) {
GeneratedMessageFactory::singleton()->RegisterFile(filename,
- register_messages);
+ assign_descriptors_table);
}
void MessageFactory::InternalRegisterGeneratedMessage(
@@ -371,26 +854,29 @@ MessageFactory* Reflection::GetMessageFactory() const {
return NULL;
}
-void* Reflection::RepeatedFieldData(
- Message* message, const FieldDescriptor* field,
- FieldDescriptor::CppType cpp_type,
- const Descriptor* message_type) const {
+void* Reflection::RepeatedFieldData(Message* message,
+ const FieldDescriptor* field,
+ FieldDescriptor::CppType cpp_type,
+ const Descriptor* message_type) const {
GOOGLE_LOG(FATAL) << "Not implemented.";
return NULL;
}
-namespace internal {
-RepeatedFieldAccessor::~RepeatedFieldAccessor() {
+namespace {
+template <typename T>
+T* GetSingleton() {
+ static T singleton;
+ return &singleton;
}
-} // namespace internal
+} // namespace
const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor(
const FieldDescriptor* field) const {
GOOGLE_CHECK(field->is_repeated());
switch (field->cpp_type()) {
#define HANDLE_PRIMITIVE_TYPE(TYPE, type) \
- case FieldDescriptor::CPPTYPE_ ## TYPE: \
- return internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<type> >::get();
+ case FieldDescriptor::CPPTYPE_##TYPE: \
+ return GetSingleton<internal::RepeatedFieldPrimitiveAccessor<type> >();
HANDLE_PRIMITIVE_TYPE(INT32, int32)
HANDLE_PRIMITIVE_TYPE(UINT32, uint32)
HANDLE_PRIMITIVE_TYPE(INT64, int64)
@@ -404,14 +890,14 @@ const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor(
switch (field->options().ctype()) {
default:
case FieldOptions::STRING:
- return internal::Singleton<internal::RepeatedPtrFieldStringAccessor>::get();
+ return GetSingleton<internal::RepeatedPtrFieldStringAccessor>();
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (field->is_map()) {
- return internal::Singleton<internal::MapFieldAccessor>::get();
+ return GetSingleton<internal::MapFieldAccessor>();
} else {
- return internal::Singleton<internal::RepeatedPtrFieldMessageAccessor>::get();
+ return GetSingleton<internal::RepeatedPtrFieldMessageAccessor>();
}
}
GOOGLE_LOG(FATAL) << "Should not reach here.";
@@ -419,55 +905,35 @@ const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor(
}
namespace internal {
-namespace {
-void ShutdownRepeatedFieldAccessor() {
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<int32> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<uint32> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<int64> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<uint64> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<float> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<double> >::ShutDown();
- internal::Singleton<internal::RepeatedFieldPrimitiveAccessor<bool> >::ShutDown();
- internal::Singleton<internal::RepeatedPtrFieldStringAccessor>::ShutDown();
- internal::Singleton<internal::RepeatedPtrFieldMessageAccessor>::ShutDown();
- internal::Singleton<internal::MapFieldAccessor>::ShutDown();
-}
-
-struct ShutdownRepeatedFieldRegister {
- ShutdownRepeatedFieldRegister() {
- OnShutdown(&ShutdownRepeatedFieldAccessor);
- }
-} shutdown_;
-
-} // namespace
-} // namespace internal
-
-namespace internal {
-template<>
+template <>
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
-// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
+// #240
+PROTOBUF_NOINLINE
#endif
-Message* GenericTypeHandler<Message>::NewFromPrototype(
- const Message* prototype, google::protobuf::Arena* arena) {
+ Message*
+ GenericTypeHandler<Message>::NewFromPrototype(const Message* prototype,
+ Arena* arena) {
return prototype->New(arena);
}
-template<>
+template <>
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
-// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
+// #240
+PROTOBUF_NOINLINE
#endif
-google::protobuf::Arena* GenericTypeHandler<Message>::GetArena(
- Message* value) {
+ Arena*
+ GenericTypeHandler<Message>::GetArena(Message* value) {
return value->GetArena();
}
-template<>
+template <>
#if defined(_MSC_VER) && (_MSC_VER >= 1800)
-// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue #240
-GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+// Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
+// #240
+PROTOBUF_NOINLINE
#endif
-void* GenericTypeHandler<Message>::GetMaybeArenaPointer(
- Message* value) {
+ void*
+ GenericTypeHandler<Message>::GetMaybeArenaPointer(Message* value) {
return value->GetMaybeArenaPointer();
}
} // namespace internal
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index f3d1a58a..9f44132b 100644
--- a/src/google/protobuf/message.h
+++ b/src/google/protobuf/message.h
@@ -115,16 +115,23 @@
#include <type_traits>
#include <vector>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/message_lite.h>
-
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/arena.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/port.h>
#define GOOGLE_PROTOBUF_HAS_ONEOF
#define GOOGLE_PROTOBUF_HAS_ARENAS
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
@@ -156,8 +163,13 @@ namespace expr {
class CelMapReflectionFriend; // field_backed_map_impl.cc
}
+namespace internal {
+class MapFieldPrinterHelper; // text_format.cc
+}
+
namespace internal {
+class ReflectionAccessor; // message.cc
class ReflectionOps; // reflection_ops.h
class MapKeySorter; // wire_format.cc
class WireFormat; // wire_format.h
@@ -186,7 +198,7 @@ struct Metadata {
// optimized for speed will want to override these with faster implementations,
// but classes optimized for code size may be happy with keeping them. See
// the optimize_for option in descriptor.proto.
-class LIBPROTOBUF_EXPORT Message : public MessageLite {
+class PROTOBUF_EXPORT Message : public MessageLite {
public:
inline Message() {}
virtual ~Message() {}
@@ -196,12 +208,12 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// Construct a new instance of the same type. Ownership is passed to the
// caller. (This is also defined in MessageLite, but is defined again here
// for return-type covariance.)
- virtual Message* New() const = 0;
+ Message* New() const override = 0;
// Construct a new instance on the arena. Ownership is passed to the caller
// if arena is a NULL. Default implementation allows for API compatibility
// during the Arena transition.
- virtual Message* New(::google::protobuf::Arena* arena) const {
+ Message* New(Arena* arena) const override {
Message* message = New();
if (arena != NULL) {
arena->Own(message);
@@ -229,11 +241,11 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// This is much, much slower than IsInitialized() as it is implemented
// purely via reflection. Generally, you should not call this unless you
// have already determined that an error exists by calling IsInitialized().
- void FindInitializationErrors(std::vector<string>* errors) const;
+ void FindInitializationErrors(std::vector<std::string>* errors) const;
// Like FindInitializationErrors, but joins all the strings, delimited by
// commas, and returns them.
- string InitializationErrorString() const;
+ std::string InitializationErrorString() const override;
// Clears all unknown fields from this message and all embedded messages.
// Normally, if unknown tag numbers are encountered when parsing a message,
@@ -257,18 +269,18 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// fields defined for the proto.
virtual size_t SpaceUsedLong() const;
- PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead")
+ PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
// Debugging & Testing----------------------------------------------
// Generates a human readable form of this message, useful for debugging
// and other purposes.
- string DebugString() const;
+ std::string DebugString() const;
// Like DebugString(), but with less whitespace.
- string ShortDebugString() const;
+ std::string ShortDebugString() const;
// Like DebugString(), but do not escape UTF-8 byte sequences.
- string Utf8DebugString() const;
+ std::string Utf8DebugString() const;
// Convenience function useful in GDB. Prints DebugString() to stdout.
void PrintDebugString() const;
@@ -305,13 +317,23 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// These methods are pure-virtual in MessageLite, but Message provides
// reflection-based default implementations.
- virtual string GetTypeName() const;
- virtual void Clear();
- virtual bool IsInitialized() const;
- virtual void CheckTypeAndMergeFrom(const MessageLite& other);
- virtual bool MergePartialFromCodedStream(io::CodedInputStream* input);
- virtual size_t ByteSizeLong() const;
- virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const;
+ std::string GetTypeName() const override;
+ void Clear() override;
+ bool IsInitialized() const override;
+ void CheckTypeAndMergeFrom(const MessageLite& other) override;
+#if !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ bool MergePartialFromCodedStream(io::CodedInputStream* input) override;
+#endif
+ size_t ByteSizeLong() const override;
+ void SerializeWithCachedSizes(io::CodedOutputStream* output) const override;
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ internal::ParseFunc _ParseFunc() const override { return _InternalParse; }
+
+ // Reflective parser
+ static const char* _InternalParse(const char* begin, const char* end,
+ void* object, internal::ParseContext* ctx);
+#endif
private:
// This is called only by the default implementation of ByteSize(), to
@@ -327,8 +349,6 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
// Introspection ---------------------------------------------------
- // Typedef for backwards-compatibility.
- typedef google::protobuf::Reflection Reflection;
// 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.
@@ -409,7 +429,7 @@ class MutableRepeatedFieldRef;
// double the message's memory footprint, probably worse. Allocating the
// objects on-demand, on the other hand, would be expensive and prone to
// memory leaks. So, instead we ended up with this flat interface.
-class LIBPROTOBUF_EXPORT Reflection {
+class PROTOBUF_EXPORT Reflection {
public:
inline Reflection() {}
virtual ~Reflection();
@@ -430,7 +450,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// Estimate the amount of memory used by the message object.
virtual size_t SpaceUsedLong(const Message& message) const = 0;
- PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceUsedLong() instead")
+ PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
int SpaceUsed(const Message& message) const {
return internal::ToIntSize(SpaceUsedLong(message));
}
@@ -527,7 +547,7 @@ class LIBPROTOBUF_EXPORT Reflection {
const FieldDescriptor* field) const = 0;
virtual bool GetBool (const Message& message,
const FieldDescriptor* field) const = 0;
- virtual string GetString(const Message& message,
+ virtual std::string GetString(const Message& message,
const FieldDescriptor* field) const = 0;
virtual const EnumValueDescriptor* GetEnum(
const Message& message, const FieldDescriptor* field) const = 0;
@@ -554,15 +574,15 @@ class LIBPROTOBUF_EXPORT Reflection {
// *scratch and return that.
//
// Note: It is perfectly reasonable and useful to write code like:
- // str = reflection->GetStringReference(field, &str);
+ // str = reflection->GetStringReference(message, field, &str);
// This line would ensure that only one copy of the string is made
// regardless of the field's underlying representation. When initializing
// a newly-constructed string, though, it's just as fast and more readable
// to use code like:
// string str = reflection->GetString(message, field);
- virtual const string& GetStringReference(const Message& message,
+ virtual const std::string& GetStringReference(const Message& message,
const FieldDescriptor* field,
- string* scratch) const = 0;
+ std::string* scratch) const = 0;
// Singular field mutators -----------------------------------------
@@ -584,14 +604,17 @@ class LIBPROTOBUF_EXPORT Reflection {
const FieldDescriptor* field, bool value) const = 0;
virtual void SetString(Message* message,
const FieldDescriptor* field,
- const string& value) const = 0;
+ const std::string& value) const = 0;
virtual void SetEnum (Message* message,
const FieldDescriptor* field,
const EnumValueDescriptor* value) const = 0;
// Set an enum field's value with an integer rather than EnumValueDescriptor.
- // If the value does not correspond to a known enum value, either behavior is
- // undefined (for proto2 messages), or the value is accepted silently for
- // messages with new unknown-enum-value semantics.
+ // For proto3 this is just setting the enum field to the value specified, for
+ // proto2 it's more complicated. If value is a known enum value the field is
+ // set as usual. If the value is unknown then it is added to the unknown field
+ // set. Note this matches the behavior of parsing unknown enum values.
+ // If multiple calls with unknown values happen than they are all added to the
+ // unknown field set in order of the calls.
virtual void SetEnumValue(Message* message,
const FieldDescriptor* field,
int value) const = 0;
@@ -652,7 +675,7 @@ class LIBPROTOBUF_EXPORT Reflection {
virtual bool GetRepeatedBool (const Message& message,
const FieldDescriptor* field,
int index) const = 0;
- virtual string GetRepeatedString(const Message& message,
+ virtual std::string GetRepeatedString(const Message& message,
const FieldDescriptor* field,
int index) const = 0;
virtual const EnumValueDescriptor* GetRepeatedEnum(
@@ -671,9 +694,9 @@ class LIBPROTOBUF_EXPORT Reflection {
const FieldDescriptor* field, int index) const = 0;
// See GetStringReference(), above.
- virtual const string& GetRepeatedStringReference(
+ virtual const std::string& GetRepeatedStringReference(
const Message& message, const FieldDescriptor* field,
- int index, string* scratch) const = 0;
+ int index, std::string* scratch) const = 0;
// Repeated field mutators -----------------------------------------
@@ -702,14 +725,17 @@ class LIBPROTOBUF_EXPORT Reflection {
int index, bool value) const = 0;
virtual void SetRepeatedString(Message* message,
const FieldDescriptor* field,
- int index, const string& value) const = 0;
+ int index, const std::string& value) const = 0;
virtual void SetRepeatedEnum(Message* message,
const FieldDescriptor* field, int index,
const EnumValueDescriptor* value) const = 0;
// Set an enum field's value with an integer rather than EnumValueDescriptor.
- // If the value does not correspond to a known enum value, either behavior is
- // undefined (for proto2 messages), or the value is accepted silently for
- // messages with new unknown-enum-value semantics.
+ // For proto3 this is just setting the enum field to the value specified, for
+ // proto2 it's more complicated. If value is a known enum value the field is
+ // set as usual. If the value is unknown then it is added to the unknown field
+ // set. Note this matches the behavior of parsing unknown enum values.
+ // If multiple calls with unknown values happen than they are all added to the
+ // unknown field set in order of the calls.
virtual void SetRepeatedEnumValue(Message* message,
const FieldDescriptor* field, int index,
int value) const = 0;
@@ -738,14 +764,17 @@ class LIBPROTOBUF_EXPORT Reflection {
const FieldDescriptor* field, bool value) const = 0;
virtual void AddString(Message* message,
const FieldDescriptor* field,
- const string& value) const = 0;
+ const std::string& value) const = 0;
virtual void AddEnum (Message* message,
const FieldDescriptor* field,
const EnumValueDescriptor* value) const = 0;
- // Set an enum field's value with an integer rather than EnumValueDescriptor.
- // If the value does not correspond to a known enum value, either behavior is
- // undefined (for proto2 messages), or the value is accepted silently for
- // messages with new unknown-enum-value semantics.
+ // Add an integer value to a repeated enum field rather than
+ // EnumValueDescriptor. For proto3 this is just setting the enum field to the
+ // value specified, for proto2 it's more complicated. If value is a known enum
+ // value the field is set as usual. If the value is unknown then it is added
+ // to the unknown field set. Note this matches the behavior of parsing unknown
+ // enum values. If multiple calls with unknown values happen than they are all
+ // added to the unknown field set in order of the calls.
virtual void AddEnumValue(Message* message,
const FieldDescriptor* field,
int value) const = 0;
@@ -755,7 +784,7 @@ class LIBPROTOBUF_EXPORT Reflection {
MessageFactory* factory = NULL) const = 0;
// Appends an already-allocated object 'new_entry' to the repeated field
- // specifyed by 'field' passing ownership to the message.
+ // specified by 'field' passing ownership to the message.
// TODO(tmarek): Make virtual after all subclasses have been
// updated.
virtual void AddAllocatedMessage(Message* message,
@@ -785,7 +814,7 @@ class LIBPROTOBUF_EXPORT Reflection {
// long as the message is not destroyed.
//
// Note that to use this method users need to include the header file
- // "google/protobuf/reflection.h" (which defines the RepeatedFieldRef
+ // "net/proto2/public/reflection.h" (which defines the RepeatedFieldRef
// class templates).
template<typename T>
RepeatedFieldRef<T> GetRepeatedFieldRef(
@@ -814,43 +843,43 @@ class LIBPROTOBUF_EXPORT Reflection {
// DEPRECATED. Please use GetRepeatedFieldRef().
//
// for T = Cord and all protobuf scalar types except enums.
- template<typename T>
- PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead")
- const RepeatedField<T>& GetRepeatedField(
- const Message&, const FieldDescriptor*) const;
+ template <typename T>
+ PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
+ const RepeatedField<T>& GetRepeatedField(const Message&,
+ const FieldDescriptor*) const;
// DEPRECATED. Please use GetMutableRepeatedFieldRef().
//
// for T = Cord and all protobuf scalar types except enums.
- template<typename T>
- PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead")
- RepeatedField<T>* MutableRepeatedField(
- Message*, const FieldDescriptor*) const;
+ template <typename T>
+ PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
+ RepeatedField<T>* MutableRepeatedField(Message*,
+ const FieldDescriptor*) const;
// DEPRECATED. Please use GetRepeatedFieldRef().
//
// for T = string, google::protobuf::internal::StringPieceField
// google::protobuf::Message & descendants.
- template<typename T>
- PROTOBUF_RUNTIME_DEPRECATED("Please use GetRepeatedFieldRef() instead")
- const RepeatedPtrField<T>& GetRepeatedPtrField(
- const Message&, const FieldDescriptor*) const;
+ template <typename T>
+ PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
+ const RepeatedPtrField<T>& GetRepeatedPtrField(const Message&,
+ const FieldDescriptor*) const;
// DEPRECATED. Please use GetMutableRepeatedFieldRef().
//
// for T = string, google::protobuf::internal::StringPieceField
// google::protobuf::Message & descendants.
- template<typename T>
- PROTOBUF_RUNTIME_DEPRECATED("Please use GetMutableRepeatedFieldRef() instead")
- RepeatedPtrField<T>* MutableRepeatedPtrField(
- Message*, const FieldDescriptor*) const;
+ template <typename T>
+ PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
+ RepeatedPtrField<T>* MutableRepeatedPtrField(Message*,
+ const FieldDescriptor*) const;
// Extensions ----------------------------------------------------------------
// Try to find an extension of this message type by fully-qualified field
// name. Returns NULL if no extension is known for this name or number.
virtual const FieldDescriptor* FindKnownExtensionByName(
- const string& name) const = 0;
+ const std::string& name) const = 0;
// Try to find an extension of this message type by field number.
// Returns NULL if no extension is known for this name or number.
@@ -952,13 +981,16 @@ class LIBPROTOBUF_EXPORT Reflection {
friend class RepeatedFieldRef;
template<typename T, typename Enable>
friend class MutableRepeatedFieldRef;
- friend class ::google::protobuf::python::MapReflectionFriend;
+ friend class python::MapReflectionFriend;
#define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
- friend class ::google::protobuf::expr::CelMapReflectionFriend;
+ friend class expr::CelMapReflectionFriend;
friend class internal::MapFieldReflectionTest;
friend class internal::MapKeySorter;
friend class internal::WireFormat;
friend class internal::ReflectionOps;
+ // Needed for implementing text format for map.
+ friend class internal::MapFieldPrinterHelper;
+ friend class internal::ReflectionAccessor;
// Special version for specialized implementations of string. We can't call
// MutableRawRepeatedField directly here because we don't have access to
@@ -1029,7 +1061,7 @@ class LIBPROTOBUF_EXPORT Reflection {
};
// Abstract interface for a factory for message objects.
-class LIBPROTOBUF_EXPORT MessageFactory {
+class PROTOBUF_EXPORT MessageFactory {
public:
inline MessageFactory() {}
virtual ~MessageFactory();
@@ -1078,8 +1110,8 @@ class LIBPROTOBUF_EXPORT MessageFactory {
// in the file. This strange mechanism is necessary because descriptors are
// built lazily, so we can't register types by their descriptor until we
// know that the descriptor exists. |filename| must be a permanent string.
- static void InternalRegisterGeneratedFile(
- const char* filename, void (*register_messages)(const string&));
+ static void InternalRegisterGeneratedFile(const char* filename,
+ void* assign_descriptors_table);
// For internal use only: Registers a message type. Called only by the
// functions which are registered with InternalRegisterGeneratedFile(),
@@ -1092,16 +1124,15 @@ class LIBPROTOBUF_EXPORT MessageFactory {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
};
-#define DECLARE_GET_REPEATED_FIELD(TYPE) \
-template<> \
-LIBPROTOBUF_EXPORT \
-const RepeatedField<TYPE>& Reflection::GetRepeatedField<TYPE>( \
- const Message& message, const FieldDescriptor* field) const; \
- \
-template<> \
-LIBPROTOBUF_EXPORT \
-RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>( \
- Message* message, const FieldDescriptor* field) const;
+#define DECLARE_GET_REPEATED_FIELD(TYPE) \
+ template <> \
+ PROTOBUF_EXPORT const RepeatedField<TYPE>& \
+ Reflection::GetRepeatedField<TYPE>(const Message& message, \
+ const FieldDescriptor* field) const; \
+ \
+ template <> \
+ PROTOBUF_EXPORT RepeatedField<TYPE>* Reflection::MutableRepeatedField<TYPE>( \
+ Message * message, const FieldDescriptor* field) const;
DECLARE_GET_REPEATED_FIELD(int32)
DECLARE_GET_REPEATED_FIELD(int64)
@@ -1113,6 +1144,53 @@ DECLARE_GET_REPEATED_FIELD(bool)
#undef DECLARE_GET_REPEATED_FIELD
+// Tries to downcast this message to a generated message type. Returns NULL if
+// this class is not an instance of T. This works even if RTTI is disabled.
+//
+// This also has the effect of creating a strong reference to T that will
+// prevent the linker from stripping it out at link time. This can be important
+// if you are using a DynamicMessageFactory that delegates to the generated
+// factory.
+template <typename T>
+const T* DynamicCastToGenerated(const Message* from) {
+ // Compile-time assert that T is a generated type that has a
+ // default_instance() accessor, but avoid actually calling it.
+ const T&(*get_default_instance)() = &T::default_instance;
+ (void)get_default_instance;
+
+ // Compile-time assert that T is a subclass of google::protobuf::Message.
+ const Message* unused = static_cast<T*>(nullptr);
+ (void)unused;
+
+#ifdef GOOGLE_PROTOBUF_NO_RTTI
+ bool ok = T::default_instance().GetReflection() == from->GetReflection();
+ return ok ? down_cast<const T*>(from) : nullptr;
+#else
+ return dynamic_cast<const T*>(from);
+#endif
+}
+
+template <typename T>
+T* DynamicCastToGenerated(Message* from) {
+ const Message* message_const = from;
+ return const_cast<T*>(DynamicCastToGenerated<T>(message_const));
+}
+
+namespace internal {
+
+// Legacy functions, to preserve compatibility with existing callers.
+// These had a slightly different signature, so we have to adjust "T".
+template <typename T>
+T dynamic_cast_if_available(const Message* from) {
+ return DynamicCastToGenerated<typename std::remove_pointer<T>::type>(from);
+}
+template <typename T>
+T dynamic_cast_if_available(Message* from) {
+ return DynamicCastToGenerated<typename std::remove_pointer<T>::type>(from);
+}
+
+} // namespace internal
+
// =============================================================================
// Implementation details for {Get,Mutable}RawRepeatedPtrField. We provide
// specializations for <string>, <StringPieceField> and <Message> and handle
@@ -1121,16 +1199,16 @@ DECLARE_GET_REPEATED_FIELD(bool)
// Such a type presumably is a descendant of google::protobuf::Message.
template<>
-inline const RepeatedPtrField<string>& Reflection::GetRepeatedPtrField<string>(
+inline const RepeatedPtrField<std::string>& Reflection::GetRepeatedPtrField<std::string>(
const Message& message, const FieldDescriptor* field) const {
- return *static_cast<RepeatedPtrField<string>* >(
+ return *static_cast<RepeatedPtrField<std::string>* >(
MutableRawRepeatedString(const_cast<Message*>(&message), field, true));
}
template<>
-inline RepeatedPtrField<string>* Reflection::MutableRepeatedPtrField<string>(
+inline RepeatedPtrField<std::string>* Reflection::MutableRepeatedPtrField<std::string>(
Message* message, const FieldDescriptor* field) const {
- return static_cast<RepeatedPtrField<string>* >(
+ return static_cast<RepeatedPtrField<std::string>* >(
MutableRawRepeatedString(message, field, true));
}
@@ -1171,6 +1249,8 @@ inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrField(
PB::default_instance().GetDescriptor()));
}
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MESSAGE_H__
diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc
index 123b142d..01bb0d39 100644
--- a/src/google/protobuf/message_lite.cc
+++ b/src/google/protobuf/message_lite.cc
@@ -34,18 +34,27 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <climits>
-
-#include <google/protobuf/arena.h>
-#include <google/protobuf/generated_message_util.h>
-#include <google/protobuf/message_lite.h>
-#include <google/protobuf/repeated_field.h>
#include <string>
+
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/message_lite.h>
+#include <google/protobuf/repeated_field.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#include "util/utf8/public/unilib.h"
+#include "util/utf8/public/unilib_utf8_utils.h"
+#endif
+
namespace google {
namespace protobuf {
@@ -71,7 +80,8 @@ void ByteSizeConsistencyError(size_t byte_size_before_serialization,
GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization)
<< "Byte size calculation and serialization were inconsistent. This "
"may indicate a bug in protocol buffers or it may be caused by "
- "concurrent modification of " << message.GetTypeName() << ".";
+ "concurrent modification of "
+ << message.GetTypeName() << ".";
GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal.";
}
@@ -96,6 +106,203 @@ string InitializationErrorMessage(const char* action,
return result;
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+// This is wrapper to turn a ZeroCopyInputStream (ZCIS) into a
+// InputStreamWithOverlap. This is done by copying data around the seams,
+// hence the name EpsCopyInputStream, pictorially if ZCIS presents a stream
+// in chunks like so
+// [---------------------------------------------------------------]
+// [---------------------] chunk 1
+// [----------------------------] chunk 2
+// chunk 3 [--------------]
+// where '-' depicts bytes of the stream or chunks vertically alligned with the
+// corresponding bytes between stream and chunk.
+//
+// This class will convert this into chunks
+// [-----------------....] chunk 1
+// [----....] patch
+// [------------------------....] chunk 2
+// [----....] patch
+// chunk 3 [----------....]
+// patch [----****]
+// by using a fixed size buffer to patch over the seams. This requires
+// copying of an "epsilon" neighboorhood around the seams. In the picture above
+// dots mean bytes beyond the end of the new chunks. Each chunk is kSlopBytes
+// smalller as its original chunk (above depicted as 4 dots) and the number of
+// of chunks is doubled because each seam in the original stream introduces a
+// new patch.
+//
+// The algorithm is simple but not entirely trivial. Two complications arise
+// 1) The original chunk could be less than kSlopBytes. Hence we can't simply
+// chop the last kSlopBytes of a chunk.
+// 2) We need to leave the underlying CodedInputStream (CIS) precisely at the
+// last byte read in the parse. In most cases a parse ends on a limit or end of
+// the ZeroCopyInputStream, which is not problematic because CIS will never give
+// us data beyond that. But the parse can end on a 0 end tag or an end group.
+// If that happens in the first kSlopBytes of the patch (which are copied
+// from the previous buffer) the CIS has already moved to the next chunk to
+// copy the remaining bytes of the patch buffer. There exist no API to rollback
+// to a previous buffer.
+//
+// We model this as a state machine. A call to get the next chunk either returns
+// an original chunk except the last kSlopBytes or it has to copy the last
+// kSlopBytes of the current chunk to the patch buffer and copy the first
+// kSlopBytes of the next chunk to the end of the patch buffer.
+//
+// In order to deal with problem 1, we need to deal with the case that a new
+// chunk can be less or equal than kSlopBytes big. We can just copy the chunk
+// to the end and return (buffer, chunk->size). Pictorially
+// [--------] chunk 1
+// [--] chunk 2
+// [---] chunk 3
+// will become
+// [----....] chunk 1
+// [--....] patch (not full range of the buffer, only two hyphens)
+// [--] chunk 2 (too small so never returned as buffer)
+// [---....] patch (not full range of the buffer, only three hyphens)
+// [---] chunk 3 (too small so never returned as buffer)
+// [----****] patch (full range, last bytes are garbage)
+// Because of this the source (the dots in above) can overlap with the
+// destination buffer and so we have to use memmove.
+//
+// To solve problem 2, we verify after copying the last kSlopBytes the parse
+// won't end before we continue to get the next chunk.
+template <int kSlopBytes>
+class EpsCopyInputStream {
+ public:
+ EpsCopyInputStream(io::CodedInputStream* input) : input_(input) {}
+ ~EpsCopyInputStream() {
+ ABSL_ASSERT(skip_ >= 0);
+ input_->Skip(skip_);
+ }
+
+ template <typename EnsureNotEnd>
+ StringPiece SafeNextWithOverlap(const EnsureNotEnd& ensure_not_end) {
+ switch (next_state_) {
+ case kEOS:
+ // End of stream
+ return nullptr;
+ case kChunk:
+ // chunk_ contains a buffer of sufficient size (> kSlopBytes).
+ // To parse the last kSlopBytes we need to copy the bytes into the
+ // buffer. Hence we set,
+ next_state_ = kBuffer;
+ skip_ = chunk_.size() - kSlopBytes;
+ return {chunk_.begin(), chunk_.size() - kSlopBytes};
+ case kBuffer: {
+ // We have to parse the last kSlopBytes of chunk_, which could alias
+ // buffer_ so we have to memmove.
+ std::memmove(buffer_, chunk_.end() - kSlopBytes, kSlopBytes);
+ skip_ += kSlopBytes;
+ // We need to fill in the other half of buffer_ with the start of the
+ // next chunk. So we need to continue to the next buffer in the ZCIS,
+ // which makes it impossible to rollback to the current buffer :(
+ // We need to verify this won't happen.
+ if (!ensure_not_end(buffer_, kSlopBytes)) {
+ // We are guaranteed to exit in this interval.
+ next_state_ = kEOS;
+ return {buffer_, kSlopBytes};
+ }
+ chunk_ = GetChunk();
+ auto size = chunk_.size();
+ if (size > kSlopBytes) {
+ next_state_ = kChunk;
+ std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), kSlopBytes);
+ return {buffer_, kSlopBytes};
+ } else if (size == 0) {
+ next_state_ = kEOS;
+ return {buffer_, kSlopBytes};
+ } else {
+ // next_state_ = kBuffer, but this is unnecessary
+
+ // The next chunk is not big enough. So we copy it in the current
+ // after the current buffer. Resulting in a buffer with
+ // size + kSlopBytes bytes.
+ std::memcpy(buffer_ + kSlopBytes, chunk_.begin(), size);
+ // skip_ becomes negative here.
+ skip_ += size - kSlopBytes;
+ chunk_ = {buffer_, size + kSlopBytes};
+ return {buffer_, size};
+ }
+ }
+ case kStart: {
+ chunk_ = GetChunk();
+ auto size = chunk_.size();
+ if (PROTOBUF_PREDICT_TRUE(size > kSlopBytes)) {
+ next_state_ = kBuffer;
+ skip_ = size - kSlopBytes;
+ return {chunk_.begin(), size - kSlopBytes};
+ }
+ size_t i = 0;
+ do {
+ if (size == 0) {
+ next_state_ = kEOS;
+ return {buffer_, i};
+ }
+ std::memcpy(buffer_ + i, chunk_.begin(), size);
+ ABSL_ASSERT(skip_ == 0);
+ skip_ = size;
+ i += size;
+ if (i > kSlopBytes) {
+ skip_ -= kSlopBytes;
+ chunk_ = {buffer_, i};
+ next_state_ = kBuffer;
+ return {buffer_, i - kSlopBytes};
+ }
+ if (!ensure_not_end(buffer_, i)) {
+ next_state_ = kEOS;
+ return {buffer_, i};
+ }
+ chunk_ = GetChunk();
+ size = chunk_.size();
+ } while (size <= kSlopBytes);
+ std::memcpy(buffer_ + i, chunk_.begin(), kSlopBytes);
+ next_state_ = kChunk;
+ return {buffer_, i};
+ }
+ }
+ }
+
+ StringPiece NextWithOverlap() {
+ return SafeNextWithOverlap([](const char*, size_t) { return true; });
+ }
+
+ void AdjustPos(int delta) {
+ ABSL_ASSERT(delta <= kSlopBytes);
+ skip_ += delta;
+ }
+
+ void SetError() { skip_ = 0; }
+
+ private:
+ io::CodedInputStream* input_;
+ StringPiece chunk_;
+ char buffer_[2 * kSlopBytes] = {};
+ enum State {
+ kStart,
+ kEOS, // -> end of stream.
+ kChunk, // -> chunk_ contains the data for Next.
+ kBuffer, // -> We need to copy the left over from previous chunk_ and
+ // load and patch the start of the next chunk in the
+ // local buffer.
+ };
+ State next_state_ = kStart;
+ int skip_ = 0; // how much bytes to skip to current position in the stream.
+
+ StringPiece GetChunk() {
+ const void* ptr;
+ ABSL_ASSERT(skip_ >= 0);
+ input_->Skip(skip_);
+ skip_ = 0;
+ int size;
+ if (!input_->GetDirectBufferPointer(&ptr, &size)) {
+ return nullptr;
+ }
+ return StringPiece(static_cast<const char*>(ptr), size);
+ }
+};
+#endif
+
// Several of the Parse methods below just do one thing and then call another
// method. In a naive implementation, we might have ParseFromString() call
// ParseFromArray() which would call ParseFromZeroCopyStream() which would call
@@ -103,16 +310,6 @@ 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineMergeFromCodedStream(
- io::CodedInputStream* input, MessageLite* message);
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromCodedStream(
- io::CodedInputStream* input, MessageLite* message);
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromCodedStream(
- io::CodedInputStream* input, MessageLite* message);
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromArray(
- const void* data, int size, MessageLite* message);
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromArray(
- const void* data, int size, MessageLite* message);
inline bool InlineMergeFromCodedStream(io::CodedInputStream* input,
MessageLite* message) {
@@ -124,36 +321,162 @@ inline bool InlineMergeFromCodedStream(io::CodedInputStream* input,
return true;
}
+inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input,
+ MessageLite* message) {
+ message->Clear();
+ return message->MergePartialFromCodedStream(input);
+}
+
inline bool InlineParseFromCodedStream(io::CodedInputStream* input,
MessageLite* message) {
message->Clear();
return InlineMergeFromCodedStream(input, message);
}
-inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input,
- MessageLite* message) {
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+template <template <int> class Input>
+inline bool InlineMergePartialEntireInput(
+ Input<internal::ParseContext::kSlopBytes>* input, MessageLite* message) {
+ internal::ParseContext ctx;
+
+ auto chunk = input->NextWithOverlap();
+ if (chunk.empty()) {
+ return true;
+ }
+ auto res = ctx.StartParse({message->_ParseFunc(), message}, chunk);
+ while (res.first == internal::ParseContext::kContinue) {
+ int overrun = res.second;
+ chunk = input->NextWithOverlap();
+ if (chunk.empty()) {
+ if (!ctx.ValidEnd(overrun)) return false;
+ return true;
+ }
+ res = ctx.ResumeParse(chunk, overrun);
+ }
+ // Either failure or ended on a zero or end-group tag
+ return false;
+}
+#endif
+
+inline bool InlineMergePartialEntireStream(io::CodedInputStream* cis,
+ MessageLite* message) {
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ EpsCopyInputStream<internal::ParseContext::kSlopBytes> input(cis);
+ if (InlineMergePartialEntireInput(&input, message)) {
+ cis->SetConsumed();
+ return true;
+ }
+ return false;
+#else
+ return message->MergePartialFromCodedStream(cis) &&
+ cis->ConsumedEntireMessage();
+#endif
+}
+
+inline bool InlineMergeEntireStream(io::CodedInputStream* input,
+ MessageLite* message) {
+ if (!InlineMergePartialEntireStream(input, message)) return false;
+ if (!message->IsInitialized()) {
+ GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message);
+ return false;
+ }
+ return true;
+}
+
+inline bool InlineParsePartialEntireStream(io::CodedInputStream* input,
+ MessageLite* message) {
message->Clear();
- return message->MergePartialFromCodedStream(input);
+ return InlineMergePartialEntireStream(input, message);
}
-inline bool InlineParseFromArray(
- const void* data, int size, MessageLite* message) {
- io::CodedInputStream input(reinterpret_cast<const uint8*>(data), size);
- return InlineParseFromCodedStream(&input, message) &&
+inline bool InlineParseEntireStream(io::CodedInputStream* input,
+ MessageLite* message) {
+ message->Clear();
+ return InlineMergeEntireStream(input, message);
+}
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+template <int kSlopBytes>
+class ArrayInput {
+ public:
+ ArrayInput(StringPiece chunk) : chunk_(chunk) {}
+
+ StringPiece NextWithOverlap() {
+ auto s = chunk_.size();
+ if (s > 16) {
+ auto res = chunk_.substr(0, s - 16);
+ chunk_ = chunk_.substr(s - 16);
+ return res;
+ } else if (s == 0) {
+ return nullptr;
+ } else {
+ std::memcpy(buffer_, chunk_.begin(), s);
+ chunk_ = nullptr;
+ return {buffer_, s};
+ }
+ }
+
+ void SetError() {}
+
+ private:
+ StringPiece chunk_;
+ char buffer_[32] = {};
+ int state_ = 0;
+};
+#endif
+
+inline bool InlineMergePartialFromArray(const void* data, int size,
+ MessageLite* msg,
+ bool aliasing = false) {
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ auto begin = static_cast<const char*>(data);
+ if (aliasing) {
+ // TODO(gerbens) make this safe against corruption buffer overflow.
+ // Short cut to allow aliasing string_piece
+ internal::ParseContext ctx;
+ ctx.extra_parse_data().aliasing = true;
+ return ctx.ParseExactRange({msg->_ParseFunc(), msg}, begin, begin + size);
+ }
+ ArrayInput<internal::ParseContext::kSlopBytes> input(
+ StringPiece(begin, size));
+ return InlineMergePartialEntireInput(&input, msg);
+#else
+ io::CodedInputStream input(static_cast<const uint8*>(data), size);
+ return msg->MergePartialFromCodedStream(&input) &&
input.ConsumedEntireMessage();
+#endif
}
-inline bool InlineParsePartialFromArray(
- const void* data, int size, MessageLite* message) {
- io::CodedInputStream input(reinterpret_cast<const uint8*>(data), size);
- return InlineParsePartialFromCodedStream(&input, message) &&
- input.ConsumedEntireMessage();
+inline bool InlineMergeFromArray(const void* data, int size,
+ MessageLite* message, bool aliasing = false) {
+ if (!InlineMergePartialFromArray(data, size, message, aliasing)) return false;
+ if (!message->IsInitialized()) {
+ GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message);
+ return false;
+ }
+ return true;
}
-} // namespace
+inline bool InlineParsePartialFromArray(const void* data, int size,
+ MessageLite* message,
+ bool aliasing = false) {
+ message->Clear();
+ return InlineMergePartialFromArray(data, size, message, aliasing);
+}
+inline bool InlineParseFromArray(const void* data, int size,
+ MessageLite* message, bool aliasing = false) {
+ if (!InlineParsePartialFromArray(data, size, message, aliasing)) return false;
+ if (!message->IsInitialized()) {
+ GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message);
+ return false;
+ }
+ return true;
+}
+
+} // namespace
-MessageLite* MessageLite::New(::google::protobuf::Arena* arena) const {
+MessageLite* MessageLite::New(Arena* arena) const {
MessageLite* message = New();
if (arena != NULL) {
arena->Own(message);
@@ -161,6 +484,48 @@ MessageLite* MessageLite::New(::google::protobuf::Arena* arena) const {
return message;
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+bool MessageLite::MergePartialFromCodedStream(io::CodedInputStream* cis) {
+ EpsCopyInputStream<internal::ParseContext::kSlopBytes> input(cis);
+ internal::ParseContext ctx(cis->RecursionBudget());
+ ctx.extra_parse_data().pool = cis->GetExtensionPool();
+ ctx.extra_parse_data().factory = cis->GetExtensionFactory();
+
+ auto chunk = input.SafeNextWithOverlap(
+ [&ctx](const char* ptr, int n) { return ctx.EnsureNoEnd(ptr, n, 0); });
+ if (chunk.empty()) {
+ cis->SetConsumed();
+ return true;
+ }
+ auto res = ctx.StartParse({_ParseFunc(), this}, chunk);
+ while (res.first == internal::ParseContext::kContinue) {
+ int overrun = res.second;
+ chunk = input.SafeNextWithOverlap([&ctx, overrun](const char* ptr, int n) {
+ return ctx.EnsureNoEnd(ptr, n, overrun);
+ });
+ if (chunk.empty()) {
+ if (!ctx.ValidEnd(overrun)) goto error;
+ cis->SetConsumed();
+ return true;
+ }
+ res = ctx.ResumeParse(chunk, overrun);
+ }
+ // Either failure or ended on a zero or end-group tag
+ if (res.first != internal::ParseContext::kFailure) {
+ cis->SetLastTag(res.first);
+ input.AdjustPos(res.second);
+ return true;
+ }
+error:
+ // Error can happen at a spot from which we can't back up. But in this case
+ // the user can't resume the stream as the error could be in an arbitrary
+ // location in the stream, so just leave the stream alone. This prevents
+ // triggering assertion fail.
+ input.SetError();
+ return false;
+}
+#endif
+
bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) {
return InlineMergeFromCodedStream(input, this);
}
@@ -175,22 +540,20 @@ bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) {
bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) {
io::CodedInputStream decoder(input);
- return ParseFromCodedStream(&decoder) && decoder.ConsumedEntireMessage();
+ return InlineParseEntireStream(&decoder, this);
}
bool MessageLite::ParsePartialFromZeroCopyStream(
io::ZeroCopyInputStream* input) {
io::CodedInputStream decoder(input);
- return ParsePartialFromCodedStream(&decoder) &&
- decoder.ConsumedEntireMessage();
+ return InlineParsePartialEntireStream(&decoder, this);
}
-bool MessageLite::ParseFromBoundedZeroCopyStream(
- io::ZeroCopyInputStream* input, int size) {
+bool MessageLite::ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
+ int size) {
io::CodedInputStream decoder(input);
decoder.PushLimit(size);
- return ParseFromCodedStream(&decoder) &&
- decoder.ConsumedEntireMessage() &&
+ return InlineParseEntireStream(&decoder, this) &&
decoder.BytesUntilLimit() == 0;
}
@@ -198,8 +561,7 @@ bool MessageLite::ParsePartialFromBoundedZeroCopyStream(
io::ZeroCopyInputStream* input, int size) {
io::CodedInputStream decoder(input);
decoder.PushLimit(size);
- return ParsePartialFromCodedStream(&decoder) &&
- decoder.ConsumedEntireMessage() &&
+ return InlineParsePartialEntireStream(&decoder, this) &&
decoder.BytesUntilLimit() == 0;
}
@@ -236,7 +598,8 @@ bool MessageLite::SerializePartialToCodedStream(
io::CodedOutputStream* output) const {
const size_t size = ByteSizeLong(); // Force size to be cached.
if (size > INT_MAX) {
- GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << size;
+ GOOGLE_LOG(ERROR) << GetTypeName()
+ << " exceeded maximum protobuf size of 2GB: " << size;
return false;
}
@@ -286,7 +649,8 @@ bool MessageLite::AppendPartialToString(string* output) const {
size_t old_size = output->size();
size_t byte_size = ByteSizeLong();
if (byte_size > INT_MAX) {
- GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB: " << byte_size;
+ GOOGLE_LOG(ERROR) << GetTypeName()
+ << " exceeded maximum protobuf size of 2GB: " << byte_size;
return false;
}
@@ -316,7 +680,12 @@ bool MessageLite::SerializeToArray(void* data, int size) const {
}
bool MessageLite::SerializePartialToArray(void* data, int size) const {
- int byte_size = ByteSizeLong();
+ const size_t byte_size = ByteSizeLong();
+ if (byte_size > INT_MAX) {
+ GOOGLE_LOG(ERROR) << GetTypeName()
+ << " exceeded maximum protobuf size of 2GB: " << byte_size;
+ return false;
+ }
if (size < byte_size) return false;
uint8* start = reinterpret_cast<uint8*>(data);
uint8* end = SerializeWithCachedSizesToArray(start);
@@ -332,15 +701,13 @@ string MessageLite::SerializeAsString() const {
// of this function, but will be overlaid with the object that the
// caller supplied for the return value to be constructed in.
string output;
- if (!AppendToString(&output))
- output.clear();
+ if (!AppendToString(&output)) output.clear();
return output;
}
string MessageLite::SerializePartialAsString() const {
string output;
- if (!AppendPartialToString(&output))
- output.clear();
+ if (!AppendPartialToString(&output)) output.clear();
return output;
}
@@ -378,9 +745,10 @@ uint8* MessageLite::InternalSerializeWithCachedSizesToArray(
}
namespace internal {
-template<>
+
+template <>
MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
- const MessageLite* prototype, google::protobuf::Arena* arena) {
+ const MessageLite* prototype, Arena* arena) {
return prototype->New(arena);
}
template <>
@@ -388,19 +756,11 @@ void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
MessageLite* to) {
to->CheckTypeAndMergeFrom(from);
}
-template<>
-void GenericTypeHandler<string>::Merge(const string& from,
- string* to) {
+template <>
+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 b8644142..0e8c3475 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -40,29 +40,47 @@
#define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
#include <climits>
+#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/arena.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/port.h>
+
+
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
namespace google {
namespace protobuf {
+
template <typename T>
class RepeatedPtrField;
+
namespace io {
+
class CodedInputStream;
class CodedOutputStream;
class ZeroCopyInputStream;
class ZeroCopyOutputStream;
-}
+
+} // namespace io
namespace internal {
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+// See parse_context.h for explanation
+class ParseContext;
+typedef const char* (*ParseFunc)(const char* ptr, const char* end, void* object,
+ ParseContext* ctx);
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
class RepeatedPtrFieldBase;
class WireFormatLite;
class WeakFieldMap;
-#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
@@ -128,14 +146,16 @@ class ExplicitlyConstructed {
// 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;
+PROTOBUF_EXPORT extern ExplicitlyConstructed<::std::string>
+ fixed_address_empty_string;
-LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() {
+
+PROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() {
return fixed_address_empty_string.get();
}
-LIBPROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const string& str);
-#endif // SWIG
+PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
+
} // namespace internal
// Interface to light weight protocol messages.
@@ -161,7 +181,7 @@ LIBPROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const string& str);
// is best when you only have a small number of message types linked
// into your binary, in which case the size of the protocol buffers
// runtime itself is the biggest problem.
-class LIBPROTOBUF_EXPORT MessageLite {
+class PROTOBUF_EXPORT MessageLite {
public:
inline MessageLite() {}
virtual ~MessageLite() {}
@@ -169,7 +189,7 @@ class LIBPROTOBUF_EXPORT MessageLite {
// Basic Operations ------------------------------------------------
// Get the name of this message type, e.g. "foo.bar.BazProto".
- virtual string GetTypeName() const = 0;
+ virtual std::string GetTypeName() const = 0;
// Construct a new instance of the same type. Ownership is passed to the
// caller.
@@ -177,14 +197,14 @@ class LIBPROTOBUF_EXPORT MessageLite {
// Construct a new instance on the arena. Ownership is passed to the caller
// if arena is a NULL. Default implementation for backwards compatibility.
- virtual MessageLite* New(::google::protobuf::Arena* arena) const;
+ virtual MessageLite* New(Arena* arena) const;
// 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.
- virtual ::google::protobuf::Arena* GetArena() const { return NULL; }
+ virtual 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
@@ -210,7 +230,7 @@ class LIBPROTOBUF_EXPORT MessageLite {
// This is not implemented for Lite messages -- it just returns "(cannot
// determine missing fields for lite message)". However, it is implemented
// for full messages. See message.h.
- virtual string InitializationErrorString() const;
+ virtual std::string InitializationErrorString() const;
// If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
// results are undefined (probably crash).
@@ -249,10 +269,10 @@ class LIBPROTOBUF_EXPORT MessageLite {
// format, matching the encoding output by MessageLite::SerializeToString().
// If you'd like to convert a human-readable string into a protocol buffer
// object, see google::protobuf::TextFormat::ParseFromString().
- bool ParseFromString(const string& data);
+ bool ParseFromString(const std::string& data);
// Like ParseFromString(), but accepts messages that are missing
// required fields.
- bool ParsePartialFromString(const string& data);
+ bool ParsePartialFromString(const std::string& data);
// Parse a protocol buffer contained in an array of bytes.
bool ParseFromArray(const void* data, int size);
// Like ParseFromArray(), but accepts messages that are missing
@@ -278,7 +298,14 @@ class LIBPROTOBUF_EXPORT MessageLite {
//
// MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
// followed by IsInitialized().
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ virtual bool MergePartialFromCodedStream(io::CodedInputStream* input);
+#else
virtual bool MergePartialFromCodedStream(io::CodedInputStream* input) = 0;
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
+ // Merge a protocol buffer contained in a string.
+ bool MergeFromString(const std::string& data);
// Serialization ---------------------------------------------------
@@ -298,9 +325,9 @@ class LIBPROTOBUF_EXPORT MessageLite {
bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
// Serialize the message and store it in the given string. All required
// fields must be set.
- bool SerializeToString(string* output) const;
+ bool SerializeToString(std::string* output) const;
// Like SerializeToString(), but allows missing required fields.
- bool SerializePartialToString(string* output) const;
+ bool SerializePartialToString(std::string* output) const;
// Serialize the message and store it in the given byte array. All required
// fields must be set.
bool SerializeToArray(void* data, int size) const;
@@ -313,15 +340,15 @@ class LIBPROTOBUF_EXPORT MessageLite {
// Note: If you intend to generate many such strings, you may
// reduce heap fragmentation by instead re-using the same string
// object with calls to SerializeToString().
- string SerializeAsString() const;
+ std::string SerializeAsString() const;
// Like SerializeAsString(), but allows missing required fields.
- string SerializePartialAsString() const;
+ std::string SerializePartialAsString() const;
// Like SerializeToString(), but appends to the data to the string's existing
// contents. All required fields must be set.
- bool AppendToString(string* output) const;
+ bool AppendToString(std::string* output) const;
// Like AppendToString(), but allows missing required fields.
- bool AppendPartialToString(string* output) const;
+ bool AppendPartialToString(std::string* output) const;
// Computes the serialized size of the message. This recursively calls
// ByteSizeLong() on all embedded messages.
@@ -331,7 +358,7 @@ class LIBPROTOBUF_EXPORT MessageLite {
virtual size_t ByteSizeLong() const = 0;
// Legacy ByteSize() API.
- PROTOBUF_RUNTIME_DEPRECATED("Please use ByteSizeLong() instead")
+ PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
int ByteSize() const {
return internal::ToIntSize(ByteSizeLong());
}
@@ -370,19 +397,27 @@ class LIBPROTOBUF_EXPORT MessageLite {
virtual uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
uint8* target) const;
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ virtual internal::ParseFunc _ParseFunc() const {
+ GOOGLE_LOG(FATAL) << "Type " << typeid(*this).name()
+ << " doesn't implement _InternalParse";
+ return nullptr;
+ }
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
protected:
// CastToBase allows generated code to cast a RepeatedPtrField<T> to
// RepeatedPtrFieldBase. We try to restrict access to RepeatedPtrFieldBase
// because it is an implementation detail that user code should not access
// directly.
template <typename T>
- static ::google::protobuf::internal::RepeatedPtrFieldBase* CastToBase(
- ::google::protobuf::RepeatedPtrField<T>* repeated) {
+ static internal::RepeatedPtrFieldBase* CastToBase(
+ RepeatedPtrField<T>* repeated) {
return repeated;
}
template <typename T>
- static const ::google::protobuf::internal::RepeatedPtrFieldBase& CastToBase(
- const ::google::protobuf::RepeatedPtrField<T>& repeated) {
+ static const internal::RepeatedPtrFieldBase& CastToBase(
+ const RepeatedPtrField<T>& repeated) {
return repeated;
}
@@ -402,23 +437,9 @@ class LIBPROTOBUF_EXPORT MessageLite {
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
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__
diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc
index 45b46bee..0840e7bf 100644
--- a/src/google/protobuf/message_unittest.cc
+++ b/src/google/protobuf/message_unittest.cc
@@ -43,9 +43,3 @@
// Must include after the above macros.
#include <google/protobuf/test_util.inc>
#include <google/protobuf/message_unittest.inc>
-
-// Make extract script happy.
-namespace google {
-namespace protobuf {
-} // namespace protobuf
-} // namespace google
diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc
index 6ffdcce0..23deaa25 100644
--- a/src/google/protobuf/message_unittest.inc
+++ b/src/google/protobuf/message_unittest.inc
@@ -46,6 +46,7 @@
#include <fstream>
#include <sstream>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -117,8 +118,8 @@ TEST(MESSAGE_TEST_NAME, SerializeToBrokenOstream) {
}
TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) {
- string filename = TestSourceDir() +
- "/google/protobuf/testdata/golden_message";
+ string filename =
+ TestUtil::GetTestDataPath("net/proto2/internal/testdata/golden_message");
int file = open(filename.c_str(), O_RDONLY | O_BINARY);
ASSERT_GE(file, 0);
@@ -130,9 +131,8 @@ TEST(MESSAGE_TEST_NAME, ParseFromFileDescriptor) {
}
TEST(MESSAGE_TEST_NAME, ParsePackedFromFileDescriptor) {
- string filename =
- TestSourceDir() +
- "/google/protobuf/testdata/golden_packed_fields_message";
+ string filename = TestUtil::GetTestDataPath(
+ "net/proto2/internal/testdata/golden_packed_fields_message");
int file = open(filename.c_str(), O_RDONLY | O_BINARY);
ASSERT_GE(file, 0);
@@ -223,23 +223,18 @@ TEST(MESSAGE_TEST_NAME, InitializationErrorString) {
TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) {
UNITTEST::TestAllTypes test_all_types;
- google::protobuf::Message* test_all_types_pointer = &test_all_types;
- EXPECT_EQ(&test_all_types,
- google::protobuf::internal::DynamicCastToGenerated<UNITTEST::TestAllTypes>(
- test_all_types_pointer));
- EXPECT_EQ(nullptr,
- google::protobuf::internal::DynamicCastToGenerated<UNITTEST::TestRequired>(
- test_all_types_pointer));
+ Message* test_all_types_pointer = &test_all_types;
+ EXPECT_EQ(&test_all_types, DynamicCastToGenerated<UNITTEST::TestAllTypes>(
+ test_all_types_pointer));
+ EXPECT_EQ(nullptr, DynamicCastToGenerated<UNITTEST::TestRequired>(
+ test_all_types_pointer));
- const google::protobuf::Message* test_all_types_pointer_const = &test_all_types;
- EXPECT_EQ(
- &test_all_types,
- google::protobuf::internal::DynamicCastToGenerated<const UNITTEST::TestAllTypes>(
- test_all_types_pointer_const));
- EXPECT_EQ(
- nullptr,
- google::protobuf::internal::DynamicCastToGenerated<const UNITTEST::TestRequired>(
- test_all_types_pointer_const));
+ const Message* test_all_types_pointer_const = &test_all_types;
+ EXPECT_EQ(&test_all_types,
+ DynamicCastToGenerated<const UNITTEST::TestAllTypes>(
+ test_all_types_pointer_const));
+ EXPECT_EQ(nullptr, DynamicCastToGenerated<const UNITTEST::TestRequired>(
+ test_all_types_pointer_const));
}
#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet.
@@ -406,9 +401,9 @@ TEST(MESSAGE_TEST_NAME, MessageIsStillValidAfterParseFails) {
// payload.
string invalid_string_data = "\x72\x01";
{
- google::protobuf::Arena arena;
+ Arena arena;
UNITTEST::TestAllTypes* arena_message =
- google::protobuf::Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
+ Arena::CreateMessage<UNITTEST::TestAllTypes>(&arena);
EXPECT_FALSE(arena_message->ParseFromString(invalid_string_data));
arena_message->Clear();
EXPECT_EQ("", arena_message->optional_string());
@@ -572,6 +567,68 @@ TEST(MESSAGE_FACTORY_TEST_NAME, GeneratedFactoryUnknownType) {
nullptr);
}
+TEST(MESSAGE_TEST_NAME, MOMIParserEdgeCases) {
+ {
+ UNITTEST::TestAllTypes msg;
+ // Parser ends in last 16 bytes of buffer due to a 0.
+ string data;
+ // 12 bytes of data
+ for (int i = 0; i < 4; i++) data += "\370\1\1";
+ // 13 byte is terminator
+ data += '\0'; // Terminator
+ // followed by the rest of the stream
+ // space is ascii 32 so no end group
+ data += string(30, ' ');
+ io::ArrayInputStream zcis(data.data(), data.size(), 17);
+ io::CodedInputStream cis(&zcis);
+ EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
+ EXPECT_EQ(cis.CurrentPosition(), 3 * 4 + 1);
+ }
+ {
+ // Parser ends in last 16 bytes of buffer due to a end-group.
+ // Must use a message that is a group. Otherwise ending on a group end is
+ // a failure.
+ UNITTEST::TestAllTypes::OptionalGroup msg;
+ string data;
+ for (int i = 0; i < 3; i++) data += "\370\1\1";
+ data += '\14'; // Octal end-group tag 12 (1 * 8 + 4(
+ data += string(30, ' ');
+ io::ArrayInputStream zcis(data.data(), data.size(), 17);
+ io::CodedInputStream cis(&zcis);
+ EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
+ EXPECT_EQ(cis.CurrentPosition(), 3 * 3 + 1);
+ EXPECT_TRUE(cis.LastTagWas(12));
+ }
+ {
+ // Parser ends in last 16 bytes of buffer due to a end-group. But is inside
+ // a length delimited field.
+ // a failure.
+ UNITTEST::TestAllTypes::OptionalGroup msg;
+ string data;
+ data += "\22\3foo";
+ data += '\14'; // Octal end-group tag 12 (1 * 8 + 4(
+ data += string(30, ' ');
+ io::ArrayInputStream zcis(data.data(), data.size(), 17);
+ io::CodedInputStream cis(&zcis);
+ EXPECT_TRUE(msg.MergePartialFromCodedStream(&cis));
+ EXPECT_EQ(cis.CurrentPosition(), 6);
+ EXPECT_TRUE(cis.LastTagWas(12));
+ }
+ {
+ // Parser fails when ending on 0 if from ZeroCopyInputStream
+ UNITTEST::TestAllTypes msg;
+ string data;
+ // 12 bytes of data
+ for (int i = 0; i < 4; i++) data += "\370\1\1";
+ // 13 byte is terminator
+ data += '\0'; // Terminator
+ data += string(30, ' ');
+ io::ArrayInputStream zcis(data.data(), data.size(), 17);
+ EXPECT_FALSE(msg.ParsePartialFromZeroCopyStream(&zcis));
+ }
+}
+
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/metadata.h b/src/google/protobuf/metadata.h
index 0a6507c0..928bbf5c 100644
--- a/src/google/protobuf/metadata.h
+++ b/src/google/protobuf/metadata.h
@@ -41,6 +41,10 @@
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/unknown_field_set.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
namespace google {
namespace protobuf {
namespace internal {
@@ -73,6 +77,6 @@ class InternalMetadataWithArena
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_METADATA_H__
diff --git a/src/google/protobuf/metadata_lite.h b/src/google/protobuf/metadata_lite.h
index 454d088c..a0e101df 100644
--- a/src/google/protobuf/metadata_lite.h
+++ b/src/google/protobuf/metadata_lite.h
@@ -31,10 +31,18 @@
#ifndef GOOGLE_PROTOBUF_METADATA_LITE_H__
#define GOOGLE_PROTOBUF_METADATA_LITE_H__
+#include <string>
#include <google/protobuf/stubs/common.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>
+#include <google/protobuf/port.h>
+
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
namespace google {
namespace protobuf {
@@ -63,35 +71,35 @@ class InternalMetadataWithArenaBase {
ptr_ = NULL;
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE const T& unknown_fields() const {
- if (GOOGLE_PREDICT_FALSE(have_unknown_fields())) {
+ PROTOBUF_ALWAYS_INLINE const T& unknown_fields() const {
+ if (PROTOBUF_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())) {
+ PROTOBUF_ALWAYS_INLINE T* mutable_unknown_fields() {
+ if (PROTOBUF_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())) {
+ PROTOBUF_ALWAYS_INLINE Arena* arena() const {
+ if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
return PtrValue<Container>()->arena;
} else {
return PtrValue<Arena>();
}
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE bool have_unknown_fields() const {
+ PROTOBUF_ALWAYS_INLINE bool have_unknown_fields() const {
return PtrTag() == kTagContainer;
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(Derived* other) {
+ PROTOBUF_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
@@ -103,21 +111,19 @@ class InternalMetadataWithArenaBase {
}
}
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void MergeFrom(const Derived& other) {
+ PROTOBUF_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() {
+ PROTOBUF_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_;
- }
+ PROTOBUF_ALWAYS_INLINE void* raw_arena_ptr() const { return ptr_; }
private:
void* ptr_;
@@ -133,7 +139,7 @@ class InternalMetadataWithArenaBase {
static const intptr_t kPtrValueMask = ~kPtrTagMask;
// Accessors for pointer tag and pointer value.
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE int PtrTag() const {
+ PROTOBUF_ALWAYS_INLINE int PtrTag() const {
return reinterpret_cast<intptr_t>(ptr_) & kPtrTagMask;
}
@@ -148,7 +154,7 @@ class InternalMetadataWithArenaBase {
Arena* arena;
};
- GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE T* mutable_unknown_fields_slow() {
+ PROTOBUF_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:
@@ -165,20 +171,20 @@ class InternalMetadataWithArenaBase {
// 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,
+ : public InternalMetadataWithArenaBase<std::string,
InternalMetadataWithArenaLite> {
public:
InternalMetadataWithArenaLite() {}
explicit InternalMetadataWithArenaLite(Arena* arena)
- : InternalMetadataWithArenaBase<string,
+ : InternalMetadataWithArenaBase<std::string,
InternalMetadataWithArenaLite>(arena) {}
- void DoSwap(string* other) {
+ void DoSwap(std::string* other) {
mutable_unknown_fields()->swap(*other);
}
- void DoMergeFrom(const string& other) {
+ void DoMergeFrom(const std::string& other) {
mutable_unknown_fields()->append(other);
}
@@ -186,8 +192,13 @@ class InternalMetadataWithArenaLite
mutable_unknown_fields()->clear();
}
- static const string& default_instance() {
- return GetEmptyStringAlreadyInited();
+ static const std::string& default_instance() {
+ // Can't use GetEmptyStringAlreadyInited() here because empty string may
+ // not have been initalized yet. This happens when protocol compiler
+ // statically determines the user can't access defaults and omits init code
+ // from proto constructors. However unknown fields are always part of a
+ // proto so it needs to be lazily initailzed. See b/112613846.
+ return GetEmptyString();
}
};
@@ -199,7 +210,7 @@ class InternalMetadataWithArenaLite
// LiteUnknownFieldSetter setter(&_internal_metadata_);
// StringOutputStream stream(setter.buffer());
// guarantees that the string is only swapped after stream is destroyed.
-class LIBPROTOBUF_EXPORT LiteUnknownFieldSetter {
+class PROTOBUF_EXPORT LiteUnknownFieldSetter {
public:
explicit LiteUnknownFieldSetter(InternalMetadataWithArenaLite* metadata)
: metadata_(metadata) {
@@ -210,15 +221,17 @@ class LIBPROTOBUF_EXPORT LiteUnknownFieldSetter {
~LiteUnknownFieldSetter() {
if (!buffer_.empty()) metadata_->mutable_unknown_fields()->swap(buffer_);
}
- string* buffer() { return &buffer_; }
+ std::string* buffer() { return &buffer_; }
private:
InternalMetadataWithArenaLite* metadata_;
- string buffer_;
+ std::string buffer_;
};
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_METADATA_LITE_H__
diff --git a/src/google/protobuf/no_field_presence_test.cc b/src/google/protobuf/no_field_presence_test.cc
index bc41beec..d212fb11 100644
--- a/src/google/protobuf/no_field_presence_test.cc
+++ b/src/google/protobuf/no_field_presence_test.cc
@@ -280,19 +280,19 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) {
// behaves properly for message fields.
proto2_nofieldpresence_unittest::TestAllTypes message;
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* desc = message.GetDescriptor();
+ const Reflection* r = message.GetReflection();
+ const Descriptor* desc = message.GetDescriptor();
// Check initial state: scalars not present (due to need to be consistent with
// MergeFrom()), message fields not present, oneofs not present.
for (int i = 0; i < desc->field_count(); i++) {
- const google::protobuf::FieldDescriptor* field = desc->field(i);
+ const FieldDescriptor* field = desc->field(i);
if (field->is_repeated()) continue;
EXPECT_EQ(false, r->HasField(message, field));
}
// Test field presence of a message field on the default instance.
- const google::protobuf::FieldDescriptor* msg_field =
+ const FieldDescriptor* msg_field =
desc->FindFieldByName("optional_nested_message");
EXPECT_EQ(false, r->HasField(
proto2_nofieldpresence_unittest::TestAllTypes::
@@ -301,11 +301,11 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) {
// Fill all fields, expect everything to report true (check oneofs below).
FillValues(&message);
for (int i = 0; i < desc->field_count(); i++) {
- const google::protobuf::FieldDescriptor* field = desc->field(i);
+ const FieldDescriptor* field = desc->field(i);
if (field->is_repeated() || field->containing_oneof()) {
continue;
}
- if (field->options().ctype() != google::protobuf::FieldOptions::STRING) {
+ if (field->options().ctype() != FieldOptions::STRING) {
continue;
}
EXPECT_EQ(true, r->HasField(message, field));
@@ -314,12 +314,11 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) {
message.Clear();
// Check zero/empty-means-not-present semantics.
- const google::protobuf::FieldDescriptor* field_int32 = desc->FindFieldByName(
- "optional_int32");
- const google::protobuf::FieldDescriptor* field_double = desc->FindFieldByName(
- "optional_double");
- const google::protobuf::FieldDescriptor* field_string = desc->FindFieldByName(
- "optional_string");
+ const FieldDescriptor* field_int32 = desc->FindFieldByName("optional_int32");
+ const FieldDescriptor* field_double =
+ desc->FindFieldByName("optional_double");
+ const FieldDescriptor* field_string =
+ desc->FindFieldByName("optional_string");
EXPECT_EQ(false, r->HasField(message, field_int32));
EXPECT_EQ(false, r->HasField(message, field_double));
@@ -344,19 +343,18 @@ TEST(NoFieldPresenceTest, ReflectionHasFieldTest) {
TEST(NoFieldPresenceTest, ReflectionClearFieldTest) {
proto2_nofieldpresence_unittest::TestAllTypes message;
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* desc = message.GetDescriptor();
+ const Reflection* r = message.GetReflection();
+ const Descriptor* desc = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* field_int32 = desc->FindFieldByName(
- "optional_int32");
- const google::protobuf::FieldDescriptor* field_double = desc->FindFieldByName(
- "optional_double");
- const google::protobuf::FieldDescriptor* field_string = desc->FindFieldByName(
- "optional_string");
- const google::protobuf::FieldDescriptor* field_message = desc->FindFieldByName(
- "optional_nested_message");
- const google::protobuf::FieldDescriptor* field_lazy = desc->FindFieldByName(
- "optional_lazy_message");
+ const FieldDescriptor* field_int32 = desc->FindFieldByName("optional_int32");
+ const FieldDescriptor* field_double =
+ desc->FindFieldByName("optional_double");
+ const FieldDescriptor* field_string =
+ desc->FindFieldByName("optional_string");
+ const FieldDescriptor* field_message =
+ desc->FindFieldByName("optional_nested_message");
+ const FieldDescriptor* field_lazy =
+ desc->FindFieldByName("optional_lazy_message");
message.set_optional_int32(42);
r->ClearField(&message, field_int32);
@@ -385,17 +383,17 @@ TEST(NoFieldPresenceTest, HasFieldOneofsTest) {
// check that HasField behaves properly for oneofs.
proto2_nofieldpresence_unittest::TestAllTypes message;
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* desc = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* desc_oneof_uint32 =
+ const Reflection* r = message.GetReflection();
+ const Descriptor* desc = message.GetDescriptor();
+ const FieldDescriptor* desc_oneof_uint32 =
desc->FindFieldByName("oneof_uint32");
- const google::protobuf::FieldDescriptor* desc_oneof_nested_message =
+ const FieldDescriptor* desc_oneof_nested_message =
desc->FindFieldByName("oneof_nested_message");
- const google::protobuf::FieldDescriptor* desc_oneof_string =
+ const FieldDescriptor* desc_oneof_string =
desc->FindFieldByName("oneof_string");
- GOOGLE_CHECK_NOTNULL(desc_oneof_uint32);
- GOOGLE_CHECK_NOTNULL(desc_oneof_nested_message);
- GOOGLE_CHECK_NOTNULL(desc_oneof_string);
+ GOOGLE_CHECK(desc_oneof_uint32 != nullptr);
+ GOOGLE_CHECK(desc_oneof_nested_message != nullptr);
+ GOOGLE_CHECK(desc_oneof_string != nullptr);
EXPECT_EQ(false, r->HasField(message, desc_oneof_uint32));
EXPECT_EQ(false, r->HasField(message, desc_oneof_nested_message));
@@ -498,11 +496,10 @@ TEST(NoFieldPresenceTest, LazyMessageFieldHasBit) {
// Check that has-bit interaction with lazy message works (has-bit before and
// after lazy decode).
proto2_nofieldpresence_unittest::TestAllTypes message;
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* desc = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* field = desc->FindFieldByName(
- "optional_lazy_message");
- GOOGLE_CHECK_NOTNULL(field);
+ const Reflection* r = message.GetReflection();
+ const Descriptor* desc = message.GetDescriptor();
+ const FieldDescriptor* field = desc->FindFieldByName("optional_lazy_message");
+ GOOGLE_CHECK(field != nullptr);
EXPECT_EQ(false, message.has_optional_lazy_message());
EXPECT_EQ(false, r->HasField(message, field));
@@ -573,5 +570,5 @@ TEST(NoFieldPresenceTest, OneofPresence) {
} // namespace
} // namespace protobuf
-
} // namespace google
+
diff --git a/src/google/protobuf/package_info.h b/src/google/protobuf/package_info.h
index 935e9639..2b61679a 100644
--- a/src/google/protobuf/package_info.h
+++ b/src/google/protobuf/package_info.h
@@ -36,8 +36,6 @@
// It is not compiled into anything, but it may be read by an automated
// documentation generator.
-namespace google {
-
// Core components of the Protocol Buffers runtime library.
//
// The files in this package represent the core of the Protocol Buffer
@@ -60,5 +58,9 @@ namespace google {
// The implementation does contain some "const" methods which actually modify
// the object behind the scenes -- e.g., to cache results -- but in these cases
// mutex locking is used to make the access thread-safe.
-namespace protobuf {}
+namespace google {
+namespace protobuf {
+// TODO(gerbens) remove this comment, we need it to prevent clang-format
+// from combining the brackets. Which would mess with extract script
+} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/port.h b/src/google/protobuf/port.h
new file mode 100644
index 00000000..63452265
--- /dev/null
+++ b/src/google/protobuf/port.h
@@ -0,0 +1,6 @@
+#ifndef THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_
+#define THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_
+
+#include <google/protobuf/stubs/port.h>
+
+#endif // THIRD_PARTY_PROTOBUF_TESTING_PROTOBUF_SRC_GOOGLE_PROTOBUF_PORT_H_
diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc
new file mode 100644
index 00000000..113605f6
--- /dev/null
+++ b/src/google/protobuf/port_def.inc
@@ -0,0 +1,308 @@
+// 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 common macros that are used in protobuf.
+//
+// To hide these definitions from the outside world (and to prevent collisions
+// if more than one version of protobuf is #included in the same project) you
+// must follow this pattern when #including port_def.inc in a header file:
+//
+// #include "other_header.h"
+// #include "message.h"
+// // etc.
+//
+// #include "port_def.inc" // MUST be last header included
+//
+// // Definitions for this header.
+//
+// #include "port_undef.inc"
+//
+// This is a textual header with no include guard, because we want to
+// detect/prohibit anytime it is #included twice without a corresponding
+// #undef.
+
+// These macros are private and should always be #undef'd from headers.
+// If any of these errors fire, you should either properly #include
+// port_undef.h at the end of your header that #includes port.h, or
+// don't #include port.h twice in a .cc file.
+#ifdef PROTOBUF_NAMESPACE
+#error PROTOBUF_NAMESPACE was previously defined
+#endif
+#ifdef PROTOBUF_NAMESPACE_ID
+#error PROTOBUF_NAMESPACE_ID was previously defined
+#endif
+#ifdef PROTOBUF_ALWAYS_INLINE
+#error PROTOBUF_ALWAYS_INLINE was previously defined
+#endif
+#ifdef PROTOBUF_COLD
+#error PROTOBUF_COLD was previously defined
+#endif
+#ifdef PROTOBUF_NOINLINE
+#error PROTOBUF_NOINLINE was previously defined
+#endif
+#ifdef PROTOBUF_SECTION_VARIABLE
+#error PROTOBUF_SECTION_VARIABLE was previously defined
+#endif
+#ifdef PROTOBUF_DEPRECATED
+#error PROTOBUF_DEPRECATED was previously defined
+#endif
+#ifdef PROTOBUF_DEPRECATED_MSG
+#error PROTOBUF_DEPRECATED_MSG was previously defined
+#endif
+#ifdef PROTOBUF_FUNC_ALIGN
+#error PROTOBUF_FUNC_ALIGN was previously defined
+#endif
+#ifdef PROTOBUF_RETURNS_NONNULL
+#error PROTOBUF_RETURNS_NONNULL was previously defined
+#endif
+#ifdef PROTOBUF_RTTI
+#error PROTOBUF_RTTI was previously defined
+#endif
+#ifdef PROTOBUF_VERSION
+#error PROTOBUF_VERSION was previously defined
+#endif
+#ifdef PROTOBUF_VERSION_SUFFIX
+#error PROTOBUF_VERSION_SUFFIX was previously defined
+#endif
+#ifdef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC
+#error PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC was previously defined
+#endif
+#ifdef PROTOBUF_PREDICT_TRUE
+#error PROTOBUF_PREDICT_TRUE was previously defined
+#endif
+#ifdef PROTOBUF_PREDICT_FALSE
+#error PROTOBUF_PREDICT_FALSE was previously defined
+#endif
+#ifdef PROTOBUF_FIELD_OFFSET
+#error PROTOBUF_FIELD_OFFSET was previously defined
+#endif
+#ifdef PROTOBUF_LL_FORMAT
+#error PROTOBUF_LL_FORMAT was previously defined
+#endif
+#ifdef PROTOBUF_GUARDED_BY
+#error PROTOBUF_GUARDED_BY was previously defined
+#endif
+#ifdef PROTOBUF_LONGLONG
+#error PROTOBUF_LONGLONG was previously defined
+#endif
+#ifdef PROTOBUF_ULONGLONG
+#error PROTOBUF_ULONGLONG was previously defined
+#endif
+#ifdef PROTOBUF_FALLTHROUGH_INTENDED
+#error PROTOBUF_FALLTHROUGH_INTENDED was previously defined
+#endif
+#ifdef PROTOBUF_EXPORT
+#error PROTOBUF_EXPORT was previously defined
+#endif
+#ifdef PROTOC_EXPORT
+#error PROTOC_EXPORT was previously defined
+#endif
+
+
+#define PROTOBUF_NAMESPACE "google::protobuf"
+#define PROTOBUF_NAMESPACE_ID google::protobuf
+#define PROTOBUF_DEPRECATED
+#define PROTOBUF_DEPRECATED_MSG(x)
+#define PROTOBUF_SECTION_VARIABLE(x)
+
+// ----------------------------------------------------------------------------
+// Annotations: Some parts of the code have been annotated in ways that might
+// be useful to some compilers or tools, but are not supported universally.
+// You can #define these annotations yourself if the default implementation
+// is not right for you.
+
+#ifdef GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#define PROTOBUF_ALWAYS_INLINE GOOGLE_ATTRIBUTE_ALWAYS_INLINE
+#else
+#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+// For functions we want to force inline.
+// Introduced in gcc 3.1.
+#define PROTOBUF_ALWAYS_INLINE __attribute__ ((always_inline))
+#else
+// Other compilers will have to figure it out for themselves.
+#define PROTOBUF_ALWAYS_INLINE
+#endif
+#endif
+
+#ifdef GOOGLE_ATTRIBUTE_NOINLINE
+#define PROTOBUF_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE
+#else
+#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+// For functions we want to force not inline.
+// Introduced in gcc 3.1.
+#define PROTOBUF_NOINLINE __attribute__ ((noinline))
+#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
+// Seems to have been around since at least Visual Studio 2005
+#define PROTOBUF_NOINLINE __declspec(noinline)
+#else
+// Other compilers will have to figure it out for themselves.
+#define PROTOBUF_NOINLINE
+#endif
+#endif
+
+#ifdef GOOGLE_ATTRIBUTE_FUNC_ALIGN
+#define PROTOBUF_FUNC_ALIGN GOOGLE_ATTRIBUTE_FUNC_ALIGN
+#else
+#if defined(__clang__) || \
+ defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
+// Function alignment attribute introduced in gcc 4.3
+#define PROTOBUF_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes)))
+#else
+#define PROTOBUF_FUNC_ALIGN(bytes)
+#endif
+#endif
+
+#ifdef GOOGLE_PREDICT_TRUE
+#define PROTOBUF_PREDICT_TRUE GOOGLE_PREDICT_TRUE
+#else
+#ifdef __GNUC__
+// Provided at least since GCC 3.0.
+#define PROTOBUF_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
+#else
+#define PROTOBUF_PREDICT_TRUE(x) (x)
+#endif
+#endif
+
+#ifdef GOOGLE_PREDICT_FALSE
+#define PROTOBUF_PREDICT_FALSE GOOGLE_PREDICT_FALSE
+#else
+#ifdef __GNUC__
+// Provided at least since GCC 3.0.
+#define PROTOBUF_PREDICT_FALSE(x) (__builtin_expect(x, 0))
+#else
+#define PROTOBUF_PREDICT_FALSE(x) (x)
+#endif
+#endif
+
+#ifdef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL
+#define PROTOBUF_RETURNS_NONNULL GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL
+#else
+#ifdef __GNUC__
+#define PROTOBUF_RETURNS_NONNULL __attribute__((returns_nonnull))
+#endif
+#endif
+
+#define PROTOBUF_GUARDED_BY(x)
+#define PROTOBUF_COLD
+
+// Copied from ABSL.
+#if defined(__clang__) && defined(__has_warning)
+#if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")
+#define PROTOBUF_FALLTHROUGH_INTENDED [[clang::fallthrough]]
+#endif
+#elif defined(__GNUC__) && __GNUC__ >= 7
+#define PROTOBUF_FALLTHROUGH_INTENDED [[gnu::fallthrough]]
+#endif
+
+#ifndef PROTOBUF_FALLTHROUGH_INTENDED
+#define PROTOBUF_FALLTHROUGH_INTENDED
+#endif
+
+#ifdef _MSC_VER
+#define PROTOBUF_LONGLONG(x) x##I64
+#define PROTOBUF_ULONGLONG(x) x##UI64
+#define PROTOBUF_LL_FORMAT "I64" // As in printf("%I64d", ...)
+#else
+// By long long, we actually mean int64.
+#define PROTOBUF_LONGLONG(x) x##LL
+#define PROTOBUF_ULONGLONG(x) x##ULL
+// Used to format real long long integers.
+#define PROTOBUF_LL_FORMAT \
+ "ll" // As in "%lld". Note that "q" is poor form also.
+#endif
+
+
+// Shared google3/opensource definitions. //////////////////////////////////////
+
+#define PROTOBUF_VERSION 3006001
+#define PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC 3006001
+#define PROTOBUF_VERSION_SUFFIX ""
+
+// The minimum library version which works with the current version of the
+// headers.
+#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3006001
+
+#if defined(GOOGLE_PROTOBUF_NO_RTTI) && GOOGLE_PROTOBUF_NO_RTTI
+#define PROTOBUF_RTTI 0
+#else
+#define PROTOBUF_RTTI 1
+#endif
+
+// 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 PROTOBUF_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 PROTOBUF_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
+
+
+#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS)
+#ifdef LIBPROTOBUF_EXPORTS
+#define PROTOBUF_EXPORT __declspec(dllexport)
+#else
+#define PROTOBUF_EXPORT __declspec(dllimport)
+#endif
+#ifdef LIBPROTOC_EXPORTS
+#define PROTOC_EXPORT __declspec(dllexport)
+#else
+#define PROTOC_EXPORT __declspec(dllimport)
+#endif
+#else
+#define PROTOBUF_EXPORT
+#define PROTOC_EXPORT
+#endif
+
+// Windows declares several inconvenient macro names. We #undef them and then
+// restore them in port_undef.inc.
+#ifdef _MSC_VER
+#pragma push_macro("GetMessage")
+#undef GetMessage
+#endif
diff --git a/src/google/protobuf/port_undef.inc b/src/google/protobuf/port_undef.inc
new file mode 100644
index 00000000..84eecf5b
--- /dev/null
+++ b/src/google/protobuf/port_undef.inc
@@ -0,0 +1,62 @@
+// 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.
+
+// #undefs all macros defined in port_def.inc. See comments in port_def.inc
+// for more info.
+
+#undef PROTOBUF_NAMESPACE
+#undef PROTOBUF_NAMESPACE_ID
+#undef PROTOBUF_ALWAYS_INLINE
+#undef PROTOBUF_COLD
+#undef PROTOBUF_NOINLINE
+#undef PROTOBUF_SECTION_VARIABLE
+#undef PROTOBUF_DEPRECATED
+#undef PROTOBUF_DEPRECATED_MSG
+#undef PROTOBUF_FUNC_ALIGN
+#undef PROTOBUF_RETURNS_NONNULL
+#undef PROTOBUF_RTTI
+#undef PROTOBUF_VERSION
+#undef PROTOBUF_VERSION_SUFFIX
+#undef PROTOBUF_FIELD_OFFSET
+#undef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC
+#undef PROTOBUF_PREDICT_TRUE
+#undef PROTOBUF_PREDICT_FALSE
+#undef PROTOBUF_LONGLONG
+#undef PROTOBUF_ULONGLONG
+#undef PROTOBUF_LL_FORMAT
+#undef PROTOBUF_GUARDED_BY
+#undef PROTOBUF_FALLTHROUGH_INTENDED
+#undef PROTOBUF_EXPORT
+#undef PROTOC_EXPORT
+
+// Restore macro that may have been #undef'd in port_def.inc.
+#ifdef _MSC_VER
+#pragma pop_macro("GetMessage")
+#endif
diff --git a/src/google/protobuf/preserve_unknown_enum_test.cc b/src/google/protobuf/preserve_unknown_enum_test.cc
index e292199e..71826c38 100644
--- a/src/google/protobuf/preserve_unknown_enum_test.cc
+++ b/src/google/protobuf/preserve_unknown_enum_test.cc
@@ -119,9 +119,12 @@ TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) {
FillMessage(&orig_message);
string serialized = orig_message.SerializeAsString();
- google::protobuf::DynamicMessageFactory factory;
- std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype(
- proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New());
+ DynamicMessageFactory factory;
+ std::unique_ptr<Message> message(
+ factory
+ .GetPrototype(
+ proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())
+ ->New());
EXPECT_EQ(true, message->ParseFromString(serialized));
message->DiscardUnknownFields();
@@ -160,9 +163,12 @@ TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) {
string serialized;
orig_message.SerializeToString(&serialized);
- google::protobuf::DynamicMessageFactory factory;
- std::unique_ptr<google::protobuf::Message> message(factory.GetPrototype(
- proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())->New());
+ DynamicMessageFactory factory;
+ std::unique_ptr<Message> message(
+ factory
+ .GetPrototype(
+ proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())
+ ->New());
EXPECT_EQ(true, message->ParseFromString(serialized));
// The intermediate message has everything in its "unknown fields".
proto2_preserve_unknown_enum_unittest::MyMessage message2;
@@ -188,23 +194,21 @@ TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) {
EXPECT_EQ(true, message.ParseFromString(serialized));
CheckMessage(message);
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* d = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* field = d->FindFieldByName("e");
+ const Reflection* r = message.GetReflection();
+ const Descriptor* d = message.GetDescriptor();
+ const FieldDescriptor* field = d->FindFieldByName("e");
// This should dynamically create an EnumValueDescriptor.
- const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message, field);
+ const EnumValueDescriptor* enum_value = r->GetEnum(message, field);
EXPECT_EQ(enum_value->number(),
static_cast<int>(proto3_preserve_unknown_enum_unittest::E_EXTRA));
// Fetching value for a second time should return the same pointer.
- const google::protobuf::EnumValueDescriptor* enum_value_second =
- r->GetEnum(message, field);
+ const EnumValueDescriptor* enum_value_second = r->GetEnum(message, field);
EXPECT_EQ(enum_value, enum_value_second);
// Check the repeated case too.
- const google::protobuf::FieldDescriptor* repeated_field =
- d->FindFieldByName("repeated_e");
+ const FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e");
enum_value = r->GetRepeatedEnum(message, repeated_field, 0);
EXPECT_EQ(enum_value->number(),
static_cast<int>(proto3_preserve_unknown_enum_unittest::E_EXTRA));
@@ -213,7 +217,7 @@ TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) {
// We should be able to use the returned value descriptor to set a value on
// another message.
- google::protobuf::Message* m = message.New();
+ Message* m = message.New();
r->SetEnum(m, field, enum_value);
EXPECT_EQ(enum_value, r->GetEnum(*m, field));
delete m;
@@ -222,12 +226,11 @@ TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) {
// Test that the new integer-based enum reflection API works.
TEST(PreserveUnknownEnumTest, IntegerEnumReflectionAPI) {
proto3_preserve_unknown_enum_unittest::MyMessage message;
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* d = message.GetDescriptor();
+ const Reflection* r = message.GetReflection();
+ const Descriptor* d = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* singular_field = d->FindFieldByName("e");
- const google::protobuf::FieldDescriptor* repeated_field =
- d->FindFieldByName("repeated_e");
+ const FieldDescriptor* singular_field = d->FindFieldByName("e");
+ const FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e");
r->SetEnumValue(&message, singular_field, 42);
EXPECT_EQ(42, r->GetEnumValue(message, singular_field));
@@ -236,51 +239,58 @@ TEST(PreserveUnknownEnumTest, IntegerEnumReflectionAPI) {
EXPECT_EQ(42, r->GetRepeatedEnumValue(message, repeated_field, 0));
r->SetRepeatedEnumValue(&message, repeated_field, 1, 84);
EXPECT_EQ(84, r->GetRepeatedEnumValue(message, repeated_field, 1));
- const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message,
- singular_field);
+ const EnumValueDescriptor* enum_value = r->GetEnum(message, singular_field);
EXPECT_EQ(42, enum_value->number());
}
// Test that the EnumValue API works properly for proto2 messages as well.
TEST(PreserveUnknownEnumTest, Proto2CatchesUnknownValues) {
protobuf_unittest::TestAllTypes message; // proto2 message
- const google::protobuf::Reflection* r = message.GetReflection();
- const google::protobuf::Descriptor* d = message.GetDescriptor();
- const google::protobuf::FieldDescriptor* repeated_field =
+ const Reflection* r = message.GetReflection();
+ const Descriptor* d = message.GetDescriptor();
+ const FieldDescriptor* repeated_field =
d->FindFieldByName("repeated_nested_enum");
// Add one element to the repeated field so that we can test
// SetRepeatedEnumValue.
- const google::protobuf::EnumValueDescriptor* enum_value =
+ const EnumValueDescriptor* enum_value =
repeated_field->enum_type()->FindValueByName("BAR");
EXPECT_TRUE(enum_value != NULL);
r->AddEnum(&message, repeated_field, enum_value);
-#ifdef PROTOBUF_HAS_DEATH_TEST
- const google::protobuf::FieldDescriptor* singular_field =
+ const FieldDescriptor* singular_field =
d->FindFieldByName("optional_nested_enum");
- // Enum-field integer-based setters GOOGLE_DCHECK-fail on invalid values, in order to
- // remain consistent with proto2 generated code.
- EXPECT_DEBUG_DEATH({
- r->SetEnumValue(&message, singular_field, 4242);
- r->GetEnum(message, singular_field)->number();
- }, "SetEnumValue accepts only valid integer values");
- EXPECT_DEBUG_DEATH({
- r->SetRepeatedEnumValue(&message, repeated_field, 0, 4242);
- r->GetRepeatedEnum(message, repeated_field, 0);
- }, "SetRepeatedEnumValue accepts only valid integer values");
- EXPECT_DEBUG_DEATH({
- r->AddEnumValue(&message, repeated_field, 4242);
- r->GetRepeatedEnum(message, repeated_field, 1);
- }, "AddEnumValue accepts only valid integer values");
-#endif // PROTOBUF_HAS_DEATH_TEST
+ // Enum-field integer-based setters treat as unknown integer values as
+ // unknown fields.
+ r->SetEnumValue(&message, singular_field, 4242);
+ EXPECT_EQ(r->GetEnum(message, singular_field)->number(),
+ protobuf_unittest::TestAllTypes::FOO);
+ r->SetRepeatedEnumValue(&message, repeated_field, 0, 4242);
+ // repeated_nested_enum was set to bar above, this should not have changed.
+ EXPECT_EQ(r->GetRepeatedEnum(message, repeated_field, 0)->number(),
+ protobuf_unittest::TestAllTypes::BAR);
+ r->AddEnumValue(&message, repeated_field, 4242);
+ // No element should be added
+ EXPECT_EQ(message.repeated_nested_enum_size(), 1);
+
+ // We require the enums to end up in unknown field set
+ ASSERT_EQ(message.unknown_fields().field_count(), 3);
+ EXPECT_EQ(message.unknown_fields().field(0).number(),
+ singular_field->number());
+ EXPECT_EQ(message.unknown_fields().field(0).varint(), 4242);
+ EXPECT_EQ(message.unknown_fields().field(1).number(),
+ repeated_field->number());
+ EXPECT_EQ(message.unknown_fields().field(1).varint(), 4242);
+ EXPECT_EQ(message.unknown_fields().field(2).number(),
+ repeated_field->number());
+ EXPECT_EQ(message.unknown_fields().field(2).varint(), 4242);
}
TEST(PreserveUnknownEnumTest, SupportsUnknownEnumValuesAPI) {
protobuf_unittest::TestAllTypes proto2_message;
proto3_preserve_unknown_enum_unittest::MyMessage new_message;
- const google::protobuf::Reflection* proto2_reflection = proto2_message.GetReflection();
- const google::protobuf::Reflection* new_reflection = new_message.GetReflection();
+ const Reflection* proto2_reflection = proto2_message.GetReflection();
+ const Reflection* new_reflection = new_message.GetReflection();
EXPECT_FALSE(proto2_reflection->SupportsUnknownEnumValues());
EXPECT_TRUE(new_reflection->SupportsUnknownEnumValues());
diff --git a/src/google/protobuf/proto3_arena_lite_unittest.cc b/src/google/protobuf/proto3_arena_lite_unittest.cc
index 2ac775d7..6d2abf63 100644
--- a/src/google/protobuf/proto3_arena_lite_unittest.cc
+++ b/src/google/protobuf/proto3_arena_lite_unittest.cc
@@ -37,9 +37,9 @@
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
-namespace google {
using proto3_arena_unittest::TestAllTypes;
+namespace google {
namespace protobuf {
namespace {
// We selectively set/check a few representative fields rather than all fields
diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc
index dac73781..a03ed423 100644
--- a/src/google/protobuf/proto3_arena_unittest.cc
+++ b/src/google/protobuf/proto3_arena_unittest.cc
@@ -39,9 +39,9 @@
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
-namespace google {
using proto3_arena_unittest::TestAllTypes;
+namespace google {
namespace protobuf {
namespace {
// We selectively set/check a few representative fields rather than all fields
@@ -126,30 +126,7 @@ TEST(Proto3ArenaTest, Parsing) {
ExpectAllFieldsSet(*arena_message);
}
-TEST(Proto3ArenaTest, UnknownFieldsDefaultDrop) {
- ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(false);
- 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);
- // But the change will never will serialized back.
- ASSERT_EQ(original.ByteSize(), arena_message->ByteSize());
- ASSERT_TRUE(
- arena_message->GetReflection()->GetUnknownFields(*arena_message).empty());
-}
-
-TEST(Proto3ArenaTest, UnknownFieldsDefaultPreserve) {
- ::google::protobuf::internal::SetProto3PreserveUnknownsDefault(true);
+TEST(Proto3ArenaTest, UnknownFields) {
TestAllTypes original;
SetAllFields(&original);
@@ -201,7 +178,7 @@ TEST(Proto3ArenaTest, ReleaseMessage) {
}
TEST(Proto3ArenaTest, MessageFieldClear) {
- // GitHub issue #310: https://github.com/google/protobuf/issues/310
+ // GitHub issue #310: https://github.com/protocolbuffers/protobuf/issues/310
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
diff --git a/src/google/protobuf/proto3_lite_unittest.cc b/src/google/protobuf/proto3_lite_unittest.cc
index 8b2c5742..abeeedb1 100644
--- a/src/google/protobuf/proto3_lite_unittest.cc
+++ b/src/google/protobuf/proto3_lite_unittest.cc
@@ -28,113 +28,16 @@
// (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>
-#include <memory>
-#include <vector>
+#include <google/protobuf/unittest_proto3.pb.h>
-#include <google/protobuf/unittest_proto3_lite.pb.h>
-#include <google/protobuf/arena.h>
-#include <google/protobuf/testing/googletest.h>
-#include <gtest/gtest.h>
+#define LITE_TEST_NAME Proto3LiteTest
+#define UNITTEST ::proto3_unittest
-namespace google {
-using proto3_lite_unittest::TestAllTypes;
+// Must include after the above macros.
+#include <google/protobuf/proto3_lite_unittest.inc>
+// Make extract script happy.
+namespace google {
namespace protobuf {
-namespace {
-// We selectively set/check a few representative fields rather than all fields
-// as this test is only expected to cover the basics of lite support.
-void SetAllFields(TestAllTypes* m) {
- m->set_optional_int32(100);
- m->set_optional_string("asdf");
- m->set_optional_bytes("jkl;");
- m->mutable_optional_nested_message()->set_bb(42);
- m->mutable_optional_foreign_message()->set_c(43);
- m->set_optional_nested_enum(
- proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
- m->set_optional_foreign_enum(
- proto3_lite_unittest::FOREIGN_BAZ);
- m->mutable_optional_lazy_message()->set_bb(45);
- m->add_repeated_int32(100);
- m->add_repeated_string("asdf");
- m->add_repeated_bytes("jkl;");
- m->add_repeated_nested_message()->set_bb(46);
- m->add_repeated_foreign_message()->set_c(47);
- m->add_repeated_nested_enum(
- proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
- m->add_repeated_foreign_enum(
- proto3_lite_unittest::FOREIGN_BAZ);
- m->add_repeated_lazy_message()->set_bb(49);
-
- m->set_oneof_uint32(1);
- m->mutable_oneof_nested_message()->set_bb(50);
- m->set_oneof_string("test"); // only this one remains set
-}
-
-void ExpectAllFieldsSet(const TestAllTypes& m) {
- EXPECT_EQ(100, m.optional_int32());
- EXPECT_EQ("asdf", m.optional_string());
- EXPECT_EQ("jkl;", m.optional_bytes());
- EXPECT_EQ(true, m.has_optional_nested_message());
- EXPECT_EQ(42, m.optional_nested_message().bb());
- EXPECT_EQ(true, m.has_optional_foreign_message());
- EXPECT_EQ(43, m.optional_foreign_message().c());
- EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
- m.optional_nested_enum());
- EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
- m.optional_foreign_enum());
- EXPECT_EQ(true, m.has_optional_lazy_message());
- EXPECT_EQ(45, m.optional_lazy_message().bb());
-
- EXPECT_EQ(1, m.repeated_int32_size());
- EXPECT_EQ(100, m.repeated_int32(0));
- EXPECT_EQ(1, m.repeated_string_size());
- EXPECT_EQ("asdf", m.repeated_string(0));
- EXPECT_EQ(1, m.repeated_bytes_size());
- EXPECT_EQ("jkl;", m.repeated_bytes(0));
- EXPECT_EQ(1, m.repeated_nested_message_size());
- EXPECT_EQ(46, m.repeated_nested_message(0).bb());
- EXPECT_EQ(1, m.repeated_foreign_message_size());
- EXPECT_EQ(47, m.repeated_foreign_message(0).c());
- EXPECT_EQ(1, m.repeated_nested_enum_size());
- EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
- m.repeated_nested_enum(0));
- EXPECT_EQ(1, m.repeated_foreign_enum_size());
- EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
- m.repeated_foreign_enum(0));
- EXPECT_EQ(1, m.repeated_lazy_message_size());
- EXPECT_EQ(49, m.repeated_lazy_message(0).bb());
-
- EXPECT_EQ(proto3_lite_unittest::TestAllTypes::kOneofString,
- m.oneof_field_case());
- EXPECT_EQ("test", m.oneof_string());
-}
-
-// In this file we only test some basic functionalities of in proto3 and expect
-// the rest is fully tested in proto2 unittests because proto3 shares most code
-// with proto2.
-
-TEST(Proto3LiteTest, Parsing) {
- TestAllTypes original;
- SetAllFields(&original);
-
- TestAllTypes msg;
- msg.ParseFromString(original.SerializeAsString());
- ExpectAllFieldsSet(msg);
-}
-
-TEST(Proto3LiteTest, Swap) {
- // Test Swap().
- TestAllTypes msg1;
- TestAllTypes msg2;
- msg1.set_optional_string("123");
- msg2.set_optional_string("3456");
- msg1.Swap(&msg2);
- EXPECT_EQ("3456", msg1.optional_string());
- EXPECT_EQ("123", msg2.optional_string());
- EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1);
-}
-
-} // namespace
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/proto3_lite_unittest.inc b/src/google/protobuf/proto3_lite_unittest.inc
new file mode 100644
index 00000000..eca9b706
--- /dev/null
+++ b/src/google/protobuf/proto3_lite_unittest.inc
@@ -0,0 +1,139 @@
+// 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 <string>
+#include <memory>
+#include <vector>
+
+#include <google/protobuf/arena.h>
+#include <google/protobuf/testing/googletest.h>
+#include <gtest/gtest.h>
+
+using UNITTEST::TestAllTypes;
+
+namespace google {
+namespace protobuf {
+namespace {
+// We selectively set/check a few representative fields rather than all fields
+// as this test is only expected to cover the basics of lite support.
+void SetAllFields(TestAllTypes* m) {
+ m->set_optional_int32(100);
+ m->set_optional_string("asdf");
+ m->set_optional_bytes("jkl;");
+ m->mutable_optional_nested_message()->set_bb(42);
+ m->mutable_optional_foreign_message()->set_c(43);
+ m->set_optional_nested_enum(
+ UNITTEST::TestAllTypes_NestedEnum_BAZ);
+ m->set_optional_foreign_enum(
+ UNITTEST::FOREIGN_BAZ);
+ m->mutable_optional_lazy_message()->set_bb(45);
+ m->add_repeated_int32(100);
+ m->add_repeated_string("asdf");
+ m->add_repeated_bytes("jkl;");
+ m->add_repeated_nested_message()->set_bb(46);
+ m->add_repeated_foreign_message()->set_c(47);
+ m->add_repeated_nested_enum(
+ UNITTEST::TestAllTypes_NestedEnum_BAZ);
+ m->add_repeated_foreign_enum(
+ UNITTEST::FOREIGN_BAZ);
+ m->add_repeated_lazy_message()->set_bb(49);
+
+ m->set_oneof_uint32(1);
+ m->mutable_oneof_nested_message()->set_bb(50);
+ m->set_oneof_string("test"); // only this one remains set
+}
+
+void ExpectAllFieldsSet(const TestAllTypes& m) {
+ EXPECT_EQ(100, m.optional_int32());
+ EXPECT_EQ("asdf", m.optional_string());
+ EXPECT_EQ("jkl;", m.optional_bytes());
+ EXPECT_EQ(true, m.has_optional_nested_message());
+ EXPECT_EQ(42, m.optional_nested_message().bb());
+ EXPECT_EQ(true, m.has_optional_foreign_message());
+ EXPECT_EQ(43, m.optional_foreign_message().c());
+ EXPECT_EQ(UNITTEST::TestAllTypes_NestedEnum_BAZ,
+ m.optional_nested_enum());
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ m.optional_foreign_enum());
+ EXPECT_EQ(true, m.has_optional_lazy_message());
+ EXPECT_EQ(45, m.optional_lazy_message().bb());
+
+ EXPECT_EQ(1, m.repeated_int32_size());
+ EXPECT_EQ(100, m.repeated_int32(0));
+ EXPECT_EQ(1, m.repeated_string_size());
+ EXPECT_EQ("asdf", m.repeated_string(0));
+ EXPECT_EQ(1, m.repeated_bytes_size());
+ EXPECT_EQ("jkl;", m.repeated_bytes(0));
+ EXPECT_EQ(1, m.repeated_nested_message_size());
+ EXPECT_EQ(46, m.repeated_nested_message(0).bb());
+ EXPECT_EQ(1, m.repeated_foreign_message_size());
+ EXPECT_EQ(47, m.repeated_foreign_message(0).c());
+ EXPECT_EQ(1, m.repeated_nested_enum_size());
+ EXPECT_EQ(UNITTEST::TestAllTypes_NestedEnum_BAZ,
+ m.repeated_nested_enum(0));
+ EXPECT_EQ(1, m.repeated_foreign_enum_size());
+ EXPECT_EQ(UNITTEST::FOREIGN_BAZ,
+ m.repeated_foreign_enum(0));
+ EXPECT_EQ(1, m.repeated_lazy_message_size());
+ EXPECT_EQ(49, m.repeated_lazy_message(0).bb());
+
+ EXPECT_EQ(UNITTEST::TestAllTypes::kOneofString,
+ m.oneof_field_case());
+ EXPECT_EQ("test", m.oneof_string());
+}
+
+// In this file we only test some basic functionalities of in proto3 and expect
+// the rest is fully tested in proto2 unittests because proto3 shares most code
+// with proto2.
+
+TEST(LITE_TEST_NAME, Parsing) {
+ TestAllTypes original;
+ SetAllFields(&original);
+
+ TestAllTypes msg;
+ msg.ParseFromString(original.SerializeAsString());
+ ExpectAllFieldsSet(msg);
+}
+
+TEST(LITE_TEST_NAME, Swap) {
+ // Test Swap().
+ TestAllTypes msg1;
+ TestAllTypes msg2;
+ msg1.set_optional_string("123");
+ msg2.set_optional_string("3456");
+ msg1.Swap(&msg2);
+ EXPECT_EQ("3456", msg1.optional_string());
+ EXPECT_EQ("123", msg2.optional_string());
+ EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1);
+}
+
+} // namespace
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h
index 5d0fc42b..094701f7 100755..100644
--- a/src/google/protobuf/reflection.h
+++ b/src/google/protobuf/reflection.h
@@ -38,6 +38,12 @@
#include <google/protobuf/message.h>
#include <google/protobuf/generated_enum_util.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -340,14 +346,13 @@ namespace internal {
//
// You can map from T to the actual type using RefTypeTraits:
// typedef RefTypeTraits<T>::AccessorValueType ActualType;
-class LIBPROTOBUF_EXPORT RepeatedFieldAccessor {
+class PROTOBUF_EXPORT RepeatedFieldAccessor {
public:
// Typedefs for clarity.
typedef void Field;
typedef void Value;
typedef void Iterator;
- virtual ~RepeatedFieldAccessor();
virtual bool IsEmpty(const Field* data) const = 0;
virtual int Size(const Field* data) const = 0;
// Depends on the underlying representation of the repeated field, this
@@ -425,6 +430,13 @@ class LIBPROTOBUF_EXPORT RepeatedFieldAccessor {
ActualType tmp = static_cast<ActualType>(value);
Add(data, static_cast<const Value*>(&tmp));
}
+
+ protected:
+ // We want the destructor to be completely trivial as to allow it to be
+ // a function local static. Hence we make it non-virtual and protected,
+ // this class only live as part of a global singleton and should not be
+ // deleted.
+ ~RepeatedFieldAccessor() = default;
};
// Implement (Mutable)RepeatedFieldRef::iterator
@@ -563,12 +575,12 @@ struct RefTypeTraits<
template<typename T>
struct RefTypeTraits<
- T, typename std::enable_if<std::is_same<string, T>::value>::type> {
+ T, typename std::enable_if<std::is_same<std::string, T>::value>::type> {
typedef RepeatedFieldRefIterator<T> iterator;
typedef RepeatedFieldAccessor AccessorType;
- typedef string AccessorValueType;
- typedef const string IteratorValueType;
- typedef const string* IteratorPointerType;
+ typedef std::string AccessorValueType;
+ typedef const std::string IteratorValueType;
+ typedef const std::string* IteratorPointerType;
static const FieldDescriptor::CppType cpp_type =
FieldDescriptor::CPPTYPE_STRING;
static const Descriptor* GetMessageFieldDescriptor() {
@@ -607,4 +619,6 @@ struct RefTypeTraits<
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_REFLECTION_H__
diff --git a/src/google/protobuf/reflection_internal.h b/src/google/protobuf/reflection_internal.h
index fcb42471..ff62d58d 100644
--- a/src/google/protobuf/reflection_internal.h
+++ b/src/google/protobuf/reflection_internal.h
@@ -43,36 +43,34 @@ namespace internal {
// corresponding random-access methods.
class RandomAccessRepeatedFieldAccessor : public RepeatedFieldAccessor {
public:
- virtual ~RandomAccessRepeatedFieldAccessor() {}
-
- virtual Iterator* BeginIterator(const Field* data) const {
+ Iterator* BeginIterator(const Field* data) const override {
return PositionToIterator(0);
}
- virtual Iterator* EndIterator(const Field* data) const {
+ Iterator* EndIterator(const Field* data) const override {
return PositionToIterator(this->Size(data));
}
- virtual Iterator* CopyIterator(const Field* data,
- const Iterator* iterator) const {
+ Iterator* CopyIterator(const Field* data,
+ const Iterator* iterator) const override {
return const_cast<Iterator*>(iterator);
}
- virtual Iterator* AdvanceIterator(const Field* data,
- Iterator* iterator) const {
+ Iterator* AdvanceIterator(const Field* data,
+ Iterator* iterator) const override {
return PositionToIterator(IteratorToPosition(iterator) + 1);
}
- virtual bool EqualsIterator(const Field* data,
- const Iterator* a,
- const Iterator* b) const {
+ bool EqualsIterator(const Field* data, const Iterator* a,
+ const Iterator* b) const override {
return a == b;
}
- virtual void DeleteIterator(const Field* data, Iterator* iterator) const {
- }
- virtual const Value* GetIteratorValue(const Field* data,
- const Iterator* iterator,
- Value* scratch_space) const {
+ void DeleteIterator(const Field* data, Iterator* iterator) const override {}
+ const Value* GetIteratorValue(const Field* data, const Iterator* iterator,
+ Value* scratch_space) const override {
return Get(data, static_cast<int>(IteratorToPosition(iterator)),
scratch_space);
}
+ protected:
+ ~RandomAccessRepeatedFieldAccessor() = default;
+
private:
static intptr_t IteratorToPosition(const Iterator* iterator) {
return reinterpret_cast<intptr_t>(iterator);
@@ -88,34 +86,34 @@ template<typename T>
class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor {
public:
RepeatedFieldWrapper() {}
- virtual ~RepeatedFieldWrapper() {}
- virtual bool IsEmpty(const Field* data) const {
+ bool IsEmpty(const Field* data) const override {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
- virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ const Value* Get(const Field* data, int index,
+ Value* scratch_space) const override {
return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ void Set(Field* data, int index, const Value* value) const override {
MutableRepeatedField(data)->Set(index, ConvertToT(value));
}
- virtual void Add(Field* data, const Value* value) const {
+ void Add(Field* data, const Value* value) const override {
MutableRepeatedField(data)->Add(ConvertToT(value));
}
- virtual void RemoveLast(Field* data) const {
+ void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ void SwapElements(Field* data, int index1, int index2) const override {
MutableRepeatedField(data)->SwapElements(index1, index2);
}
protected:
+ ~RepeatedFieldWrapper() = default;
typedef RepeatedField<T> RepeatedFieldType;
static const RepeatedFieldType* GetRepeatedField(const Field* data) {
return reinterpret_cast<const RepeatedFieldType*>(data);
@@ -142,37 +140,36 @@ class RepeatedFieldWrapper : public RandomAccessRepeatedFieldAccessor {
template<typename T>
class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor {
public:
- RepeatedPtrFieldWrapper() {}
- virtual ~RepeatedPtrFieldWrapper() {}
- virtual bool IsEmpty(const Field* data) const {
+ bool IsEmpty(const Field* data) const override {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
- virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ const Value* Get(const Field* data, int index,
+ Value* scratch_space) const override {
return ConvertFromT(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ void Set(Field* data, int index, const Value* value) const override {
ConvertToT(value, MutableRepeatedField(data)->Mutable(index));
}
- virtual void Add(Field* data, const Value* value) const {
+ void Add(Field* data, const Value* value) const override {
T* allocated = New(value);
ConvertToT(value, allocated);
MutableRepeatedField(data)->AddAllocated(allocated);
}
- virtual void RemoveLast(Field* data) const {
+ void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ void SwapElements(Field* data, int index1, int index2) const override {
MutableRepeatedField(data)->SwapElements(index1, index2);
}
protected:
+ ~RepeatedPtrFieldWrapper() = default;
typedef RepeatedPtrField<T> RepeatedFieldType;
static const RepeatedFieldType* GetRepeatedField(const Field* data) {
return reinterpret_cast<const RepeatedFieldType*>(data);
@@ -202,41 +199,39 @@ class RepeatedPtrFieldWrapper : public RandomAccessRepeatedFieldAccessor {
// An implementation of RandomAccessRepeatedFieldAccessor that manipulates
// MapFieldBase.
-class MapFieldAccessor : public RandomAccessRepeatedFieldAccessor {
+class MapFieldAccessor final : public RandomAccessRepeatedFieldAccessor {
public:
MapFieldAccessor() {}
virtual ~MapFieldAccessor() {}
virtual bool IsEmpty(const Field* data) const {
return GetRepeatedField(data)->empty();
}
- virtual int Size(const Field* data) const {
+ int Size(const Field* data) const override {
return GetRepeatedField(data)->size();
}
- virtual const Value* Get(const Field* data, int index,
- Value* scratch_space) const {
+ const Value* Get(const Field* data, int index,
+ Value* scratch_space) const override {
return ConvertFromEntry(GetRepeatedField(data)->Get(index), scratch_space);
}
- virtual void Clear(Field* data) const {
+ void Clear(Field* data) const override {
MutableRepeatedField(data)->Clear();
}
- virtual void Set(Field* data, int index, const Value* value) const {
+ void Set(Field* data, int index, const Value* value) const override {
ConvertToEntry(value, MutableRepeatedField(data)->Mutable(index));
}
- virtual void Add(Field* data, const Value* value) const {
+ void Add(Field* data, const Value* value) const override {
Message* allocated = New(value);
ConvertToEntry(value, allocated);
MutableRepeatedField(data)->AddAllocated(allocated);
}
- virtual void RemoveLast(Field* data) const {
+ void RemoveLast(Field* data) const override {
MutableRepeatedField(data)->RemoveLast();
}
- virtual void SwapElements(Field* data, int index1, int index2) const {
+ void SwapElements(Field* data, int index1, int index2) const override {
MutableRepeatedField(data)->SwapElements(index1, index2);
}
- virtual void Swap(
- Field* data,
- const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator,
+ Field* other_data) const override {
GOOGLE_CHECK(this == other_mutator);
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
}
@@ -268,19 +263,16 @@ class MapFieldAccessor : public RandomAccessRepeatedFieldAccessor {
};
// Default implementations of RepeatedFieldAccessor for primitive types.
-template<typename T>
-class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper<T> {
+template <typename T>
+class RepeatedFieldPrimitiveAccessor final : public RepeatedFieldWrapper<T> {
typedef void Field;
typedef void Value;
using RepeatedFieldWrapper<T>::MutableRepeatedField;
public:
RepeatedFieldPrimitiveAccessor() {}
- virtual ~RepeatedFieldPrimitiveAccessor() {}
- virtual void Swap(
- Field* data,
- const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator,
+ Field* other_data) const override {
// Currently RepeatedFieldPrimitiveAccessor is the only implementation of
// RepeatedFieldAccessor for primitive types. As we are using singletons
// for these accessors, here "other_mutator" must be "this".
@@ -289,90 +281,83 @@ class RepeatedFieldPrimitiveAccessor : public RepeatedFieldWrapper<T> {
}
protected:
- virtual T ConvertToT(const Value* value) const {
+ T ConvertToT(const Value* value) const override {
return *static_cast<const T*>(value);
}
- virtual const Value* ConvertFromT(const T& value,
- Value* scratch_space) const {
+ const Value* ConvertFromT(const T& value,
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
// Default implementation of RepeatedFieldAccessor for string fields with
// ctype=STRING.
-class RepeatedPtrFieldStringAccessor : public RepeatedPtrFieldWrapper<string> {
+class RepeatedPtrFieldStringAccessor final
+ : public RepeatedPtrFieldWrapper<std::string> {
typedef void Field;
typedef void Value;
using RepeatedFieldAccessor::Add;
public:
RepeatedPtrFieldStringAccessor() {}
- virtual ~RepeatedPtrFieldStringAccessor() {}
- virtual void Swap(
- Field* data,
- const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator,
+ Field* other_data) const override {
if (this == other_mutator) {
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
} else {
- RepeatedPtrField<string> tmp;
+ RepeatedPtrField<std::string> tmp;
tmp.Swap(MutableRepeatedField(data));
int other_size = other_mutator->Size(other_data);
for (int i = 0; i < other_size; ++i) {
- Add<string>(data, other_mutator->Get<string>(other_data, i));
+ Add<std::string>(data, other_mutator->Get<std::string>(other_data, i));
}
int size = Size(data);
other_mutator->Clear(other_data);
for (int i = 0; i < size; ++i) {
- other_mutator->Add<string>(other_data, tmp.Get(i));
+ other_mutator->Add<std::string>(other_data, tmp.Get(i));
}
}
}
protected:
- virtual string* New(const Value*) const {
- return new string();
- }
- virtual void ConvertToT(const Value* value, string* result) const {
- *result = *static_cast<const string*>(value);
+ std::string* New(const Value*) const override { return new std::string(); }
+ void ConvertToT(const Value* value, std::string* result) const override {
+ *result = *static_cast<const std::string*>(value);
}
- virtual const Value* ConvertFromT(const string& value,
- Value* scratch_space) const {
+ const Value* ConvertFromT(const std::string& value,
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
-class RepeatedPtrFieldMessageAccessor
+class RepeatedPtrFieldMessageAccessor final
: public RepeatedPtrFieldWrapper<Message> {
typedef void Field;
typedef void Value;
public:
RepeatedPtrFieldMessageAccessor() {}
- virtual ~RepeatedPtrFieldMessageAccessor() {}
- virtual void Swap(
- Field* data,
- const internal::RepeatedFieldAccessor* other_mutator,
- Field* other_data) const {
+ void Swap(Field* data, const internal::RepeatedFieldAccessor* other_mutator,
+ Field* other_data) const override {
GOOGLE_CHECK(this == other_mutator);
MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));
}
protected:
- virtual Message* New(const Value* value) const {
+ Message* New(const Value* value) const override {
return static_cast<const Message*>(value)->New();
}
- virtual void ConvertToT(const Value* value, Message* result) const {
+ void ConvertToT(const Value* value, Message* result) const override {
result->CopyFrom(*static_cast<const Message*>(value));
}
- virtual const Value* ConvertFromT(const Message& value,
- Value* scratch_space) const {
+ const Value* ConvertFromT(const Message& value,
+ Value* scratch_space) const override {
return static_cast<const Value*>(&value);
}
};
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_REFLECTION_INTERNAL_H__
diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc
index 3cd50340..f028b2b0 100644
--- a/src/google/protobuf/reflection_ops.cc
+++ b/src/google/protobuf/reflection_ops.cc
@@ -41,6 +41,7 @@
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/map_field.h>
+#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/stubs/strutil.h>
diff --git a/src/google/protobuf/reflection_ops.h b/src/google/protobuf/reflection_ops.h
index 45d8c650..b30c050a 100644
--- a/src/google/protobuf/reflection_ops.h
+++ b/src/google/protobuf/reflection_ops.h
@@ -41,6 +41,12 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/message.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -54,7 +60,7 @@ namespace internal {
// the Message interface.
//
// This class is really a namespace that contains only static methods.
-class LIBPROTOBUF_EXPORT ReflectionOps {
+class PROTOBUF_EXPORT ReflectionOps {
public:
static void Copy(const Message& from, Message* to);
static void Merge(const Message& from, Message* to);
@@ -66,8 +72,8 @@ class LIBPROTOBUF_EXPORT ReflectionOps {
// paths (e.g. "foo.bar[5].baz") to *names. "prefix" will be attached to
// the front of each name.
static void FindInitializationErrors(const Message& message,
- const string& prefix,
- std::vector<string>* errors);
+ const std::string& prefix,
+ std::vector<std::string>* errors);
private:
// All methods are static. No need to construct.
@@ -76,6 +82,8 @@ class LIBPROTOBUF_EXPORT ReflectionOps {
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_REFLECTION_OPS_H__
diff --git a/src/google/protobuf/repeated_field.cc b/src/google/protobuf/repeated_field.cc
index 310000aa..e09f3e6a 100644
--- a/src/google/protobuf/repeated_field.cc
+++ b/src/google/protobuf/repeated_field.cc
@@ -38,6 +38,8 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -62,8 +64,7 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) {
if (arena == NULL) {
rep_ = reinterpret_cast<Rep*>(::operator new(bytes));
} else {
- rep_ = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena, bytes));
+ rep_ = reinterpret_cast<Rep*>(Arena::CreateArray<char>(arena, bytes));
}
#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
const int old_total_size = total_size_;
@@ -103,18 +104,17 @@ void RepeatedPtrFieldBase::CloseGap(int start, int num) {
rep_->allocated_size -= num;
}
-google::protobuf::MessageLite* RepeatedPtrFieldBase::AddWeak(
- const google::protobuf::MessageLite* prototype) {
+MessageLite* RepeatedPtrFieldBase::AddWeak(const MessageLite* prototype) {
if (rep_ != NULL && current_size_ < rep_->allocated_size) {
- return reinterpret_cast<google::protobuf::MessageLite*>(
- rep_->elements[current_size_++]);
+ return reinterpret_cast<MessageLite*>(rep_->elements[current_size_++]);
}
if (!rep_ || rep_->allocated_size == total_size_) {
Reserve(total_size_ + 1);
}
++rep_->allocated_size;
- google::protobuf::MessageLite* result = prototype ? prototype->New(arena_) :
- Arena::CreateMessage<ImplicitWeakMessage>(arena_);
+ MessageLite* result = prototype
+ ? prototype->New(arena_)
+ : Arena::CreateMessage<ImplicitWeakMessage>(arena_);
rep_->elements[current_size_++] = result;
return result;
}
@@ -122,5 +122,14 @@ google::protobuf::MessageLite* RepeatedPtrFieldBase::AddWeak(
} // namespace internal
+template class PROTOBUF_EXPORT RepeatedField<bool>;
+template class PROTOBUF_EXPORT RepeatedField<int32>;
+template class PROTOBUF_EXPORT RepeatedField<uint32>;
+template class PROTOBUF_EXPORT RepeatedField<int64>;
+template class PROTOBUF_EXPORT RepeatedField<uint64>;
+template class PROTOBUF_EXPORT RepeatedField<float>;
+template class PROTOBUF_EXPORT RepeatedField<double>;
+template class PROTOBUF_EXPORT RepeatedPtrField<string>;
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index fbfbf942..42144222 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -46,6 +46,7 @@
#ifndef GOOGLE_PROTOBUF_REPEATED_FIELD_H__
#define GOOGLE_PROTOBUF_REPEATED_FIELD_H__
+#include <utility>
#ifdef _MSC_VER
// This is required for min/max on VS2013 only.
#include <algorithm>
@@ -54,24 +55,30 @@
#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/arena.h>
#include <google/protobuf/implicit_weak_message.h>
#include <google/protobuf/message_lite.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
+#include <google/protobuf/stubs/casts.h>
#include <type_traits>
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
// Forward-declare these so that we can make them friends.
-namespace google {
namespace upb {
namespace google_opensource {
class GMR_Handlers;
} // namespace google_opensource
} // namespace upb
+namespace google {
namespace protobuf {
class Message;
@@ -246,9 +253,7 @@ class RepeatedField final {
iterator erase(const_iterator first, const_iterator last);
// Get the Arena on which this RepeatedField stores its elements.
- ::google::protobuf::Arena* GetArena() const {
- return GetArenaNoVirtual();
- }
+ Arena* GetArena() const { return GetArenaNoVirtual(); }
// For internal use only.
//
@@ -280,16 +285,23 @@ class RepeatedField final {
static const size_t kRepHeaderSize;
// We reuse the Rep* for an Arena* when total_size == 0, to avoid having to do
- // an allocation in the constructor when we have an Arena.
+ // an allocation in the constructor when we have an Arena.
union Pointer {
Pointer(Arena* a) : arena(a) {}
- Arena* arena; // When total_size_ == 0.
- Rep* rep; // When total_size_ != 0.
+ Arena* arena; // When total_size_ == 0.
+ Element* elements; // When total_size_ != 0, this is Rep->elements of Rep.
} ptr_;
+ Element* elements() const {
+ GOOGLE_DCHECK_GT(total_size_, 0);
+ return ptr_.elements;
+ }
+
Rep* rep() const {
GOOGLE_DCHECK_GT(total_size_, 0);
- return ptr_.rep;
+ char* addr =
+ reinterpret_cast<char*>(ptr_.elements) - offsetof(Rep, elements);
+ return reinterpret_cast<Rep*>(addr);
}
friend class Arena;
@@ -306,7 +318,7 @@ class RepeatedField final {
// Internal helper expected by Arena methods.
inline Arena* GetArenaNoVirtual() const {
- return (total_size_ == 0) ? ptr_.arena : ptr_.rep->arena;
+ return (total_size_ == 0) ? ptr_.arena : rep()->arena;
}
// Internal helper to delete all elements and deallocate the storage.
@@ -413,7 +425,7 @@ struct TypeImplementsMergeBehavior< ::std::string> {
// typedef MyType WeakType;
// static Type* New();
// static WeakType* NewFromPrototype(const WeakType* prototype,
-// ::google::protobuf::Arena* arena);
+// Arena* arena);
// static void Delete(Type*);
// static void Clear(Type*);
// static void Merge(const Type& from, Type* to);
@@ -421,10 +433,10 @@ struct TypeImplementsMergeBehavior< ::std::string> {
// // Only needs to be implemented if SpaceUsedExcludingSelf() is called.
// static int SpaceUsedLong(const Type&);
// };
-class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
+class PROTOBUF_EXPORT RepeatedPtrFieldBase {
protected:
RepeatedPtrFieldBase();
- explicit RepeatedPtrFieldBase(::google::protobuf::Arena* arena);
+ explicit RepeatedPtrFieldBase(Arena* arena);
~RepeatedPtrFieldBase() {}
// Must be called from destructor.
@@ -453,7 +465,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
// a link-time dependency on the concrete message type. This method is used to
// implement implicit weak fields. The prototype may be NULL, in which case an
// ImplicitWeakMessage will be used as a placeholder.
- google::protobuf::MessageLite* AddWeak(const google::protobuf::MessageLite* prototype);
+ MessageLite* AddWeak(const MessageLite* prototype);
template <typename TypeHandler>
void Clear();
@@ -466,7 +478,7 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
protected:
template <typename TypeHandler>
void Add(typename TypeHandler::Type&& value,
- std::enable_if<TypeHandler::Moveable>* dummy = NULL);
+ typename std::enable_if<TypeHandler::Moveable>::type* dummy = NULL);
template <typename TypeHandler>
void RemoveLast();
@@ -488,8 +500,8 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
const typename TypeHandler::Type* const* data() const;
- template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- void Swap(RepeatedPtrFieldBase* other);
+ template <typename TypeHandler>
+ PROTOBUF_ALWAYS_INLINE void Swap(RepeatedPtrFieldBase* other);
void SwapElements(int index1, int index2);
@@ -533,20 +545,21 @@ class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase {
template <typename TypeHandler>
void AddAllocatedInternal(typename TypeHandler::Type* value, std::false_type);
- template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
- void AddAllocatedSlowWithCopy(typename TypeHandler::Type* value,
- Arena* value_arena,
- Arena* my_arena);
- template <typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
- void AddAllocatedSlowWithoutCopy(typename TypeHandler::Type* value);
+ template <typename TypeHandler>
+ PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy(
+ typename TypeHandler::Type* value, Arena* value_arena, Arena* my_arena);
+ template <typename TypeHandler>
+ PROTOBUF_NOINLINE void AddAllocatedSlowWithoutCopy(
+ typename TypeHandler::Type* value);
template <typename TypeHandler>
typename TypeHandler::Type* ReleaseLastInternal(std::true_type);
template <typename TypeHandler>
typename TypeHandler::Type* ReleaseLastInternal(std::false_type);
- template<typename TypeHandler> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
- void SwapFallback(RepeatedPtrFieldBase* other);
+ template <typename TypeHandler>
+ PROTOBUF_NOINLINE void SwapFallback(
+ RepeatedPtrFieldBase* other);
inline Arena* GetArenaNoVirtual() const {
return arena_;
@@ -640,24 +653,24 @@ class GenericTypeHandler {
static const bool Moveable = false;
static inline GenericType* New(Arena* arena) {
- return ::google::protobuf::Arena::CreateMaybeMessage<Type>(arena);
+ return Arena::CreateMaybeMessage<Type>(arena);
}
- static inline GenericType* NewFromPrototype(
- const GenericType* prototype, ::google::protobuf::Arena* arena = NULL);
+ static inline GenericType* NewFromPrototype(const GenericType* prototype,
+ Arena* arena = NULL);
static inline void Delete(GenericType* value, Arena* arena) {
if (arena == NULL) {
delete value;
}
}
- static inline ::google::protobuf::Arena* GetArena(GenericType* value) {
- return ::google::protobuf::Arena::GetArena<Type>(value);
+ static inline Arena* GetArena(GenericType* value) {
+ return Arena::GetArena<Type>(value);
}
static inline void* GetMaybeArenaPointer(GenericType* value) {
- return ::google::protobuf::Arena::GetArena<Type>(value);
+ return Arena::GetArena<Type>(value);
}
static inline void Clear(GenericType* value) { value->Clear(); }
- GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
+ PROTOBUF_NOINLINE
static void Merge(const GenericType& from, GenericType* to);
static inline size_t SpaceUsedLong(const GenericType& value) {
return value.SpaceUsedLong();
@@ -666,7 +679,7 @@ class GenericTypeHandler {
template <typename GenericType>
GenericType* GenericTypeHandler<GenericType>::NewFromPrototype(
- const GenericType* /* prototype */, ::google::protobuf::Arena* arena) {
+ const GenericType* /* prototype */, Arena* arena) {
return New(arena);
}
template <typename GenericType>
@@ -678,12 +691,11 @@ void GenericTypeHandler<GenericType>::Merge(const GenericType& from,
// 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<>
+template <>
MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
- const MessageLite* prototype, google::protobuf::Arena* arena);
-template<>
-inline google::protobuf::Arena* GenericTypeHandler<MessageLite>::GetArena(
- MessageLite* value) {
+ const MessageLite* prototype, Arena* arena);
+template <>
+inline Arena* GenericTypeHandler<MessageLite>::GetArena(MessageLite* value) {
return value->GetArena();
}
template<>
@@ -695,25 +707,25 @@ template <>
void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
MessageLite* to);
template<>
-inline void GenericTypeHandler<string>::Clear(string* value) {
+inline void GenericTypeHandler<std::string>::Clear(std::string* value) {
value->clear();
}
template<>
-void GenericTypeHandler<string>::Merge(const string& from,
- string* to);
+void GenericTypeHandler<std::string>::Merge(const std::string& from,
+ std::string* to);
// Declarations of the specialization as we cannot define them here, as the
// header that defines ProtocolMessage depends on types defined in this header.
-#define DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(TypeName) \
- template<> LIBPROTOBUF_EXPORT \
- TypeName* GenericTypeHandler<TypeName>::NewFromPrototype( \
- const TypeName* prototype, google::protobuf::Arena* arena); \
- template<> LIBPROTOBUF_EXPORT \
- google::protobuf::Arena* GenericTypeHandler<TypeName>::GetArena( \
- TypeName* value); \
- template<> LIBPROTOBUF_EXPORT \
- void* GenericTypeHandler<TypeName>::GetMaybeArenaPointer( \
- TypeName* value);
+#define DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(TypeName) \
+ template <> \
+ PROTOBUF_EXPORT TypeName* GenericTypeHandler<TypeName>::NewFromPrototype( \
+ const TypeName* prototype, Arena* arena); \
+ template <> \
+ PROTOBUF_EXPORT Arena* GenericTypeHandler<TypeName>::GetArena( \
+ TypeName* value); \
+ template <> \
+ PROTOBUF_EXPORT void* GenericTypeHandler<TypeName>::GetMaybeArenaPointer( \
+ TypeName* value);
// Message specialization bodies defined in message.cc. This split is necessary
// to allow proto2-lite (which includes this header) to be independent of
@@ -725,35 +737,32 @@ DECLARE_SPECIALIZATIONS_FOR_BASE_PROTO_TYPES(Message)
class StringTypeHandler {
public:
- typedef string Type;
- typedef string WeakType;
+ typedef std::string Type;
+ typedef std::string WeakType;
static const bool Moveable = std::is_move_constructible<Type>::value &&
std::is_move_assignable<Type>::value;
- static inline string* New(Arena* arena) {
- return Arena::Create<string>(arena);
+ static inline std::string* New(Arena* arena) {
+ return Arena::Create<std::string>(arena);
}
- static inline string* New(Arena* arena, string&& value) {
- return Arena::Create<string>(arena, std::move(value));
+ static inline std::string* New(Arena* arena, std::string&& value) {
+ return Arena::Create<std::string>(arena, std::move(value));
}
- static inline string* NewFromPrototype(const string*,
- ::google::protobuf::Arena* arena) {
+ static inline std::string* NewFromPrototype(const std::string*, Arena* arena) {
return New(arena);
}
- static inline ::google::protobuf::Arena* GetArena(string*) {
- return NULL;
- }
- static inline void* GetMaybeArenaPointer(string* /* value */) {
+ static inline Arena* GetArena(std::string*) { return NULL; }
+ static inline void* GetMaybeArenaPointer(std::string* /* value */) {
return NULL;
}
- static inline void Delete(string* value, Arena* arena) {
+ static inline void Delete(std::string* value, Arena* arena) {
if (arena == NULL) {
delete value;
}
}
- static inline void Clear(string* value) { value->clear(); }
- static inline void Merge(const string& from, string* to) { *to = from; }
- static size_t SpaceUsedLong(const string& value) {
+ static inline void Clear(std::string* value) { value->clear(); }
+ static inline void Merge(const std::string& from, std::string* to) { *to = from; }
+ static size_t SpaceUsedLong(const std::string& value) {
return sizeof(value) + StringSpaceUsedExcludingSelfLong(value);
}
};
@@ -766,7 +775,7 @@ template <typename Element>
class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
public:
RepeatedPtrField();
- explicit RepeatedPtrField(::google::protobuf::Arena* arena);
+ explicit RepeatedPtrField(Arena* arena);
RepeatedPtrField(const RepeatedPtrField& other);
template <typename Iter>
@@ -992,9 +1001,7 @@ class RepeatedPtrField final : private internal::RepeatedPtrFieldBase {
iterator erase(const_iterator first, const_iterator last);
// Gets the arena on which this RepeatedPtrField stores its elements.
- ::google::protobuf::Arena* GetArena() const {
- return GetArenaNoVirtual();
- }
+ Arena* GetArena() const { return GetArenaNoVirtual(); }
// For internal use only.
//
@@ -1131,22 +1138,27 @@ inline int RepeatedField<Element>::Capacity() const {
template<typename Element>
inline void RepeatedField<Element>::AddAlreadyReserved(const Element& value) {
GOOGLE_DCHECK_LT(current_size_, total_size_);
- rep()->elements[current_size_++] = value;
+ elements()[current_size_++] = value;
}
template<typename Element>
inline Element* RepeatedField<Element>::AddAlreadyReserved() {
GOOGLE_DCHECK_LT(current_size_, total_size_);
- return &rep()->elements[current_size_++];
+ return &elements()[current_size_++];
}
template<typename Element>
-inline Element* RepeatedField<Element>::AddNAlreadyReserved(int elements) {
- GOOGLE_DCHECK_LE(current_size_ + elements, total_size_);
- // Warning: total_size_ can be NULL if elements == 0 && current_size_ == 0.
- // Existing callers depend on this behavior. :(
- Element* ret = &ptr_.rep->elements[current_size_];
- current_size_ += elements;
+inline Element* RepeatedField<Element>::AddNAlreadyReserved(int n) {
+ GOOGLE_DCHECK_GE(total_size_ - current_size_, n)
+ << total_size_ << ", " << current_size_;
+ // Warning: sometimes people call this when n==0 and total_size_==0. This
+ // forces us to add this branch, to avoid reading the non-active union member
+ // (which is UB). Luckily the compiler is smart enough to optimize the branch
+ // away.
+ Element* ret =
+ total_size_ == 0 ? reinterpret_cast<Element*>(ptr_.arena) : ptr_.elements;
+ ret += current_size_;
+ current_size_ += n;
return ret;
}
@@ -1155,8 +1167,7 @@ inline void RepeatedField<Element>::Resize(int new_size, const Element& value) {
GOOGLE_DCHECK_GE(new_size, 0);
if (new_size > current_size_) {
Reserve(new_size);
- std::fill(&rep()->elements[current_size_],
- &rep()->elements[new_size], value);
+ std::fill(&elements()[current_size_], &elements()[new_size], value);
}
current_size_ = new_size;
}
@@ -1165,33 +1176,33 @@ template <typename Element>
inline const Element& RepeatedField<Element>::Get(int index) const {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- return rep()->elements[index];
+ return elements()[index];
}
template <typename Element>
inline Element* RepeatedField<Element>::Mutable(int index) {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- return &rep()->elements[index];
+ return &elements()[index];
}
template <typename Element>
inline void RepeatedField<Element>::Set(int index, const Element& value) {
GOOGLE_DCHECK_GE(index, 0);
GOOGLE_DCHECK_LT(index, current_size_);
- rep()->elements[index] = value;
+ elements()[index] = value;
}
template <typename Element>
inline void RepeatedField<Element>::Add(const Element& value) {
if (current_size_ == total_size_) Reserve(total_size_ + 1);
- rep()->elements[current_size_++] = value;
+ elements()[current_size_++] = value;
}
template <typename Element>
inline Element* RepeatedField<Element>::Add() {
if (current_size_ == total_size_) Reserve(total_size_ + 1);
- return &rep()->elements[current_size_++];
+ return &elements()[current_size_++];
}
template <typename Element>
@@ -1262,17 +1273,17 @@ inline typename RepeatedField<Element>::iterator RepeatedField<Element>::erase(
template <typename Element>
inline Element* RepeatedField<Element>::mutable_data() {
- return total_size_ > 0 ? rep()->elements : NULL;
+ return total_size_ > 0 ? elements() : NULL;
}
template <typename Element>
inline const Element* RepeatedField<Element>::data() const {
- return total_size_ > 0 ? rep()->elements : NULL;
+ return total_size_ > 0 ? elements() : NULL;
}
template <typename Element>
inline const Element* RepeatedField<Element>::unsafe_data() const {
- return rep()->elements;
+ return elements();
}
template <typename Element>
@@ -1307,38 +1318,38 @@ void RepeatedField<Element>::UnsafeArenaSwap(RepeatedField* other) {
template <typename Element>
void RepeatedField<Element>::SwapElements(int index1, int index2) {
using std::swap; // enable ADL with fallback
- swap(rep()->elements[index1], rep()->elements[index2]);
+ swap(elements()[index1], elements()[index2]);
}
template <typename Element>
inline typename RepeatedField<Element>::iterator
RepeatedField<Element>::begin() {
- return total_size_ > 0 ? rep()->elements : NULL;
+ return total_size_ > 0 ? elements() : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::begin() const {
- return total_size_ > 0 ? rep()->elements : NULL;
+ return total_size_ > 0 ? elements() : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::cbegin() const {
- return total_size_ > 0 ? rep()->elements : NULL;
+ return total_size_ > 0 ? elements() : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::iterator
RepeatedField<Element>::end() {
- return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
+ return total_size_ > 0 ? elements() + current_size_ : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::end() const {
- return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
+ return total_size_ > 0 ? elements() + current_size_ : NULL;
}
template <typename Element>
inline typename RepeatedField<Element>::const_iterator
RepeatedField<Element>::cend() const {
- return total_size_ > 0 ? rep()->elements + current_size_ : NULL;
+ return total_size_ > 0 ? elements() + current_size_ : NULL;
}
template <typename Element>
@@ -1352,8 +1363,9 @@ template <typename Element>
void RepeatedField<Element>::Reserve(int new_size) {
if (total_size_ >= new_size) return;
Rep* old_rep = total_size_ > 0 ? rep() : NULL;
+ Rep* new_rep;
Arena* arena = GetArenaNoVirtual();
- new_size = std::max(google::protobuf::internal::kMinRepeatedFieldAllocationSize,
+ new_size = std::max(internal::kMinRepeatedFieldAllocationSize,
std::max(total_size_ * 2, new_size));
GOOGLE_DCHECK_LE(
static_cast<size_t>(new_size),
@@ -1361,14 +1373,14 @@ void RepeatedField<Element>::Reserve(int new_size) {
<< "Requested size is too large to fit into size_t.";
size_t bytes = kRepHeaderSize + sizeof(Element) * static_cast<size_t>(new_size);
if (arena == NULL) {
- ptr_.rep = static_cast<Rep*>(::operator new(bytes));
+ new_rep = static_cast<Rep*>(::operator new(bytes));
} else {
- ptr_.rep = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena, bytes));
+ new_rep = reinterpret_cast<Rep*>(Arena::CreateArray<char>(arena, bytes));
}
- ptr_.rep->arena = arena;
+ new_rep->arena = arena;
int old_total_size = total_size_;
total_size_ = new_size;
+ ptr_.elements = new_rep->elements;
// Invoke placement-new on newly allocated elements. We shouldn't have to do
// this, since Element is supposed to be POD, but a previous version of this
// code allocated storage with "new Element[size]" and some code uses
@@ -1378,13 +1390,13 @@ void RepeatedField<Element>::Reserve(int new_size) {
// effect unless its side-effects are required for correctness.
// Note that we do this before MoveArray() below because Element's copy
// assignment implementation will want an initialized instance first.
- Element* e = &rep()->elements[0];
+ Element* e = &elements()[0];
Element* limit = e + total_size_;
for (; e < limit; e++) {
new (e) Element;
}
if (current_size_ > 0) {
- MoveArray(&rep()->elements[0], old_rep->elements, current_size_);
+ MoveArray(&elements()[0], old_rep->elements, current_size_);
}
// Likewise, we need to invoke destructors on the old array.
@@ -1441,12 +1453,8 @@ inline RepeatedPtrFieldBase::RepeatedPtrFieldBase()
rep_(NULL) {
}
-inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(::google::protobuf::Arena* arena)
- : arena_(arena),
- current_size_(0),
- total_size_(0),
- rep_(NULL) {
-}
+inline RepeatedPtrFieldBase::RepeatedPtrFieldBase(Arena* arena)
+ : arena_(arena), current_size_(0), total_size_(0), rep_(NULL) {}
template <typename TypeHandler>
void RepeatedPtrFieldBase::Destroy() {
@@ -1541,7 +1549,7 @@ inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add(
template <typename TypeHandler>
inline void RepeatedPtrFieldBase::Add(
typename TypeHandler::Type&& value,
- std::enable_if<TypeHandler::Moveable>*) {
+ typename std::enable_if<TypeHandler::Moveable>::type*) {
if (rep_ != NULL && current_size_ < rep_->allocated_size) {
*cast<TypeHandler>(rep_->elements[current_size_++]) = std::move(value);
return;
@@ -1878,7 +1886,7 @@ class RepeatedPtrField<Element>::TypeHandler
};
template <>
-class RepeatedPtrField<string>::TypeHandler
+class RepeatedPtrField<std::string>::TypeHandler
: public internal::StringTypeHandler {
};
@@ -1887,8 +1895,8 @@ inline RepeatedPtrField<Element>::RepeatedPtrField()
: RepeatedPtrFieldBase() {}
template <typename Element>
-inline RepeatedPtrField<Element>::RepeatedPtrField(::google::protobuf::Arena* arena) :
- RepeatedPtrFieldBase(arena) {}
+inline RepeatedPtrField<Element>::RepeatedPtrField(Arena* arena)
+ : RepeatedPtrFieldBase(arena) {}
template <typename Element>
inline RepeatedPtrField<Element>::RepeatedPtrField(
@@ -2233,7 +2241,7 @@ class RepeatedPtrIterator
: it_(other.it_) {
// Force a compiler error if the other type is not convertible to ours.
if (false) {
- implicit_cast<Element*>(static_cast<OtherElement*>(nullptr));
+ ::google::protobuf::implicit_cast<Element*>(static_cast<OtherElement*>(nullptr));
}
}
@@ -2440,13 +2448,12 @@ RepeatedPtrField<Element>::pointer_end() const {
const_cast<const void* const*>(raw_data() + size()));
}
-
// Iterators and helper functions that follow the spirit of the STL
// std::back_insert_iterator and std::back_inserter but are tailor-made
// for RepeatedField and RepeatedPtrField. Typical usage would be:
//
// std::copy(some_sequence.begin(), some_sequence.end(),
-// google::protobuf::RepeatedFieldBackInserter(proto.mutable_sequence()));
+// RepeatedFieldBackInserter(proto.mutable_sequence()));
//
// Ported by johannes from util/gtl/proto-array-iterators.h
@@ -2548,9 +2555,8 @@ class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator
: public std::iterator<std::output_iterator_tag, T> {
public:
explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator(
- ::google::protobuf::RepeatedPtrField<T>* const mutable_field)
- : field_(mutable_field) {
- }
+ RepeatedPtrField<T>* const mutable_field)
+ : field_(mutable_field) {}
UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=(
T const* const ptr_to_value) {
field_->UnsafeArenaAddAllocated(const_cast<T*>(ptr_to_value));
@@ -2568,7 +2574,7 @@ class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator
}
private:
- ::google::protobuf::RepeatedPtrField<T>* field_;
+ RepeatedPtrField<T>* field_;
};
} // namespace internal
@@ -2616,15 +2622,27 @@ AllocatedRepeatedPtrFieldBackInserter(
// If you put temp_field on the arena this fails, because the ownership
// transfers to the arena at the "AddAllocated" call and is not released anymore
// causing a double delete. Using UnsafeArenaAddAllocated prevents this.
-template<typename T>
+template <typename T>
internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>
UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(
- ::google::protobuf::RepeatedPtrField<T>* const mutable_field) {
+ RepeatedPtrField<T>* const mutable_field) {
return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>(
mutable_field);
}
-} // namespace protobuf
+// Extern declarations of common instantiations to reduce libray bloat.
+extern template class PROTOBUF_EXPORT RepeatedField<bool>;
+extern template class PROTOBUF_EXPORT RepeatedField<int32>;
+extern template class PROTOBUF_EXPORT RepeatedField<uint32>;
+extern template class PROTOBUF_EXPORT RepeatedField<int64>;
+extern template class PROTOBUF_EXPORT RepeatedField<uint64>;
+extern template class PROTOBUF_EXPORT RepeatedField<float>;
+extern template class PROTOBUF_EXPORT RepeatedField<double>;
+extern template class PROTOBUF_EXPORT RepeatedPtrField<std::string>;
+} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_REPEATED_FIELD_H__
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc
index 053a4d68..fa86c593 100644
--- a/src/google/protobuf/repeated_field_unittest.cc
+++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -45,10 +45,10 @@
#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 {
diff --git a/src/google/protobuf/service.cc b/src/google/protobuf/service.cc
index ffa919da..a6616b40 100644
--- a/src/google/protobuf/service.cc
+++ b/src/google/protobuf/service.cc
@@ -42,5 +42,5 @@ RpcChannel::~RpcChannel() {}
RpcController::~RpcController() {}
} // namespace protobuf
-
} // namespace google
+
diff --git a/src/google/protobuf/service.h b/src/google/protobuf/service.h
index ad6f9685..0792817a 100644
--- a/src/google/protobuf/service.h
+++ b/src/google/protobuf/service.h
@@ -104,6 +104,12 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/callback.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -123,7 +129,7 @@ class Message; // message.h
// stubs), but they subclass this base interface. The methods of this
// interface can be used to call the methods of the Service without knowing
// its exact type at compile time (analogous to Reflection).
-class LIBPROTOBUF_EXPORT Service {
+class PROTOBUF_EXPORT Service {
public:
inline Service() {}
virtual ~Service();
@@ -200,7 +206,7 @@ class LIBPROTOBUF_EXPORT Service {
// "least common denominator" set of features which we expect all
// implementations to support. Specific implementations may provide more
// advanced features (e.g. deadline propagation).
-class LIBPROTOBUF_EXPORT RpcController {
+class PROTOBUF_EXPORT RpcController {
public:
inline RpcController() {}
virtual ~RpcController();
@@ -220,7 +226,7 @@ class LIBPROTOBUF_EXPORT RpcController {
virtual bool Failed() const = 0;
// If Failed() is true, returns a human-readable description of the error.
- virtual string ErrorText() const = 0;
+ virtual std::string ErrorText() const = 0;
// Advises the RPC system that the caller desires that the RPC call be
// canceled. The RPC system may cancel it immediately, may wait awhile and
@@ -238,7 +244,7 @@ class LIBPROTOBUF_EXPORT RpcController {
// you need to return machine-readable information about failures, you
// should incorporate it into your response protocol buffer and should
// NOT call SetFailed().
- virtual void SetFailed(const string& reason) = 0;
+ virtual void SetFailed(const std::string& reason) = 0;
// If true, indicates that the client canceled the RPC, so the server may
// as well give up on replying to it. The server should still call the
@@ -266,7 +272,7 @@ class LIBPROTOBUF_EXPORT RpcController {
// RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234");
// MyService* service = new MyService::Stub(channel);
// service->MyMethod(request, &response, callback);
-class LIBPROTOBUF_EXPORT RpcChannel {
+class PROTOBUF_EXPORT RpcChannel {
public:
inline RpcChannel() {}
virtual ~RpcChannel();
@@ -287,6 +293,8 @@ class LIBPROTOBUF_EXPORT RpcChannel {
};
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_SERVICE_H__
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc
index 739172f8..a3dd41d4 100644
--- a/src/google/protobuf/source_context.pb.cc
+++ b/src/google/protobuf/source_context.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class SourceContextDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<SourceContext>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<SourceContext> _instance;
} _SourceContext_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
-static void InitDefaultsSourceContext() {
+static void InitDefaultsSourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,24 +35,26 @@ static void InitDefaultsSourceContext() {
::google::protobuf::SourceContext::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsSourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_SourceContext.base);
+void InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::SourceContext, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::SourceContext, file_name_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::SourceContext)},
};
@@ -65,52 +62,34 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_SourceContext_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/source_context.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fsource_5fcontext_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, "google/protobuf/source_context.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto,
+ "\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"
+ "rceContextProtoP\001ZAgoogle.golang.org/gen"
+ "proto/protobuf/source_context;source_con"
+ "text\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTy"
+ "pesb\006proto3"
+,
+ "google/protobuf/source_context.proto", &assign_descriptors_table_google_2fprotobuf_2fsource_5fcontext_2eproto, 251,
+};
-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"
- "rceContextProtoP\001ZAgoogle.golang.org/gen"
- "proto/protobuf/source_context;source_con"
- "text\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTy"
- "pesb\006proto3"
+void AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 251);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/source_context.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto = []() { AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -118,14 +97,16 @@ namespace protobuf {
void SourceContext::InitAsDefaultInstance() {
}
+class SourceContext::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SourceContext::kFileNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SourceContext::SourceContext()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
}
@@ -141,6 +122,8 @@ SourceContext::SourceContext(const SourceContext& from)
}
void SourceContext::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base);
file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -156,13 +139,8 @@ void SourceContext::SharedDtor() {
void SourceContext::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* SourceContext::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() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base);
return *internal_default_instance();
}
@@ -177,9 +155,62 @@ void SourceContext::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* SourceContext::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<SourceContext*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string file_name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.SourceContext.file_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_file_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool SourceContext::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.SourceContext)
for (;;) {
@@ -189,8 +220,7 @@ bool SourceContext::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string file_name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_file_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -222,6 +252,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SourceContext::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -239,9 +270,9 @@ void SourceContext::SerializeWithCachedSizes(
1, this->file_name(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.SourceContext)
}
@@ -264,9 +295,9 @@ void SourceContext::SerializeWithCachedSizes(
1, this->file_name(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.SourceContext)
return target;
@@ -276,11 +307,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// string file_name = 1;
if (this->file_name().size() > 0) {
total_size += 1 +
@@ -297,7 +332,7 @@ void SourceContext::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceContext)
GOOGLE_DCHECK_NE(&from, this);
const SourceContext* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const SourceContext>(
+ ::google::protobuf::DynamicCastToGenerated<SourceContext>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.SourceContext)
@@ -345,14 +380,14 @@ void SourceContext::Swap(SourceContext* other) {
}
void SourceContext::InternalSwap(SourceContext* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
file_name_.Swap(&other->file_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata SourceContext::GetMetadata() const {
- protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fsource_5fcontext_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto[kIndexInFileMessages];
}
@@ -361,10 +396,11 @@ void SourceContext::InternalSwap(SourceContext* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::SourceContext* Arena::CreateMaybeMessage< ::google::protobuf::SourceContext >(Arena* arena) {
return Arena::CreateInternal< ::google::protobuf::SourceContext >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index dcc856e2..b6fed22c 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,30 +32,28 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto();
namespace google {
namespace protobuf {
class SourceContext;
class SourceContextDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*);
+PROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::SourceContext* Arena::CreateMaybeMessage<::google::protobuf::SourceContext>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -62,7 +61,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ {
+class PROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ {
public:
SourceContext();
virtual ~SourceContext();
@@ -88,7 +87,9 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
return *this;
}
#endif
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const SourceContext& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -121,8 +122,13 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -165,11 +171,12 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
// @@protoc_insertion_point(class_scope:google.protobuf.SourceContext)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr file_name_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto;
};
// ===================================================================
@@ -246,4 +253,5 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto
diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc
index 8f2d4848..10e33ca2 100644
--- a/src/google/protobuf/struct.pb.cc
+++ b/src/google/protobuf/struct.pb.cc
@@ -6,38 +6,30 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
-namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue;
-} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto;
namespace google {
namespace protobuf {
class Struct_FieldsEntry_DoNotUseDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Struct_FieldsEntry_DoNotUse>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Struct_FieldsEntry_DoNotUse> _instance;
} _Struct_FieldsEntry_DoNotUse_default_instance_;
class StructDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Struct>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Struct> _instance;
} _Struct_default_instance_;
class ValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Value>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Value> _instance;
int null_value_;
double number_value_;
::google::protobuf::internal::ArenaStringPtr string_value_;
@@ -47,13 +39,11 @@ class ValueDefaultTypeInternal {
} _Value_default_instance_;
class ListValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<ListValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<ListValue> _instance;
} _ListValue_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fstruct_2eproto {
-static void InitDefaultsListValue() {
+static void InitDefaultsListValue_google_2fprotobuf_2fstruct_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -81,36 +71,37 @@ static void InitDefaultsListValue() {
::google::protobuf::ListValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsListValue_google_2fprotobuf_2fstruct_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_ListValue.base);
+void InitDefaults_google_2fprotobuf_2fstruct_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[4];
-const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fstruct_2eproto[4];
+const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto[1];
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto = nullptr;
-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_),
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, _has_bits_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Struct_FieldsEntry_DoNotUse, key_),
+ PROTOBUF_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_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Struct, fields_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _internal_metadata_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Value, _internal_metadata_),
~0u, // no _extensions_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Value, _oneof_case_[0]),
+ PROTOBUF_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_),
@@ -118,15 +109,15 @@ const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUT
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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Value, kind_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::ListValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::ListValue, values_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 7, sizeof(::google::protobuf::Struct_FieldsEntry_DoNotUse)},
{ 9, -1, sizeof(::google::protobuf::Struct)},
{ 15, -1, sizeof(::google::protobuf::Value)},
@@ -140,67 +131,49 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_ListValue_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/struct.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, file_level_enum_descriptors, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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);
-}
-
-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"
- "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo"
- "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull"
- "_value\030\001 \001(\0162\032.google.protobuf.NullValue"
- "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val"
- "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru"
- "ct_value\030\005 \001(\0132\027.google.protobuf.StructH"
- "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf."
- "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu"
- "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull"
- "Value\022\016\n\nNULL_VALUE\020\000B\201\001\n\023com.google.pro"
- "tobufB\013StructProtoP\001Z1github.com/golang/"
- "protobuf/ptypes/struct;structpb\370\001\001\242\002\003GPB"
- "\252\002\036Google.Protobuf.WellKnownTypesb\006proto"
- "3"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fstruct_2eproto, "google/protobuf/struct.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fstruct_2eproto, 4, file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto, file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fstruct_2eproto,
+ "\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"
+ "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo"
+ "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull"
+ "_value\030\001 \001(\0162\032.google.protobuf.NullValue"
+ "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val"
+ "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru"
+ "ct_value\030\005 \001(\0132\027.google.protobuf.StructH"
+ "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf."
+ "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu"
+ "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull"
+ "Value\022\016\n\nNULL_VALUE\020\000B\201\001\n\023com.google.pro"
+ "tobufB\013StructProtoP\001Z1github.com/golang/"
+ "protobuf/ptypes/struct;structpb\370\001\001\242\002\003GPB"
+ "\252\002\036Google.Protobuf.WellKnownTypesb\006proto"
+ "3"
+,
+ "google/protobuf/struct.proto", &assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto, 641,
+};
+
+void AddDescriptors_google_2fprotobuf_2fstruct_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 641);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/struct.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto = []() { AddDescriptors_google_2fprotobuf_2fstruct_2eproto(); return true; }();
namespace google {
namespace protobuf {
const ::google::protobuf::EnumDescriptor* NullValue_descriptor() {
- protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_enum_descriptors[0];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto[0];
}
bool NullValue_IsValid(int value) {
switch (value) {
@@ -215,32 +188,54 @@ bool NullValue_IsValid(int value) {
// ===================================================================
Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse() {}
-Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {}
+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];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fstruct_2eproto[0];
}
void Struct_FieldsEntry_DoNotUse::MergeFrom(
const ::google::protobuf::Message& other) {
::google::protobuf::Message::MergeFrom(other);
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+bool Struct_FieldsEntry_DoNotUse::_ParseMap(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) {
+ using MF = ::google::protobuf::internal::MapField<
+ Struct_FieldsEntry_DoNotUse, EntryKeyType, EntryValueType,
+ kEntryKeyFieldType, kEntryValueFieldType,
+ kEntryDefaultEnumValue>;
+ auto mf = static_cast<MF*>(object);
+ Parser<MF, ::google::protobuf::Map<EntryKeyType, EntryValueType>> parser(mf);
+#define DO_(x) if (!(x)) return false
+ DO_(parser.ParseMap(begin, end));
+ DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
+ parser.key().data(), static_cast<int>(parser.key().length()),
+ ::google::protobuf::internal::WireFormatLite::PARSE,
+ "google.protobuf.Struct.FieldsEntry.key"));
+#undef DO_
+ return true;
+}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
// ===================================================================
void Struct::InitAsDefaultInstance() {
}
+class Struct::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Struct::kFieldsFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Struct::Struct()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Struct)
}
@@ -248,7 +243,6 @@ Struct::Struct(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
fields_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Struct)
@@ -262,6 +256,8 @@ Struct::Struct(const Struct& from)
}
void Struct::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
}
Struct::~Struct() {
@@ -277,18 +273,13 @@ void Struct::ArenaDtor(void* object) {
Struct* _this = reinterpret_cast< Struct* >(object);
(void)_this;
}
-void Struct::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Struct::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Struct::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Struct::descriptor() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Struct& Struct::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
return *internal_default_instance();
}
@@ -303,9 +294,65 @@ void Struct::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Struct::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Struct*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // map<string, .google.protobuf.Value> fields = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::SlowMapEntryParser;
+ auto parse_map = ::google::protobuf::Struct_FieldsEntry_DoNotUse::_ParseMap;
+ ctx->extra_parse_data().payload.clear();
+ ctx->extra_parse_data().parse_map = parse_map;
+ object = &msg->fields_;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, object, ctx));
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Struct::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Struct)
for (;;) {
@@ -315,8 +362,7 @@ bool Struct::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .google.protobuf.Value> fields = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
Struct_FieldsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField<
Struct_FieldsEntry_DoNotUse,
::std::string, ::google::protobuf::Value,
@@ -355,6 +401,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Struct::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -391,35 +438,31 @@ void Struct::SerializeWithCachedSizes(
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
- entry.reset(fields_.NewEntryWrapper(
- items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
- ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, *entry, output);
+ entry.reset(fields_.NewEntryWrapper(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[static_cast<ptrdiff_t>(i)]);
+ Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)]));
}
} else {
::std::unique_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) {
- entry.reset(fields_.NewEntryWrapper(
- it->first, it->second));
- ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 1, *entry, output);
+ entry.reset(fields_.NewEntryWrapper(it->first, it->second));
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
- Utf8Check::Check(&*it);
+ Utf8Check::Check(&(*it));
}
}
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Struct)
}
@@ -460,39 +503,31 @@ void Struct::SerializeWithCachedSizes(
::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());
::std::unique_ptr<Struct_FieldsEntry_DoNotUse> entry;
for (size_type i = 0; i < n; i++) {
- entry.reset(fields_.NewEntryWrapper(
- items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
- target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, *entry, deterministic, target);
-;
+ entry.reset(fields_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second));
+ target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, *entry, deterministic, target);
if (entry->GetArena() != NULL) {
entry.release();
}
- Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]);
+ Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)]));
}
} else {
::std::unique_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) {
- entry.reset(fields_.NewEntryWrapper(
- it->first, it->second));
- target = ::google::protobuf::internal::WireFormatLite::
- InternalWriteMessageNoVirtualToArray(
- 1, *entry, deterministic, target);
-;
+ entry.reset(fields_.NewEntryWrapper(it->first, it->second));
+ target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(1, *entry, deterministic, target);
if (entry->GetArena() != NULL) {
entry.release();
}
- Utf8Check::Check(&*it);
+ Utf8Check::Check(&(*it));
}
}
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Struct)
return target;
@@ -502,11 +537,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// map<string, .google.protobuf.Value> fields = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->fields_size());
@@ -536,7 +575,7 @@ void Struct::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Struct)
GOOGLE_DCHECK_NE(&from, this);
const Struct* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Struct>(
+ ::google::protobuf::DynamicCastToGenerated<Struct>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Struct)
@@ -596,13 +635,13 @@ void Struct::UnsafeArenaSwap(Struct* other) {
}
void Struct::InternalSwap(Struct* other) {
using std::swap;
- fields_.Swap(&other->fields_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ fields_.Swap(&other->fields_);
}
::google::protobuf::Metadata Struct::GetMetadata() const {
- protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fstruct_2eproto[kIndexInFileMessages];
}
@@ -619,6 +658,20 @@ void Value::InitAsDefaultInstance() {
::google::protobuf::_Value_default_instance_.list_value_ = const_cast< ::google::protobuf::ListValue*>(
::google::protobuf::ListValue::internal_default_instance());
}
+class Value::HasBitSetters {
+ public:
+ static const ::google::protobuf::Struct& struct_value(const Value* msg);
+ static const ::google::protobuf::ListValue& list_value(const Value* msg);
+};
+
+const ::google::protobuf::Struct&
+Value::HasBitSetters::struct_value(const Value* msg) {
+ return *msg->kind_.struct_value_;
+}
+const ::google::protobuf::ListValue&
+Value::HasBitSetters::list_value(const Value* msg) {
+ return *msg->kind_.list_value_;
+}
void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
clear_kind();
@@ -660,15 +713,12 @@ const int Value::kListValueFieldNumber;
Value::Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Value)
}
Value::Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Value)
@@ -711,6 +761,8 @@ Value::Value(const Value& from)
}
void Value::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
clear_has_kind();
}
@@ -730,18 +782,13 @@ void Value::ArenaDtor(void* object) {
Value* _this = reinterpret_cast< Value* >(object);
(void)_this;
}
-void Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Value::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Value::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Value::descriptor() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Value& Value::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
return *internal_default_instance();
}
@@ -796,9 +843,121 @@ void Value::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Value::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Value*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // .google.protobuf.NullValue null_value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::NullValue value = static_cast<::google::protobuf::NullValue>(val);
+ msg->set_null_value(value);
+ break;
+ }
+ // double number_value = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 17) goto handle_unusual;
+ double val;
+ ::std::memcpy(&val, ptr, 8);
+ ptr += 8;
+ msg->set_number_value(val);
+ break;
+ }
+ // string string_value = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Value.string_value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_string_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // bool bool_value = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_bool_value(value);
+ break;
+ }
+ // .google.protobuf.Struct struct_value = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Struct::_InternalParse;
+ object = msg->mutable_struct_value();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // .google.protobuf.ListValue list_value = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::ListValue::_InternalParse;
+ object = msg->mutable_list_value();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Value::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Value)
for (;;) {
@@ -808,9 +967,8 @@ bool Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.protobuf.NullValue null_value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -823,8 +981,7 @@ bool Value::MergePartialFromCodedStream(
// double number_value = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (17 & 0xFF)) {
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -838,8 +995,7 @@ bool Value::MergePartialFromCodedStream(
// string string_value = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_string_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -854,8 +1010,7 @@ bool Value::MergePartialFromCodedStream(
// bool bool_value = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -869,8 +1024,7 @@ bool Value::MergePartialFromCodedStream(
// .google.protobuf.Struct struct_value = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_struct_value()));
} else {
@@ -881,8 +1035,7 @@ bool Value::MergePartialFromCodedStream(
// .google.protobuf.ListValue list_value = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_list_value()));
} else {
@@ -910,6 +1063,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -946,18 +1100,18 @@ void Value::SerializeWithCachedSizes(
// .google.protobuf.Struct struct_value = 5;
if (has_struct_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->_internal_struct_value(), output);
+ 5, HasBitSetters::struct_value(this), output);
}
// .google.protobuf.ListValue list_value = 6;
if (has_list_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 6, this->_internal_list_value(), output);
+ 6, HasBitSetters::list_value(this), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Value)
}
@@ -1000,19 +1154,19 @@ void Value::SerializeWithCachedSizes(
if (has_struct_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, this->_internal_struct_value(), deterministic, target);
+ 5, HasBitSetters::struct_value(this), deterministic, target);
}
// .google.protobuf.ListValue list_value = 6;
if (has_list_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 6, this->_internal_list_value(), deterministic, target);
+ 6, HasBitSetters::list_value(this), deterministic, target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Value)
return target;
@@ -1022,11 +1176,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
switch (kind_case()) {
// .google.protobuf.NullValue null_value = 1;
case kNullValue: {
@@ -1078,7 +1236,7 @@ void Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Value)
GOOGLE_DCHECK_NE(&from, this);
const Value* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Value>(
+ ::google::protobuf::DynamicCastToGenerated<Value>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Value)
@@ -1166,14 +1324,14 @@ void Value::UnsafeArenaSwap(Value* other) {
}
void Value::InternalSwap(Value* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
swap(kind_, other->kind_);
swap(_oneof_case_[0], other->_oneof_case_[0]);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Value::GetMetadata() const {
- protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fstruct_2eproto[kIndexInFileMessages];
}
@@ -1181,14 +1339,16 @@ void Value::InternalSwap(Value* other) {
void ListValue::InitAsDefaultInstance() {
}
+class ListValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int ListValue::kValuesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
ListValue::ListValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ListValue)
}
@@ -1196,7 +1356,6 @@ ListValue::ListValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
values_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue)
@@ -1210,6 +1369,8 @@ ListValue::ListValue(const ListValue& from)
}
void ListValue::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
}
ListValue::~ListValue() {
@@ -1225,18 +1386,13 @@ void ListValue::ArenaDtor(void* object) {
ListValue* _this = reinterpret_cast< ListValue* >(object);
(void)_this;
}
-void ListValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void ListValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void ListValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* ListValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const ListValue& ListValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fstruct_2eproto::scc_info_ListValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_ListValue_google_2fprotobuf_2fstruct_2eproto.base);
return *internal_default_instance();
}
@@ -1251,9 +1407,64 @@ void ListValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* ListValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<ListValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // repeated .google.protobuf.Value values = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Value::_InternalParse;
+ object = msg->add_values();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool ListValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.ListValue)
for (;;) {
@@ -1263,8 +1474,7 @@ bool ListValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.Value values = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_values()));
} else {
@@ -1292,6 +1502,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void ListValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1308,9 +1519,9 @@ void ListValue::SerializeWithCachedSizes(
output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.ListValue)
}
@@ -1330,9 +1541,9 @@ void ListValue::SerializeWithCachedSizes(
1, this->values(static_cast<int>(i)), deterministic, target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.ListValue)
return target;
@@ -1342,11 +1553,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Value values = 1;
{
unsigned int count = static_cast<unsigned int>(this->values_size());
@@ -1367,7 +1582,7 @@ void ListValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ListValue)
GOOGLE_DCHECK_NE(&from, this);
const ListValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const ListValue>(
+ ::google::protobuf::DynamicCastToGenerated<ListValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.ListValue)
@@ -1427,13 +1642,13 @@ void ListValue::UnsafeArenaSwap(ListValue* other) {
}
void ListValue::InternalSwap(ListValue* other) {
using std::swap;
- CastToBase(&values_)->InternalSwap(CastToBase(&other->values_));
_internal_metadata_.Swap(&other->_internal_metadata_);
+ CastToBase(&values_)->InternalSwap(CastToBase(&other->values_));
}
::google::protobuf::Metadata ListValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fstruct_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fstruct_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fstruct_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fstruct_2eproto[kIndexInFileMessages];
}
@@ -1442,19 +1657,20 @@ void ListValue::InternalSwap(ListValue* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Struct_FieldsEntry_DoNotUse >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Struct* Arena::CreateMaybeMessage< ::google::protobuf::Struct >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Struct* Arena::CreateMaybeMessage< ::google::protobuf::Struct >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Struct >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Value* Arena::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Value* Arena::CreateMaybeMessage< ::google::protobuf::Value >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Value >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::ListValue* Arena::CreateMaybeMessage< ::google::protobuf::ListValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::ListValue >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index 1cf75d9b..224fe81a 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -35,42 +36,40 @@
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fstruct_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fstruct_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[4]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fstruct_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fstruct_2eproto();
namespace google {
namespace protobuf {
class ListValue;
class ListValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instance_;
+PROTOBUF_EXPORT extern ListValueDefaultTypeInternal _ListValue_default_instance_;
class Struct;
class StructDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern StructDefaultTypeInternal _Struct_default_instance_;
+PROTOBUF_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_;
+PROTOBUF_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 {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*);
+PROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::ListValue* Arena::CreateMaybeMessage<::google::protobuf::ListValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Struct* Arena::CreateMaybeMessage<::google::protobuf::Struct>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::google::protobuf::Struct_FieldsEntry_DoNotUse>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Value* Arena::CreateMaybeMessage<::google::protobuf::Value>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -78,15 +77,15 @@ namespace protobuf {
enum NullValue {
NULL_VALUE = 0,
- NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
- NullValue_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
+ NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::min(),
+ NullValue_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::max()
};
-LIBPROTOBUF_EXPORT bool NullValue_IsValid(int value);
+PROTOBUF_EXPORT bool NullValue_IsValid(int value);
const NullValue NullValue_MIN = NULL_VALUE;
const NullValue NullValue_MAX = NULL_VALUE;
const int NullValue_ARRAYSIZE = NullValue_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* NullValue_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* NullValue_descriptor();
inline const ::std::string& NullValue_Name(NullValue value) {
return ::google::protobuf::internal::NameOfEnum(
NullValue_descriptor(), value);
@@ -104,6 +103,9 @@ class Struct_FieldsEntry_DoNotUse : public ::google::protobuf::internal::MapEntr
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > {
public:
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+static bool _ParseMap(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
typedef ::google::protobuf::internal::MapEntry<Struct_FieldsEntry_DoNotUse,
::std::string, ::google::protobuf::Value,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
@@ -119,7 +121,7 @@ public:
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ {
+class PROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Struct) */ {
public:
Struct();
virtual ~Struct();
@@ -151,7 +153,9 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Struct& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -185,8 +189,13 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -230,6 +239,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
// @@protoc_insertion_point(class_scope:google.protobuf.Struct)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -242,11 +252,11 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > fields_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ {
+class PROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ {
public:
Value();
virtual ~Value();
@@ -278,7 +288,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Value& default_instance();
enum KindCase {
@@ -322,8 +334,13 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -389,11 +406,11 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -412,9 +429,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
bool has_struct_value() const;
void clear_struct_value();
static const int kStructValueFieldNumber = 5;
- private:
- const ::google::protobuf::Struct& _internal_struct_value() const;
- public:
const ::google::protobuf::Struct& struct_value() const;
::google::protobuf::Struct* release_struct_value();
::google::protobuf::Struct* mutable_struct_value();
@@ -427,9 +441,6 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
bool has_list_value() const;
void clear_list_value();
static const int kListValueFieldNumber = 6;
- private:
- const ::google::protobuf::ListValue& _internal_list_value() const;
- public:
const ::google::protobuf::ListValue& list_value() const;
::google::protobuf::ListValue* release_list_value();
::google::protobuf::ListValue* mutable_list_value();
@@ -442,6 +453,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
KindCase kind_case() const;
// @@protoc_insertion_point(class_scope:google.protobuf.Value)
private:
+ class HasBitSetters;
void set_has_null_value();
void set_has_number_value();
void set_has_string_value();
@@ -468,11 +480,11 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
- friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ {
+class PROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ {
public:
ListValue();
virtual ~ListValue();
@@ -504,7 +516,9 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const ListValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -538,8 +552,13 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -585,6 +604,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
// @@protoc_insertion_point(class_scope:google.protobuf.ListValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -592,7 +612,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fstruct_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto;
};
// ===================================================================
@@ -776,14 +796,12 @@ inline ::std::string* Value::release_string_value() {
}
}
inline void Value::set_allocated_string_value(::std::string* string_value) {
- if (!has_string_value()) {
- kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ if (has_kind()) {
+ clear_kind();
}
- clear_kind();
if (string_value != NULL) {
set_has_string_value();
- kind_.string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
- GetArenaNoVirtual());
+ kind_.string_value_.UnsafeSetDefault(string_value);
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
}
@@ -855,9 +873,6 @@ inline void Value::clear_struct_value() {
clear_has_kind();
}
}
-inline const ::google::protobuf::Struct& Value::_internal_struct_value() const {
- 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()) {
@@ -923,9 +938,6 @@ inline void Value::clear_list_value() {
clear_has_kind();
}
}
-inline const ::google::protobuf::ListValue& Value::_internal_list_value() const {
- 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()) {
@@ -1048,4 +1060,5 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::NullValue>()
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto
diff --git a/src/google/protobuf/stubs/bytestream.cc b/src/google/protobuf/stubs/bytestream.cc
index f4af6a50..8df2566a 100644
--- a/src/google/protobuf/stubs/bytestream.cc
+++ b/src/google/protobuf/stubs/bytestream.cc
@@ -113,7 +113,7 @@ char* GrowingArrayByteSink::GetBuffer(size_t* nbytes) {
ShrinkToFit();
char* b = buf_;
*nbytes = size_;
- buf_ = NULL;
+ buf_ = nullptr;
size_ = capacity_ = 0;
return b;
}
diff --git a/src/google/protobuf/stubs/bytestream.h b/src/google/protobuf/stubs/bytestream.h
index 86510d14..29a9fbe7 100644
--- a/src/google/protobuf/stubs/bytestream.h
+++ b/src/google/protobuf/stubs/bytestream.h
@@ -56,8 +56,9 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
class CordByteSink;
-class MemBlock;
namespace google {
namespace protobuf {
@@ -74,7 +75,7 @@ namespace strings {
// sink->Append(my_data.data(), my_data.size());
// sink->Flush();
//
-class LIBPROTOBUF_EXPORT ByteSink {
+class PROTOBUF_EXPORT ByteSink {
public:
ByteSink() {}
virtual ~ByteSink() {}
@@ -103,7 +104,7 @@ class LIBPROTOBUF_EXPORT ByteSink {
// source->Skip(data.length());
// }
//
-class LIBPROTOBUF_EXPORT ByteSource {
+class PROTOBUF_EXPORT ByteSource {
public:
ByteSource() {}
virtual ~ByteSource() {}
@@ -159,10 +160,10 @@ class LIBPROTOBUF_EXPORT ByteSource {
// sink.Append("hi", 2); // OK
// sink.Append(data, 100); // WOOPS! Overflows buf[10].
//
-class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
+class PROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
public:
explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {}
- virtual void Append(const char* data, size_t n);
+ virtual void Append(const char* data, size_t n) override;
// Returns the current output pointer so that a caller can see how many bytes
// were produced.
@@ -187,10 +188,10 @@ class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
// sink.Append("hi", 2); // OK
// sink.Append(data, 100); // Will only write 8 more bytes
//
-class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink {
+class PROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink {
public:
CheckedArrayByteSink(char* outbuf, size_t capacity);
- virtual void Append(const char* bytes, size_t n);
+ virtual void Append(const char* bytes, size_t n) override;
// Returns the number of bytes actually written to the sink.
size_t NumberOfBytesWritten() const { return size_; }
@@ -223,11 +224,11 @@ class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink {
// const char* buf = sink.GetBuffer(); // Ownership transferred
// delete[] buf;
//
-class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
+class PROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
public:
explicit GrowingArrayByteSink(size_t estimated_size);
virtual ~GrowingArrayByteSink();
- virtual void Append(const char* bytes, size_t n);
+ virtual void Append(const char* bytes, size_t n) override;
// Returns the allocated buffer, and sets nbytes to its size. The caller takes
// ownership of the buffer and must delete it with delete[].
@@ -253,10 +254,10 @@ class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
// sink.Append("World", 5);
// assert(dest == "Hello World");
//
-class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink {
+class PROTOBUF_EXPORT StringByteSink : public ByteSink {
public:
explicit StringByteSink(string* dest) : dest_(dest) {}
- virtual void Append(const char* data, size_t n);
+ virtual void Append(const char* data, size_t n) override;
private:
string* dest_;
@@ -270,10 +271,10 @@ class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink {
// NullByteSink sink;
// sink.Append(data, data.size()); // All data ignored.
//
-class LIBPROTOBUF_EXPORT NullByteSink : public ByteSink {
+class PROTOBUF_EXPORT NullByteSink : public ByteSink {
public:
NullByteSink() {}
- virtual void Append(const char *data, size_t n) {}
+ virtual void Append(const char *data, size_t n) override {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink);
@@ -292,13 +293,13 @@ class LIBPROTOBUF_EXPORT NullByteSink : public ByteSink {
// assert(source.Available() == 5);
// assert(source.Peek() == "Hello");
//
-class LIBPROTOBUF_EXPORT ArrayByteSource : public ByteSource {
+class PROTOBUF_EXPORT ArrayByteSource : public ByteSource {
public:
explicit ArrayByteSource(StringPiece s) : input_(s) {}
- virtual size_t Available() const;
- virtual StringPiece Peek();
- virtual void Skip(size_t n);
+ virtual size_t Available() const override;
+ virtual StringPiece Peek() override;
+ virtual void Skip(size_t n) override;
private:
StringPiece input_;
@@ -323,18 +324,18 @@ class LIBPROTOBUF_EXPORT ArrayByteSource : public ByteSource {
// assert(limit.Available() == 5);
// assert(limit.Peek() == "Hello");
//
-class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource {
+class PROTOBUF_EXPORT LimitByteSource : public ByteSource {
public:
// Returns at most "limit" bytes from "source".
LimitByteSource(ByteSource* source, size_t limit);
- virtual size_t Available() const;
- virtual StringPiece Peek();
- virtual void Skip(size_t n);
+ virtual size_t Available() const override;
+ virtual StringPiece Peek() override;
+ virtual void Skip(size_t n) override;
// We override CopyTo so that we can forward to the underlying source, in
// case it has an efficient implementation of CopyTo.
- virtual void CopyTo(ByteSink* sink, size_t n);
+ virtual void CopyTo(ByteSink* sink, size_t n) override;
private:
ByteSource* source_;
@@ -345,4 +346,6 @@ class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource {
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h
index 6888f136..7cce4426 100644
--- a/src/google/protobuf/stubs/callback.h
+++ b/src/google/protobuf/stubs/callback.h
@@ -5,6 +5,8 @@
#include <google/protobuf/stubs/macros.h>
+#include <google/protobuf/port_def.inc>
+
// ===================================================================
// emulates google3/base/callback.h
@@ -68,7 +70,7 @@ namespace protobuf {
// string my_str;
// NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes.
// However, correctly-typed pointers will work just fine.
-class LIBPROTOBUF_EXPORT Closure {
+class PROTOBUF_EXPORT Closure {
public:
Closure() {}
virtual ~Closure();
@@ -91,8 +93,8 @@ class ResultCallback {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback);
};
-template<typename R, typename A1>
-class LIBPROTOBUF_EXPORT ResultCallback1 {
+template <typename R, typename A1>
+class PROTOBUF_EXPORT ResultCallback1 {
public:
ResultCallback1() {}
virtual ~ResultCallback1() {}
@@ -103,8 +105,8 @@ class LIBPROTOBUF_EXPORT ResultCallback1 {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback1);
};
-template<typename R, typename A1, typename A2>
-class LIBPROTOBUF_EXPORT ResultCallback2 {
+template <typename R, typename A1, typename A2>
+class PROTOBUF_EXPORT ResultCallback2 {
public:
ResultCallback2() {}
virtual ~ResultCallback2() {}
@@ -117,7 +119,7 @@ class LIBPROTOBUF_EXPORT ResultCallback2 {
namespace internal {
-class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure {
+class PROTOBUF_EXPORT FunctionClosure0 : public Closure {
public:
typedef void (*FunctionType)();
@@ -125,7 +127,7 @@ class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure {
: function_(function), self_deleting_(self_deleting) {}
~FunctionClosure0();
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_();
if (needs_delete) delete this;
@@ -145,7 +147,7 @@ class MethodClosure0 : public Closure {
: object_(object), method_(method), self_deleting_(self_deleting) {}
~MethodClosure0() {}
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)();
if (needs_delete) delete this;
@@ -168,7 +170,7 @@ class FunctionClosure1 : public Closure {
arg1_(arg1) {}
~FunctionClosure1() {}
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_(arg1_);
if (needs_delete) delete this;
@@ -191,7 +193,7 @@ class MethodClosure1 : public Closure {
arg1_(arg1) {}
~MethodClosure1() {}
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)(arg1_);
if (needs_delete) delete this;
@@ -215,7 +217,7 @@ class FunctionClosure2 : public Closure {
arg1_(arg1), arg2_(arg2) {}
~FunctionClosure2() {}
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_(arg1_, arg2_);
if (needs_delete) delete this;
@@ -239,7 +241,7 @@ class MethodClosure2 : public Closure {
arg1_(arg1), arg2_(arg2) {}
~MethodClosure2() {}
- void Run() {
+ void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)(arg1_, arg2_);
if (needs_delete) delete this;
@@ -262,7 +264,7 @@ class FunctionResultCallback_0_0 : public ResultCallback<R> {
: function_(function), self_deleting_(self_deleting) {}
~FunctionResultCallback_0_0() {}
- R Run() {
+ R Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_();
if (needs_delete) delete this;
@@ -284,7 +286,7 @@ class FunctionResultCallback_1_0 : public ResultCallback<R> {
: function_(function), self_deleting_(self_deleting), p1_(p1) {}
~FunctionResultCallback_1_0() {}
- R Run() {
+ R Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(p1_);
if (needs_delete) delete this;
@@ -306,7 +308,7 @@ class FunctionResultCallback_0_1 : public ResultCallback1<R, Arg1> {
: function_(function), self_deleting_(self_deleting) {}
~FunctionResultCallback_0_1() {}
- R Run(Arg1 a1) {
+ R Run(Arg1 a1) override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(a1);
if (needs_delete) delete this;
@@ -328,7 +330,7 @@ class FunctionResultCallback_1_1 : public ResultCallback1<R, A1> {
: function_(function), self_deleting_(self_deleting), p1_(p1) {}
~FunctionResultCallback_1_1() {}
- R Run(A1 a1) {
+ R Run(A1 a1) override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(p1_, a1);
if (needs_delete) delete this;
@@ -387,7 +389,7 @@ class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> {
p5_(p5) {}
~MethodResultCallback_5_2() {}
- R Run(A1 a1, A2 a2) {
+ R Run(A1 a1, A2 a2) override {
bool needs_delete = self_deleting_;
R result = (object_->*method_)(p1_, p2_, p3_, p4_, p5_, a1, a2);
if (needs_delete) delete this;
@@ -568,10 +570,11 @@ inline ResultCallback2<R, A1, A2>* NewPermanentCallback(
// A function which does nothing. Useful for creating no-op callbacks, e.g.:
// Closure* nothing = NewCallback(&DoNothing);
-void LIBPROTOBUF_EXPORT DoNothing();
-
+void PROTOBUF_EXPORT DoNothing();
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
diff --git a/src/google/protobuf/stubs/casts.h b/src/google/protobuf/stubs/casts.h
index 35e2dba0..b509f68c 100644
--- a/src/google/protobuf/stubs/casts.h
+++ b/src/google/protobuf/stubs/casts.h
@@ -89,7 +89,7 @@ inline To down_cast(From* f) { // so we only accept pointers
}
#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
- assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only!
+ assert(f == nullptr || dynamic_cast<To>(f) != nullptr); // RTTI: debug mode only!
#endif
return static_cast<To>(f);
}
@@ -107,7 +107,7 @@ inline To down_cast(From& f) {
#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
// RTTI: debug mode only!
- assert(dynamic_cast<ToAsPointer>(&f) != NULL);
+ assert(dynamic_cast<ToAsPointer>(&f) != nullptr);
#endif
return *static_cast<ToAsPointer>(&f);
}
diff --git a/src/google/protobuf/stubs/common.cc b/src/google/protobuf/stubs/common.cc
index 6544c6ed..38153321 100755..100644
--- a/src/google/protobuf/stubs/common.cc
+++ b/src/google/protobuf/stubs/common.cc
@@ -30,7 +30,6 @@
// 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>
@@ -55,6 +54,8 @@
#include <android/log.h>
#endif
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -176,12 +177,12 @@ void NullLogHandler(LogLevel /* level */, const char* /* filename */,
static LogHandler* log_handler_ = &DefaultLogHandler;
static int log_silencer_count_ = 0;
-static Mutex* log_silencer_count_mutex_ = NULL;
+static Mutex* log_silencer_count_mutex_ = nullptr;
GOOGLE_PROTOBUF_DECLARE_ONCE(log_silencer_count_init_);
void DeleteLogSilencerCount() {
delete log_silencer_count_mutex_;
- log_silencer_count_mutex_ = NULL;
+ log_silencer_count_mutex_ = nullptr;
}
void InitLogSilencerCount() {
log_silencer_count_mutex_ = new Mutex;
@@ -243,8 +244,8 @@ DECLARE_STREAM_OPERATOR(long , "%ld")
DECLARE_STREAM_OPERATOR(unsigned long, "%lu")
DECLARE_STREAM_OPERATOR(double , "%g" )
DECLARE_STREAM_OPERATOR(void* , "%p" )
-DECLARE_STREAM_OPERATOR(long long , "%" GOOGLE_LL_FORMAT "d")
-DECLARE_STREAM_OPERATOR(unsigned long long, "%" GOOGLE_LL_FORMAT "u")
+DECLARE_STREAM_OPERATOR(long long , "%" PROTOBUF_LL_FORMAT "d")
+DECLARE_STREAM_OPERATOR(unsigned long long, "%" PROTOBUF_LL_FORMAT "u")
#undef DECLARE_STREAM_OPERATOR
LogMessage::LogMessage(LogLevel level, const char* filename, int line)
@@ -282,9 +283,9 @@ void LogFinisher::operator=(LogMessage& other) {
LogHandler* SetLogHandler(LogHandler* new_func) {
LogHandler* old = internal::log_handler_;
if (old == &internal::NullLogHandler) {
- old = NULL;
+ old = nullptr;
}
- if (new_func == NULL) {
+ if (new_func == nullptr) {
internal::log_handler_ = &internal::NullLogHandler;
} else {
internal::log_handler_ = new_func;
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index d35377ae..b3cb882d 100644
--- a/src/google/protobuf/stubs/common.h
+++ b/src/google/protobuf/stubs/common.h
@@ -73,22 +73,7 @@
#include <pthread.h>
#endif
-#if defined(_WIN32) && defined(GetMessage)
-// Allow GetMessage to be used as a valid method name in protobuf classes.
-// windows.h defines GetMessage() as a macro. Let's re-define it as an inline
-// function. The inline function should be equivalent for C++ users.
-inline BOOL GetMessage_Win32(
- LPMSG lpMsg, HWND hWnd,
- UINT wMsgFilterMin, UINT wMsgFilterMax) {
- return GetMessage(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
-}
-#undef GetMessage
-inline BOOL GetMessage(
- LPMSG lpMsg, HWND hWnd,
- UINT wMsgFilterMin, UINT wMsgFilterMax) {
- return GetMessage_Win32(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax);
-}
-#endif
+#include <google/protobuf/port_def.inc>
namespace std {}
@@ -125,11 +110,11 @@ static const int kMinHeaderVersionForProtoc = 3006001;
// Verifies that the headers and libraries are compatible. Use the macro
// below to call this.
-void LIBPROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion,
- const char* filename);
+void PROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion,
+ const char* filename);
// Converts a numeric version number to a string.
-std::string LIBPROTOBUF_EXPORT VersionString(int version);
+std::string PROTOBUF_EXPORT VersionString(int version);
} // namespace internal
@@ -151,14 +136,14 @@ namespace internal {
// Checks if the buffer contains structurally-valid UTF-8. Implemented in
// structurally_valid.cc.
-LIBPROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len);
+PROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len);
inline bool IsStructurallyValidUTF8(const std::string& str) {
return IsStructurallyValidUTF8(str.data(), static_cast<int>(str.length()));
}
// Returns initial number of bytes of structually valid UTF-8.
-LIBPROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str);
+PROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str);
// Coerce UTF-8 byte string in src_str to be
// a structurally-valid equal-length string by selectively
@@ -172,8 +157,9 @@ LIBPROTOBUF_EXPORT int UTF8SpnStructurallyValid(const StringPiece& str);
//
// Optimized for: all structurally valid and no byte copying is done.
//
-LIBPROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid(
- const StringPiece& str, char* dst, char replace_char);
+PROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid(const StringPiece& str,
+ char* dst,
+ char replace_char);
} // namespace internal
@@ -195,18 +181,18 @@ LIBPROTOBUF_EXPORT char* UTF8CoerceToStructurallyValid(
// any other part of the protocol buffers library after
// ShutdownProtobufLibrary() has been called. Furthermore this call is not
// thread safe, user needs to synchronize multiple calls.
-LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary();
+PROTOBUF_EXPORT void ShutdownProtobufLibrary();
namespace internal {
// Register a function to be called when ShutdownProtocolBuffers() is called.
-LIBPROTOBUF_EXPORT void OnShutdown(void (*func)());
+PROTOBUF_EXPORT void OnShutdown(void (*func)());
// Run an arbitrary function on an arg
-LIBPROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
+PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
template <typename T>
T* OnShutdownDelete(T* p) {
- OnShutdownRun([](const void* p) { delete static_cast<const T*>(p); }, p);
+ OnShutdownRun([](const void* pp) { delete static_cast<const T*>(pp); }, p);
return p;
}
@@ -239,4 +225,6 @@ using std::string;
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_COMMON_H__
diff --git a/src/google/protobuf/stubs/common_unittest.cc b/src/google/protobuf/stubs/common_unittest.cc
index 798a2a27..3ce1c49a 100644
--- a/src/google/protobuf/stubs/common_unittest.cc
+++ b/src/google/protobuf/stubs/common_unittest.cc
@@ -100,14 +100,14 @@ TEST(LoggingTest, DefaultLogging) {
}
TEST(LoggingTest, NullLogging) {
- LogHandler* old_handler = SetLogHandler(NULL);
+ LogHandler* old_handler = SetLogHandler(nullptr);
CaptureTestStderr();
GOOGLE_LOG(INFO ) << "A message.";
GOOGLE_LOG(WARNING) << "A warning.";
GOOGLE_LOG(ERROR ) << "An error.";
- EXPECT_TRUE(SetLogHandler(old_handler) == NULL);
+ EXPECT_TRUE(SetLogHandler(old_handler) == nullptr);
string text = GetCapturedTestStderr();
EXPECT_EQ("", text);
@@ -179,9 +179,9 @@ class ClosureTest : public testing::Test {
virtual void SetUp() {
current_instance_ = this;
a_ = 0;
- b_ = NULL;
+ b_ = nullptr;
c_.clear();
- permanent_closure_ = NULL;
+ permanent_closure_ = nullptr;
}
void DeleteClosureInCallback() {
@@ -196,7 +196,7 @@ class ClosureTest : public testing::Test {
static ClosureTest* current_instance_;
};
-ClosureTest* ClosureTest::current_instance_ = NULL;
+ClosureTest* ClosureTest::current_instance_ = nullptr;
TEST_F(ClosureTest, TestClosureFunction0) {
Closure* closure = NewCallback(&SetA123Function);
@@ -321,7 +321,7 @@ TEST_F(ClosureTest, TestPermanentClosureFunction2) {
EXPECT_EQ(789, a_);
EXPECT_EQ(cstr, b_);
a_ = 0;
- b_ = NULL;
+ b_ = nullptr;
closure->Run();
EXPECT_EQ(789, a_);
EXPECT_EQ(cstr, b_);
@@ -338,7 +338,7 @@ TEST_F(ClosureTest, TestPermanentClosureMethod2) {
EXPECT_EQ(789, a_);
EXPECT_EQ(cstr, b_);
a_ = 0;
- b_ = NULL;
+ b_ = nullptr;
closure->Run();
EXPECT_EQ(789, a_);
EXPECT_EQ(cstr, b_);
diff --git a/src/google/protobuf/stubs/fastmem.h b/src/google/protobuf/stubs/fastmem.h
index 1f1f6ed3..76c8a3ae 100644
--- a/src/google/protobuf/stubs/fastmem.h
+++ b/src/google/protobuf/stubs/fastmem.h
@@ -51,6 +51,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -64,7 +66,7 @@ namespace internal {
// if it makes sense to do so.:w
inline bool memeq(const char* a, const char* b, size_t n) {
size_t n_rounded_down = n & ~static_cast<size_t>(7);
- if (GOOGLE_PREDICT_FALSE(n_rounded_down == 0)) { // n <= 7
+ if (PROTOBUF_PREDICT_FALSE(n_rounded_down == 0)) { // n <= 7
return memcmp(a, b, n) == 0;
}
// n >= 8
@@ -150,4 +152,6 @@ inline void memcpy_inlined(char *dst, const char *src, size_t size) {
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_FASTMEM_H_
diff --git a/src/google/protobuf/stubs/hash.h b/src/google/protobuf/stubs/hash.h
index fd8ba156..a093b406 100644
--- a/src/google/protobuf/stubs/hash.h
+++ b/src/google/protobuf/stubs/hash.h
@@ -29,8 +29,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
-//
-// Deals with the fact that hash_map is not defined everywhere.
#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__
#define GOOGLE_PROTOBUF_STUBS_HASH_H__
@@ -38,304 +36,19 @@
#include <string.h>
#include <google/protobuf/stubs/common.h>
-#define GOOGLE_PROTOBUF_HAVE_HASH_MAP 1
-#define GOOGLE_PROTOBUF_HAVE_HASH_SET 1
-
-// Use C++11 unordered_{map|set} if available.
-#if ((defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11) || \
- (((__cplusplus >= 201103L) || defined(__GXX_EXPERIMENTAL_CXX0X)) && \
- (__GLIBCXX__ > 20090421)))
-# define GOOGLE_PROTOBUF_HAS_CXX11_HASH
-
-// For XCode >= 4.6: the compiler is clang with libc++.
-// For earlier XCode version: the compiler is gcc-4.2.1 with libstdc++.
-// libc++ provides <unordered_map> and friends even in non C++11 mode,
-// and it does not provide the tr1 library. Therefore the following macro
-// checks against this special case.
-// Note that we should not test the __APPLE_CC__ version number or the
-// __clang__ macro, since the new compiler can still use -stdlib=libstdc++, in
-// which case <unordered_map> is not compilable without -std=c++11
-#elif defined(__APPLE_CC__)
-# if __GNUC__ >= 4
-# define GOOGLE_PROTOBUF_HAS_TR1
-# else
-// Not tested for gcc < 4... These setting can compile under 4.2.1 though.
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx
-# include <ext/hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <ext/hash_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
-# endif
-
-// Version checks for gcc.
-#elif defined(__GNUC__)
-// For GCC 4.x+, use tr1::unordered_map/set; otherwise, follow the
-// instructions from:
-// https://gcc.gnu.org/onlinedocs/libstdc++/manual/backwards.html
-# if __GNUC__ >= 4
-# define GOOGLE_PROTOBUF_HAS_TR1
-# elif __GNUC__ >= 3
-# include <backward/hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <backward/hash_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
-# if __GNUC__ == 3 && __GNUC_MINOR__ == 0
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE std // GCC 3.0
-# else
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE __gnu_cxx // GCC 3.1 and later
-# endif
-# else
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE
-# include <hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <hash_set>
-# 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:
-// http://blogs.msdn.com/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx
-// And.. they are moved back to stdext in MSVC 2013 (haven't checked 2012). That
-// said, use unordered_map for MSVC 2010 and beyond is our safest bet.
-#elif defined(_MSC_VER)
-# if _MSC_VER >= 1600 // Since Visual Studio 2010
-# define GOOGLE_PROTOBUF_HAS_CXX11_HASH
-# define GOOGLE_PROTOBUF_HASH_COMPARE std::hash_compare
-# elif _MSC_VER >= 1500 // Since Visual Studio 2008
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext
-# include <hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <hash_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
-# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
-# define GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
-# elif _MSC_VER >= 1310
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE stdext
-# include <hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <hash_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
-# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
-# else
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE std
-# include <hash_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS hash_map
-# include <hash_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS hash_set
-# define GOOGLE_PROTOBUF_HASH_COMPARE stdext::hash_compare
-# endif
-
-// **ADD NEW COMPILERS SUPPORT HERE.**
-// For other compilers, undefine the macro and fallback to use std::map, in
-// google/protobuf/stubs/hash.h
-#else
-# undef GOOGLE_PROTOBUF_HAVE_HASH_MAP
-# undef GOOGLE_PROTOBUF_HAVE_HASH_SET
-#endif
-
-#if defined(GOOGLE_PROTOBUF_HAS_CXX11_HASH)
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE std
-# include <unordered_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map
-# include <unordered_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set
-#elif defined(GOOGLE_PROTOBUF_HAS_TR1)
-# define GOOGLE_PROTOBUF_HASH_NAMESPACE std::tr1
-# include <tr1/unordered_map>
-# define GOOGLE_PROTOBUF_HASH_MAP_CLASS unordered_map
-# include <tr1/unordered_set>
-# define GOOGLE_PROTOBUF_HASH_SET_CLASS unordered_set
-#endif
+#include <unordered_map>
+#include <unordered_set>
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START \
namespace google { \
namespace protobuf {
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END }}
-#undef GOOGLE_PROTOBUF_HAS_CXX11_HASH
-#undef GOOGLE_PROTOBUF_HAS_TR1
-
-#if defined(GOOGLE_PROTOBUF_HAVE_HASH_MAP) && \
- defined(GOOGLE_PROTOBUF_HAVE_HASH_SET)
-#else
-#define GOOGLE_PROTOBUF_MISSING_HASH
-#include <map>
-#include <set>
-#endif
-
namespace google {
namespace protobuf {
-#ifdef GOOGLE_PROTOBUF_MISSING_HASH
-#undef GOOGLE_PROTOBUF_MISSING_HASH
-
-// This system doesn't have hash_map or hash_set. Emulate them using map and
-// set.
-
-// Make hash<T> be the same as less<T>. Note that everywhere where custom
-// hash functions are defined in the protobuf code, they are also defined such
-// that they can be used as "less" functions, which is required by MSVC anyway.
template <typename Key>
-struct hash {
- // Dummy, just to make derivative hash functions compile.
- int operator()(const Key& key) {
- GOOGLE_LOG(FATAL) << "Should never be called.";
- return 0;
- }
-
- inline bool operator()(const Key& a, const Key& b) const {
- return a < b;
- }
-};
-
-// Make sure char* is compared by value.
-template <>
-struct hash<const char*> {
- // Dummy, just to make derivative hash functions compile.
- int operator()(const char* key) {
- GOOGLE_LOG(FATAL) << "Should never be called.";
- return 0;
- }
-
- inline bool operator()(const char* a, const char* b) const {
- return strcmp(a, b) < 0;
- }
-};
-
-template <typename Key, typename Data,
- typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key>,
- typename Alloc = std::allocator< std::pair<const Key, Data> > >
-class hash_map : public std::map<Key, Data, HashFcn, Alloc> {
- typedef std::map<Key, Data, HashFcn, Alloc> BaseClass;
-
- public:
- hash_map(int a = 0, const HashFcn& b = HashFcn(),
- const EqualKey& c = EqualKey(),
- const Alloc& d = Alloc()) : BaseClass(b, d) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-template <typename Key,
- typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key> >
-class hash_set : public std::set<Key, HashFcn> {
- public:
- hash_set(int = 0) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) && \
- !(defined(_LIBCPP_STD_VER) && _LIBCPP_STD_VER >= 11)
-
-template <typename Key>
-struct hash : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> {
-};
-
-// MSVC's hash_compare<const char*> hashes based on the string contents but
-// compares based on the string pointer. WTF?
-class CstringLess {
- public:
- inline bool operator()(const char* a, const char* b) const {
- return strcmp(a, b) < 0;
- }
-};
-
-template <>
-struct hash<const char*>
- : public GOOGLE_PROTOBUF_HASH_COMPARE<const char*, CstringLess> {};
-
-#ifdef GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
-
-template <typename Key, typename HashFcn, typename EqualKey>
-struct InternalHashCompare : public GOOGLE_PROTOBUF_HASH_COMPARE<Key> {
- InternalHashCompare() {}
- InternalHashCompare(HashFcn hashfcn, EqualKey equalkey)
- : hashfcn_(hashfcn), equalkey_(equalkey) {}
- size_t operator()(const Key& key) const { return hashfcn_(key); }
- bool operator()(const Key& key1, const Key& key2) const {
- return !equalkey_(key1, key2);
- }
- HashFcn hashfcn_;
- EqualKey equalkey_;
-};
-
-template <typename Key, typename Data,
- typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key>,
- typename Alloc = std::allocator< std::pair<const Key, Data> > >
-class hash_map
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> {
- typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, InternalHashCompare<Key, HashFcn, EqualKey>, Alloc> BaseClass;
-
- public:
- hash_map(int a = 0, const HashFcn& b = HashFcn(),
- const EqualKey& c = EqualKey(), const Alloc& d = Alloc())
- : BaseClass(InternalHashCompare<Key, HashFcn, EqualKey>(b, c), d) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-template <typename Key, typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key> >
-class hash_set
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
- Key, InternalHashCompare<Key, HashFcn, EqualKey> > {
- public:
- hash_set(int = 0) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-#else // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
-
-template <typename Key, typename Data,
- typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key>,
- typename Alloc = std::allocator< std::pair<const Key, Data> > >
-class hash_map
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, HashFcn, EqualKey, Alloc> {
- typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, HashFcn, EqualKey, Alloc> BaseClass;
-
- public:
- hash_map(int a = 0, const HashFcn& b = HashFcn(),
- const EqualKey& c = EqualKey(),
- const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-template <typename Key, typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key> >
-class hash_set
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
- Key, HashFcn, EqualKey> {
- public:
- hash_set(int = 0) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-#endif // GOOGLE_PROTOBUF_CONTAINERS_NEED_HASH_COMPARE
-
-#else // defined(_MSC_VER) && !defined(_STLPORT_VERSION)
-
-template <typename Key>
-struct hash : public GOOGLE_PROTOBUF_HASH_NAMESPACE::hash<Key> {
-};
+struct hash : public std::hash<Key> {};
template <typename Key>
struct hash<const Key*> {
@@ -364,37 +77,6 @@ struct hash<bool> {
}
};
-template <typename Key, typename Data,
- typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key>,
- typename Alloc = std::allocator< std::pair<const Key, Data> > >
-class hash_map
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, HashFcn, EqualKey, Alloc> {
- typedef GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_MAP_CLASS<
- Key, Data, HashFcn, EqualKey, Alloc> BaseClass;
-
- public:
- hash_map(int a = 0, const HashFcn& b = HashFcn(),
- const EqualKey& c = EqualKey(),
- const Alloc& d = Alloc()) : BaseClass(a, b, c, d) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-template <typename Key, typename HashFcn = hash<Key>,
- typename EqualKey = std::equal_to<Key> >
-class hash_set
- : public GOOGLE_PROTOBUF_HASH_NAMESPACE::GOOGLE_PROTOBUF_HASH_SET_CLASS<
- Key, HashFcn, EqualKey> {
- public:
- hash_set(int = 0) {}
-
- HashFcn hash_function() const { return HashFcn(); }
-};
-
-#endif // !GOOGLE_PROTOBUF_MISSING_HASH
-
template <>
struct hash<string> {
inline size_t operator()(const string& key) const {
diff --git a/src/google/protobuf/stubs/int128.cc b/src/google/protobuf/stubs/int128.cc
index a5090801..f86ac4a0 100644
--- a/src/google/protobuf/stubs/int128.cc
+++ b/src/google/protobuf/stubs/int128.cc
@@ -34,12 +34,14 @@
#include <ostream> // NOLINT(readability/streams)
#include <sstream>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
const uint128_pod kuint128max = {
- static_cast<uint64>(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF)),
- static_cast<uint64>(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF))
+ static_cast<uint64>(PROTOBUF_LONGLONG(0xFFFFFFFFFFFFFFFF)),
+ static_cast<uint64>(PROTOBUF_LONGLONG(0xFFFFFFFFFFFFFFFF))
};
// Returns the 0-based position of the last set bit (i.e., most significant bit)
@@ -63,7 +65,7 @@ static inline int Fls64(uint64 n) {
STEP(uint32, n32, pos, 0x10);
STEP(uint32, n32, pos, 0x08);
STEP(uint32, n32, pos, 0x04);
- return pos + ((GOOGLE_ULONGLONG(0x3333333322221100) >> (n32 << 2)) & 0x3);
+ return pos + ((PROTOBUF_ULONGLONG(0x3333333322221100) >> (n32 << 2)) & 0x3);
}
#undef STEP
@@ -76,52 +78,36 @@ static inline int Fls128(uint128 n) {
return Fls64(Uint128Low64(n));
}
-// Long division/modulo for uint128 implemented using the shift-subtract
-// division algorithm adapted from:
-// http://stackoverflow.com/questions/5386377/division-without-using
void uint128::DivModImpl(uint128 dividend, uint128 divisor,
uint128* quotient_ret, uint128* remainder_ret) {
if (divisor == 0) {
GOOGLE_LOG(FATAL) << "Division or mod by zero: dividend.hi=" << dividend.hi_
<< ", lo=" << dividend.lo_;
- }
-
- if (divisor > dividend) {
+ } else if (dividend < divisor) {
*quotient_ret = 0;
*remainder_ret = dividend;
return;
- }
-
- if (divisor == dividend) {
- *quotient_ret = 1;
- *remainder_ret = 0;
- return;
- }
-
- uint128 denominator = divisor;
- uint128 position = 1;
- uint128 quotient = 0;
-
- // Left aligns the MSB of the denominator and the dividend.
- int shift = Fls128(dividend) - Fls128(denominator);
- denominator <<= shift;
- position <<= shift;
-
- // Uses shift-subtract algorithm to divide dividend by denominator. The
- // remainder will be left in dividend.
- while (position > 0) {
- if (dividend >= denominator) {
- dividend -= denominator;
- quotient |= position;
+ } else {
+ int dividend_bit_length = Fls128(dividend);
+ int divisor_bit_length = Fls128(divisor);
+ int difference = dividend_bit_length - divisor_bit_length;
+ uint128 quotient = 0;
+ while (difference >= 0) {
+ quotient <<= 1;
+ uint128 shifted_divisor = divisor << difference;
+ if (shifted_divisor <= dividend) {
+ dividend -= shifted_divisor;
+ quotient += 1;
+ }
+ difference -= 1;
}
- position >>= 1;
- denominator >>= 1;
+ //record the final quotient and remainder
+ *quotient_ret = quotient;
+ *remainder_ret = dividend;
}
-
- *quotient_ret = quotient;
- *remainder_ret = dividend;
}
+
uint128& uint128::operator/=(const uint128& divisor) {
uint128 quotient = 0;
uint128 remainder = 0;
@@ -145,15 +131,18 @@ std::ostream& operator<<(std::ostream& o, const uint128& b) {
std::streamsize div_base_log;
switch (flags & std::ios::basefield) {
case std::ios::hex:
- div = static_cast<uint64>(GOOGLE_ULONGLONG(0x1000000000000000)); // 16^15
+ div =
+ static_cast<uint64>(PROTOBUF_ULONGLONG(0x1000000000000000)); // 16^15
div_base_log = 15;
break;
case std::ios::oct:
- div = static_cast<uint64>(GOOGLE_ULONGLONG(01000000000000000000000)); // 8^21
+ div = static_cast<uint64>(
+ PROTOBUF_ULONGLONG(01000000000000000000000)); // 8^21
div_base_log = 21;
break;
default: // std::ios::dec
- div = static_cast<uint64>(GOOGLE_ULONGLONG(10000000000000000000)); // 10^19
+ div = static_cast<uint64>(
+ PROTOBUF_ULONGLONG(10000000000000000000)); // 10^19
div_base_log = 19;
break;
}
diff --git a/src/google/protobuf/stubs/int128.h b/src/google/protobuf/stubs/int128.h
index 1499bb76..dc70d96e 100644
--- a/src/google/protobuf/stubs/int128.h
+++ b/src/google/protobuf/stubs/int128.h
@@ -34,6 +34,8 @@
#include <iosfwd>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -48,7 +50,7 @@ struct uint128_pod;
#endif
// An unsigned 128-bit integer type. Thread-compatible.
-class LIBPROTOBUF_EXPORT uint128 {
+class PROTOBUF_EXPORT uint128 {
public:
UINT128_CONSTEXPR uint128(); // Sets to 0, but don't trust on this behavior.
UINT128_CONSTEXPR uint128(uint64 top, uint64 bottom);
@@ -84,8 +86,8 @@ class LIBPROTOBUF_EXPORT uint128 {
friend uint64 Uint128High64(const uint128& v);
// We add "std::" to avoid including all of port.h.
- LIBPROTOBUF_EXPORT friend std::ostream& operator<<(std::ostream& o,
- const uint128& b);
+ PROTOBUF_EXPORT friend std::ostream& operator<<(std::ostream& o,
+ const uint128& b);
private:
static void DivModImpl(uint128 dividend, uint128 divisor,
@@ -116,11 +118,11 @@ struct uint128_pod {
uint64 lo;
};
-LIBPROTOBUF_EXPORT extern const uint128_pod kuint128max;
+PROTOBUF_EXPORT extern const uint128_pod kuint128max;
// allow uint128 to be logged
-LIBPROTOBUF_EXPORT extern std::ostream& operator<<(std::ostream& o,
- const uint128& b);
+PROTOBUF_EXPORT extern std::ostream& operator<<(std::ostream& o,
+ const uint128& b);
// Methods to access low and high pieces of 128-bit value.
// Defined externally from uint128 to facilitate conversion
@@ -380,4 +382,6 @@ inline uint128& uint128::operator--() {
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_INT128_H_
diff --git a/src/google/protobuf/stubs/int128_unittest.cc b/src/google/protobuf/stubs/int128_unittest.cc
index 1ec899ad..9a8125d4 100644
--- a/src/google/protobuf/stubs/int128_unittest.cc
+++ b/src/google/protobuf/stubs/int128_unittest.cc
@@ -37,6 +37,8 @@
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -291,24 +293,26 @@ TEST(Int128, Multiply) {
}
// Verified with dc.
- a = uint128(GOOGLE_ULONGLONG(0xffffeeeeddddcccc),
- GOOGLE_ULONGLONG(0xbbbbaaaa99998888));
- b = uint128(GOOGLE_ULONGLONG(0x7777666655554444),
- GOOGLE_ULONGLONG(0x3333222211110000));
+ a = uint128(PROTOBUF_ULONGLONG(0xffffeeeeddddcccc),
+ PROTOBUF_ULONGLONG(0xbbbbaaaa99998888));
+ b = uint128(PROTOBUF_ULONGLONG(0x7777666655554444),
+ PROTOBUF_ULONGLONG(0x3333222211110000));
c = a * b;
- EXPECT_EQ(uint128(GOOGLE_ULONGLONG(0x530EDA741C71D4C3),
- GOOGLE_ULONGLONG(0xBF25975319080000)), c);
+ EXPECT_EQ(uint128(PROTOBUF_ULONGLONG(0x530EDA741C71D4C3),
+ PROTOBUF_ULONGLONG(0xBF25975319080000)),
+ c);
EXPECT_EQ(0, c - b * a);
- EXPECT_EQ(a*a - b*b, (a+b) * (a-b));
+ EXPECT_EQ(a * a - b * b, (a + b) * (a - b));
// Verified with dc.
- a = uint128(GOOGLE_ULONGLONG(0x0123456789abcdef),
- GOOGLE_ULONGLONG(0xfedcba9876543210));
- b = uint128(GOOGLE_ULONGLONG(0x02468ace13579bdf),
- GOOGLE_ULONGLONG(0xfdb97531eca86420));
+ a = uint128(PROTOBUF_ULONGLONG(0x0123456789abcdef),
+ PROTOBUF_ULONGLONG(0xfedcba9876543210));
+ b = uint128(PROTOBUF_ULONGLONG(0x02468ace13579bdf),
+ PROTOBUF_ULONGLONG(0xfdb97531eca86420));
c = a * b;
- EXPECT_EQ(uint128(GOOGLE_ULONGLONG(0x97a87f4f261ba3f2),
- GOOGLE_ULONGLONG(0x342d0bbf48948200)), c);
+ EXPECT_EQ(uint128(PROTOBUF_ULONGLONG(0x97a87f4f261ba3f2),
+ PROTOBUF_ULONGLONG(0x342d0bbf48948200)),
+ c);
EXPECT_EQ(0, c - b * a);
EXPECT_EQ(a*a - b*b, (a+b) * (a-b));
}
@@ -355,10 +359,10 @@ TEST(Int128, DivideAndMod) {
EXPECT_EQ(0, q);
EXPECT_EQ(0, r);
- a = uint128(GOOGLE_ULONGLONG(0x530eda741c71d4c3),
- GOOGLE_ULONGLONG(0xbf25975319080000));
- q = uint128(GOOGLE_ULONGLONG(0x4de2cab081),
- GOOGLE_ULONGLONG(0x14c34ab4676e4bab));
+ a = uint128(PROTOBUF_ULONGLONG(0x530eda741c71d4c3),
+ PROTOBUF_ULONGLONG(0xbf25975319080000));
+ q = uint128(PROTOBUF_ULONGLONG(0x4de2cab081),
+ PROTOBUF_ULONGLONG(0x14c34ab4676e4bab));
b = uint128(0x1110001);
r = uint128(0x3eb455);
ASSERT_EQ(a, q * b + r); // Sanity-check.
@@ -396,8 +400,8 @@ TEST(Int128, DivideAndMod) {
// Try a large remainder.
b = a / 2 + 1;
- uint128 expected_r(GOOGLE_ULONGLONG(0x29876d3a0e38ea61),
- GOOGLE_ULONGLONG(0xdf92cba98c83ffff));
+ uint128 expected_r(PROTOBUF_ULONGLONG(0x29876d3a0e38ea61),
+ PROTOBUF_ULONGLONG(0xdf92cba98c83ffff));
// Sanity checks.
ASSERT_EQ(a / 2 - 1, expected_r);
ASSERT_EQ(a, b + expected_r);
@@ -455,50 +459,50 @@ TEST(Int128, OStream) {
char fill;
const char* rep;
} cases[] = {
- // zero with different bases
- {uint128(0), std::ios::dec, 0, '_', "0"},
- {uint128(0), std::ios::oct, 0, '_', "0"},
- {uint128(0), std::ios::hex, 0, '_', "0"},
- // crossover between lo_ and hi_
- {uint128(0, -1), std::ios::dec, 0, '_', "18446744073709551615"},
- {uint128(0, -1), std::ios::oct, 0, '_', "1777777777777777777777"},
- {uint128(0, -1), std::ios::hex, 0, '_', "ffffffffffffffff"},
- {uint128(1, 0), std::ios::dec, 0, '_', "18446744073709551616"},
- {uint128(1, 0), std::ios::oct, 0, '_', "2000000000000000000000"},
- {uint128(1, 0), std::ios::hex, 0, '_', "10000000000000000"},
- // just the top bit
- {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::dec, 0, '_',
- "170141183460469231731687303715884105728"},
- {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::oct, 0, '_',
- "2000000000000000000000000000000000000000000"},
- {uint128(GOOGLE_ULONGLONG(0x8000000000000000), 0), std::ios::hex, 0, '_',
- "80000000000000000000000000000000"},
- // maximum uint128 value
- {uint128(-1, -1), std::ios::dec, 0, '_',
- "340282366920938463463374607431768211455"},
- {uint128(-1, -1), std::ios::oct, 0, '_',
- "3777777777777777777777777777777777777777777"},
- {uint128(-1, -1), std::ios::hex, 0, '_',
- "ffffffffffffffffffffffffffffffff"},
- // uppercase
- {uint128(-1, -1), std::ios::hex | std::ios::uppercase, 0, '_',
- "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"},
- // showbase
- {uint128(1), std::ios::dec | std::ios::showbase, 0, '_', "1"},
- {uint128(1), std::ios::oct | std::ios::showbase, 0, '_', "01"},
- {uint128(1), std::ios::hex | std::ios::showbase, 0, '_', "0x1"},
- // showbase does nothing on zero
- {uint128(0), std::ios::dec | std::ios::showbase, 0, '_', "0"},
- {uint128(0), std::ios::oct | std::ios::showbase, 0, '_', "0"},
- {uint128(0), std::ios::hex | std::ios::showbase, 0, '_', "0"},
- // showpos does nothing on unsigned types
- {uint128(1), std::ios::dec | std::ios::showpos, 0, '_', "1"},
- // padding
- {uint128(9), std::ios::dec, 6, '_', "_____9"},
- {uint128(12345), std::ios::dec, 6, '_', "_12345"},
- // left adjustment
- {uint128(9), std::ios::dec | std::ios::left, 6, '_', "9_____"},
- {uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"},
+ // zero with different bases
+ {uint128(0), std::ios::dec, 0, '_', "0"},
+ {uint128(0), std::ios::oct, 0, '_', "0"},
+ {uint128(0), std::ios::hex, 0, '_', "0"},
+ // crossover between lo_ and hi_
+ {uint128(0, -1), std::ios::dec, 0, '_', "18446744073709551615"},
+ {uint128(0, -1), std::ios::oct, 0, '_', "1777777777777777777777"},
+ {uint128(0, -1), std::ios::hex, 0, '_', "ffffffffffffffff"},
+ {uint128(1, 0), std::ios::dec, 0, '_', "18446744073709551616"},
+ {uint128(1, 0), std::ios::oct, 0, '_', "2000000000000000000000"},
+ {uint128(1, 0), std::ios::hex, 0, '_', "10000000000000000"},
+ // just the top bit
+ {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::dec, 0,
+ '_', "170141183460469231731687303715884105728"},
+ {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::oct, 0,
+ '_', "2000000000000000000000000000000000000000000"},
+ {uint128(PROTOBUF_ULONGLONG(0x8000000000000000), 0), std::ios::hex, 0,
+ '_', "80000000000000000000000000000000"},
+ // maximum uint128 value
+ {uint128(-1, -1), std::ios::dec, 0, '_',
+ "340282366920938463463374607431768211455"},
+ {uint128(-1, -1), std::ios::oct, 0, '_',
+ "3777777777777777777777777777777777777777777"},
+ {uint128(-1, -1), std::ios::hex, 0, '_',
+ "ffffffffffffffffffffffffffffffff"},
+ // uppercase
+ {uint128(-1, -1), std::ios::hex | std::ios::uppercase, 0, '_',
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"},
+ // showbase
+ {uint128(1), std::ios::dec | std::ios::showbase, 0, '_', "1"},
+ {uint128(1), std::ios::oct | std::ios::showbase, 0, '_', "01"},
+ {uint128(1), std::ios::hex | std::ios::showbase, 0, '_', "0x1"},
+ // showbase does nothing on zero
+ {uint128(0), std::ios::dec | std::ios::showbase, 0, '_', "0"},
+ {uint128(0), std::ios::oct | std::ios::showbase, 0, '_', "0"},
+ {uint128(0), std::ios::hex | std::ios::showbase, 0, '_', "0"},
+ // showpos does nothing on unsigned types
+ {uint128(1), std::ios::dec | std::ios::showpos, 0, '_', "1"},
+ // padding
+ {uint128(9), std::ios::dec, 6, '_', "_____9"},
+ {uint128(12345), std::ios::dec, 6, '_', "_12345"},
+ // left adjustment
+ {uint128(9), std::ios::dec | std::ios::left, 6, '_', "9_____"},
+ {uint128(12345), std::ios::dec | std::ios::left, 6, '_', "12345_"},
};
for (size_t i = 0; i < GOOGLE_ARRAYSIZE(cases); ++i) {
std::ostringstream os;
diff --git a/src/google/protobuf/stubs/io_win32.cc b/src/google/protobuf/stubs/io_win32.cc
index 4407facb..f00a268f 100644
--- a/src/google/protobuf/stubs/io_win32.cc
+++ b/src/google/protobuf/stubs/io_win32.cc
@@ -91,7 +91,7 @@ struct CharTraits<wchar_t> {
template <typename char_type>
bool null_or_empty(const char_type* s) {
- return s == NULL || *s == 0;
+ return s == nullptr || *s == 0;
}
// Returns true if the path starts with a drive letter, e.g. "c:".
@@ -225,7 +225,7 @@ bool as_windows_path(const char* path, wstring* result) {
if (!is_path_absolute(wpath.c_str())) {
- int size = ::GetCurrentDirectoryW(0, NULL);
+ int size = ::GetCurrentDirectoryW(0, nullptr);
if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
@@ -316,17 +316,17 @@ FILE* fopen(const char* path, const char* mode) {
#ifdef SUPPORT_LONGPATHS
if (null_or_empty(path)) {
errno = EINVAL;
- return NULL;
+ return nullptr;
}
wstring wpath;
if (!as_windows_path(path, &wpath)) {
errno = ENOENT;
- return NULL;
+ return nullptr;
}
wstring wmode;
if (!strings::utf8_to_wcs(mode, &wmode)) {
errno = EINVAL;
- return NULL;
+ return nullptr;
}
return ::_wfopen(wpath.c_str(), wmode.c_str());
#else
@@ -365,15 +365,15 @@ bool wcs_to_mbs(const WCHAR* s, string* out, bool outUtf8) {
BOOL usedDefaultChar = FALSE;
SetLastError(0);
int size = WideCharToMultiByte(
- outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0, NULL,
- outUtf8 ? NULL : &usedDefaultChar);
+ outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0, nullptr,
+ outUtf8 ? nullptr : &usedDefaultChar);
if ((size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
|| usedDefaultChar) {
return false;
}
std::unique_ptr<CHAR[]> astr(new CHAR[size]);
WideCharToMultiByte(
- outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, NULL, NULL);
+ outUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, astr.get(), size, nullptr, nullptr);
out->assign(astr.get());
return true;
}
@@ -386,7 +386,7 @@ bool mbs_to_wcs(const char* s, wstring* out, bool inUtf8) {
SetLastError(0);
int size =
- MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, NULL, 0);
+ MultiByteToWideChar(inUtf8 ? CP_UTF8 : CP_ACP, 0, s, -1, nullptr, 0);
if (size == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
diff --git a/src/google/protobuf/stubs/io_win32.h b/src/google/protobuf/stubs/io_win32.h
index 9e17d253..afa5de35 100644
--- a/src/google/protobuf/stubs/io_win32.h
+++ b/src/google/protobuf/stubs/io_win32.h
@@ -50,6 +50,8 @@
#include <string>
#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port_def.inc>
+
// Compilers on Windows other than MSVC (e.g. Cygwin, MinGW32) define the
// following functions already, except for mkdir.
namespace google {
@@ -57,35 +59,34 @@ 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_utf8_to_winpath(const char* path);
+PROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode);
+PROTOBUF_EXPORT int access(const char* path, int mode);
+PROTOBUF_EXPORT int chdir(const char* path);
+PROTOBUF_EXPORT int close(int fd);
+PROTOBUF_EXPORT int dup(int fd);
+PROTOBUF_EXPORT int dup2(int fd1, int fd2);
+PROTOBUF_EXPORT int mkdir(const char* path, int _mode);
+PROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0);
+PROTOBUF_EXPORT int read(int fd, void* buffer, size_t size);
+PROTOBUF_EXPORT int setmode(int fd, int mode);
+PROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer);
+PROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size);
+PROTOBUF_EXPORT std::wstring testonly_utf8_to_winpath(const char* path);
namespace strings {
// Convert from UTF-16 to Active-Code-Page-encoded or to UTF-8-encoded text.
-LIBPROTOBUF_EXPORT bool wcs_to_mbs(
- const wchar_t* s, std::string* out, bool outUtf8);
+PROTOBUF_EXPORT bool wcs_to_mbs(const wchar_t* s, std::string* out,
+ bool outUtf8);
// Convert from Active-Code-Page-encoded or UTF-8-encoded text to UTF-16.
-LIBPROTOBUF_EXPORT bool mbs_to_wcs(
- const char* s, std::wstring* out, bool inUtf8);
+PROTOBUF_EXPORT bool mbs_to_wcs(const char* s, std::wstring* out, bool inUtf8);
// Convert from UTF-8-encoded text to UTF-16.
-LIBPROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out);
+PROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out);
// Convert from UTF-16-encoded text to UTF-8.
-LIBPROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out);
+PROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out);
} // namespace strings
@@ -112,4 +113,6 @@ LIBPROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out);
#endif // defined(_WIN32)
+#include <google/protobuf/port_undef.inc>
+
#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
index c933757c..6c70d461 100644
--- a/src/google/protobuf/stubs/io_win32_unittest.cc
+++ b/src/google/protobuf/stubs/io_win32_unittest.cc
@@ -63,17 +63,17 @@ namespace {
const char kUtf8Text[] = {
'h', 'i', ' ',
// utf-8: 11010000 10011111, utf-16: 100 0001 1111 = 0x041F
- 0xd0, 0x9f,
+ static_cast<char>(0xd0), static_cast<char>(0x9f),
// utf-8: 11010001 10000000, utf-16: 100 0100 0000 = 0x0440
- 0xd1, 0x80,
+ static_cast<char>(0xd1), static_cast<char>(0x80),
// utf-8: 11010000 10111000, utf-16: 100 0011 1000 = 0x0438
- 0xd0, 0xb8,
+ static_cast<char>(0xd0), static_cast<char>(0xb8),
// utf-8: 11010000 10110010, utf-16: 100 0011 0010 = 0x0432
- 0xd0, 0xb2,
+ static_cast<char>(0xd0), static_cast<char>(0xb2),
// utf-8: 11010000 10110101, utf-16: 100 0011 0101 = 0x0435
- 0xd0, 0xb5,
+ static_cast<char>(0xd0), static_cast<char>(0xb5),
// utf-8: 11010001 10000010, utf-16: 100 0100 0010 = 0x0442
- 0xd1, 0x82, 0
+ static_cast<char>(0xd1), static_cast<char>(0x82), 0
};
const wchar_t kUtf16Text[] = {
@@ -112,7 +112,7 @@ void StripTrailingSlashes(string* str) {
}
bool GetEnvVarAsUtf8(const WCHAR* name, string* result) {
- DWORD size = ::GetEnvironmentVariableW(name, NULL, 0);
+ DWORD size = ::GetEnvironmentVariableW(name, nullptr, 0);
if (size > 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND) {
std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
::GetEnvironmentVariableW(name, wcs.get(), size);
@@ -128,7 +128,7 @@ bool GetEnvVarAsUtf8(const WCHAR* name, string* result) {
}
bool GetCwdAsUtf8(string* result) {
- DWORD size = ::GetCurrentDirectoryW(0, NULL);
+ DWORD size = ::GetCurrentDirectoryW(0, nullptr);
if (size > 0) {
std::unique_ptr<WCHAR[]> wcs(new WCHAR[size]);
::GetCurrentDirectoryW(size, wcs.get());
@@ -201,7 +201,7 @@ bool IoWin32Test::CreateAllUnder(wstring path) {
if (path.find(L"\\\\?\\") != 0) {
path = wstring(L"\\\\?\\") + path;
}
- if (::CreateDirectoryW(path.c_str(), NULL) ||
+ if (::CreateDirectoryW(path.c_str(), nullptr) ||
GetLastError() == ERROR_ALREADY_EXISTS ||
GetLastError() == ERROR_ACCESS_DENIED) {
return true;
@@ -210,7 +210,7 @@ bool IoWin32Test::CreateAllUnder(wstring path) {
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)) {
+ if (CreateAllUnder(parent) && CreateDirectoryW(path.c_str(), nullptr)) {
return true;
}
}
@@ -352,8 +352,8 @@ TEST_F(IoWin32Test, MkdirTestNonAscii) {
// Create a non-ASCII path.
// Ensure that we can create the directory using SetCurrentDirectoryW.
- EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), NULL));
- EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), NULL));
+ EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1").c_str(), nullptr));
+ EXPECT_TRUE(CreateDirectoryW((wtest_tmpdir + L"\\1\\" + kUtf16Text).c_str(), nullptr));
// Ensure that we can create a very similarly named directory using mkdir.
// We don't attemp to delete and recreate the same directory, because on
// Windows, deleting files and directories seems to be asynchronous.
@@ -386,7 +386,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) {
wstring wNonAscii(wtest_tmpdir + L"\\" + kUtf16Text);
string nonAscii;
EXPECT_TRUE(strings::wcs_to_utf8(wNonAscii.c_str(), &nonAscii));
- EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), NULL));
+ EXPECT_TRUE(CreateDirectoryW(wNonAscii.c_str(), nullptr));
WCHAR cwd[MAX_PATH];
EXPECT_TRUE(GetCurrentDirectoryW(MAX_PATH, cwd));
// Ensure that we can cd into the path using SetCurrentDirectoryW.
@@ -400,7 +400,7 @@ TEST_F(IoWin32Test, ChdirTestNonAscii) {
}
TEST_F(IoWin32Test, AsWindowsPathTest) {
- DWORD size = GetCurrentDirectoryW(0, NULL);
+ DWORD size = GetCurrentDirectoryW(0, nullptr);
std::unique_ptr<wchar_t[]> cwd_str(new wchar_t[size]);
EXPECT_GT(GetCurrentDirectoryW(size, cwd_str.get()), 0);
wstring cwd = wstring(L"\\\\?\\") + cwd_str.get();
diff --git a/src/google/protobuf/stubs/logging.h b/src/google/protobuf/stubs/logging.h
index f69605d9..8d7e6401 100644
--- a/src/google/protobuf/stubs/logging.h
+++ b/src/google/protobuf/stubs/logging.h
@@ -34,6 +34,8 @@
#include <google/protobuf/stubs/macros.h>
#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port_def.inc>
+
// ===================================================================
// emulates google3/base/logging.h
@@ -70,7 +72,7 @@ namespace internal {
class LogFinisher;
-class LIBPROTOBUF_EXPORT LogMessage {
+class PROTOBUF_EXPORT LogMessage {
public:
LogMessage(LogLevel level, const char* filename, int line);
~LogMessage();
@@ -102,7 +104,7 @@ class LIBPROTOBUF_EXPORT LogMessage {
// Used to make the entire "LOG(BLAH) << etc." expression have a void return
// type and print a newline after each message.
-class LIBPROTOBUF_EXPORT LogFinisher {
+class PROTOBUF_EXPORT LogFinisher {
public:
void operator=(LogMessage& other);
};
@@ -162,7 +164,7 @@ namespace internal {
template<typename T>
T* CheckNotNull(const char* /* file */, int /* line */,
const char* name, T* val) {
- if (val == NULL) {
+ if (val == nullptr) {
GOOGLE_LOG(FATAL) << name;
}
return val;
@@ -170,7 +172,7 @@ T* CheckNotNull(const char* /* file */, int /* line */,
} // namespace internal
#define GOOGLE_CHECK_NOTNULL(A) \
::google::protobuf::internal::CheckNotNull(\
- __FILE__, __LINE__, "'" #A "' must not be NULL", (A))
+ __FILE__, __LINE__, "'" #A "' must not be nullptr", (A))
#ifdef NDEBUG
@@ -208,7 +210,7 @@ typedef void LogHandler(LogLevel level, const char* filename, int line,
// also help end users figure out a problem. If you would prefer that
// these messages be sent somewhere other than stderr, call SetLogHandler()
// to set your own handler. This returns the old handler. Set the handler
-// to NULL to ignore log messages (but see also LogSilencer, below).
+// to nullptr to ignore log messages (but see also LogSilencer, below).
//
// Obviously, SetLogHandler is not thread-safe. You should only call it
// at initialization time, and probably not from library code. If you
@@ -216,7 +218,7 @@ typedef void LogHandler(LogLevel level, const char* filename, int line,
// have some code that tends to trigger them frequently and you know
// the warnings are not important to you), use the LogSilencer class
// below.
-LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func);
+PROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func);
// Create a LogSilencer if you want to temporarily suppress all log
// messages. As long as any LogSilencer objects exist, non-fatal
@@ -225,7 +227,7 @@ LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func);
// accidentally suppress log messages occurring in another thread, but
// since messages are generally for debugging purposes only, this isn't
// a big deal. If you want to intercept log messages, use SetLogHandler().
-class LIBPROTOBUF_EXPORT LogSilencer {
+class PROTOBUF_EXPORT LogSilencer {
public:
LogSilencer();
~LogSilencer();
@@ -234,4 +236,6 @@ class LIBPROTOBUF_EXPORT LogSilencer {
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_LOGGING_H_
diff --git a/src/google/protobuf/stubs/map_util.h b/src/google/protobuf/stubs/map_util.h
index 3e6d381f..2313e1f5 100644
--- a/src/google/protobuf/stubs/map_util.h
+++ b/src/google/protobuf/stubs/map_util.h
@@ -131,7 +131,7 @@ FindWithDefault(const Collection& collection,
}
// Returns a pointer to the const value associated with the given key if it
-// exists, or NULL otherwise.
+// exists, or nullptr otherwise.
template <class Collection>
const typename Collection::value_type::second_type*
FindOrNull(const Collection& collection,
@@ -156,11 +156,11 @@ FindOrNull(Collection& collection, // NOLINT
}
// Returns the pointer value associated with the given key. If none is found,
-// NULL is returned. The function is designed to be used with a map of keys to
+// nullptr is returned. The function is designed to be used with a map of keys to
// pointers.
//
// This function does not distinguish between a missing key and a key mapped
-// to a NULL value.
+// to nullptr.
template <class Collection>
typename Collection::value_type::second_type
FindPtrOrNull(const Collection& collection,
@@ -188,7 +188,7 @@ FindPtrOrNull(Collection& collection, // NOLINT
}
// Finds the pointer value associated with the given key in a map whose values
-// are linked_ptrs. Returns NULL if key is not found.
+// are linked_ptrs. Returns nullptr if key is not found.
template <class Collection>
typename Collection::value_type::second_type::element_type*
FindLinkedPtrOrNull(const Collection& collection,
@@ -215,7 +215,7 @@ FindLinkedPtrOrDie(const Collection& collection,
}
// Finds the value associated with the given key and copies it to *value (if not
-// NULL). Returns false if the key was not found, true otherwise.
+// nullptr). Returns false if the key was not found, true otherwise.
template <class Collection, class Key, class Value>
bool FindCopy(const Collection& collection,
const Key& key,
@@ -447,7 +447,7 @@ LookupOrInsertNew(Collection* const collection,
std::pair<typename Collection::iterator, bool> ret =
collection->insert(typename Collection::value_type(
key,
- static_cast<typename Collection::value_type::second_type>(NULL)));
+ static_cast<typename Collection::value_type::second_type>(nullptr)));
if (ret.second) {
ret.first->second = new Element();
}
@@ -466,7 +466,7 @@ LookupOrInsertNew(Collection* const collection,
std::pair<typename Collection::iterator, bool> ret =
collection->insert(typename Collection::value_type(
key,
- static_cast<typename Collection::value_type::second_type>(NULL)));
+ static_cast<typename Collection::value_type::second_type>(nullptr)));
if (ret.second) {
ret.first->second = new Element(arg);
}
@@ -612,7 +612,7 @@ bool UpdateReturnCopy(Collection* const collection,
return false;
}
-// Tries to insert the given key-value pair into the collection. Returns NULL if
+// Tries to insert the given key-value pair into the collection. Returns nullptr if
// the insert succeeds. Otherwise, returns a pointer to the existing value.
//
// This complements UpdateReturnCopy in that it allows to update only after
@@ -625,7 +625,7 @@ InsertOrReturnExisting(Collection* const collection,
const typename Collection::value_type& vt) {
std::pair<typename Collection::iterator, bool> ret = collection->insert(vt);
if (ret.second) {
- return NULL; // Inserted, no existing previous value.
+ return nullptr; // Inserted, no existing previous value.
} else {
return &ret.first->second; // Return address of already existing value.
}
@@ -644,7 +644,7 @@ InsertOrReturnExisting(
// Erases the collection item identified by the given key, and returns the value
// associated with that key. It is assumed that the value (i.e., the
-// mapped_type) is a pointer. Returns NULL if the key was not found in the
+// mapped_type) is a pointer. Returns nullptr if the key was not found in the
// collection.
//
// Examples:
@@ -665,7 +665,7 @@ typename Collection::value_type::second_type EraseKeyReturnValuePtr(
const typename Collection::value_type::first_type& key) {
typename Collection::iterator it = collection->find(key);
if (it == collection->end()) {
- return NULL;
+ return nullptr;
}
typename Collection::value_type::second_type v = it->second;
collection->erase(it);
@@ -679,7 +679,7 @@ typename Collection::value_type::second_type EraseKeyReturnValuePtr(
template <class MapContainer, class KeyContainer>
void InsertKeysFromMap(const MapContainer& map_container,
KeyContainer* key_container) {
- GOOGLE_CHECK(key_container != NULL);
+ GOOGLE_CHECK(key_container != nullptr);
for (typename MapContainer::const_iterator it = map_container.begin();
it != map_container.end(); ++it) {
key_container->insert(it->first);
@@ -693,7 +693,7 @@ void InsertKeysFromMap(const MapContainer& map_container,
template <class MapContainer, class KeyContainer>
void AppendKeysFromMap(const MapContainer& map_container,
KeyContainer* key_container) {
- GOOGLE_CHECK(key_container != NULL);
+ GOOGLE_CHECK(key_container != nullptr);
for (typename MapContainer::const_iterator it = map_container.begin();
it != map_container.end(); ++it) {
key_container->push_back(it->first);
@@ -710,7 +710,7 @@ void AppendKeysFromMap(const MapContainer& map_container,
template <class MapContainer, class KeyType>
void AppendKeysFromMap(const MapContainer& map_container,
std::vector<KeyType>* key_container) {
- GOOGLE_CHECK(key_container != NULL);
+ GOOGLE_CHECK(key_container != nullptr);
// We now have the opportunity to call reserve(). Calling reserve() every
// time is a bad idea for some use cases: libstdc++'s implementation of
// vector<>::reserve() resizes the vector's backing store to exactly the
@@ -737,7 +737,7 @@ void AppendKeysFromMap(const MapContainer& map_container,
template <class MapContainer, class ValueContainer>
void AppendValuesFromMap(const MapContainer& map_container,
ValueContainer* value_container) {
- GOOGLE_CHECK(value_container != NULL);
+ GOOGLE_CHECK(value_container != nullptr);
for (typename MapContainer::const_iterator it = map_container.begin();
it != map_container.end(); ++it) {
value_container->push_back(it->second);
@@ -754,7 +754,7 @@ void AppendValuesFromMap(const MapContainer& map_container,
template <class MapContainer, class ValueType>
void AppendValuesFromMap(const MapContainer& map_container,
std::vector<ValueType>* value_container) {
- GOOGLE_CHECK(value_container != NULL);
+ GOOGLE_CHECK(value_container != nullptr);
// See AppendKeysFromMap for why this is done.
if (value_container->empty()) {
value_container->reserve(map_container.size());
diff --git a/src/google/protobuf/stubs/mathlimits.h b/src/google/protobuf/stubs/mathlimits.h
index 9c9d0e9a..e603947a 100644
--- a/src/google/protobuf/stubs/mathlimits.h
+++ b/src/google/protobuf/stubs/mathlimits.h
@@ -66,6 +66,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
// ========================================================================= //
// Useful integer and floating point limits and type traits.
@@ -173,43 +175,43 @@ template<typename T> struct MathLimits {
static bool IsPosInf(const Type /*x*/) { return false; } \
static bool IsNegInf(const Type /*x*/) { return false; }
-#define DECL_SIGNED_INT_LIMITS(IntType, UnsignedIntType) \
-template<> \
-struct LIBPROTOBUF_EXPORT MathLimits<IntType> { \
- typedef IntType Type; \
- typedef UnsignedIntType UnsignedType; \
- static const bool kIsSigned = true; \
- static const bool kIsInteger = true; \
- static const Type kPosMin = 1; \
- static const Type kPosMax = SIGNED_INT_MAX(Type); \
- static const Type kMin = SIGNED_INT_MIN(Type); \
- static const Type kMax = kPosMax; \
- static const Type kNegMin = -1; \
- static const Type kNegMax = kMin; \
- static const int kMin10Exp = 0; \
- static const int kMax10Exp = SIGNED_MAX_10_EXP(Type); \
- static const Type kEpsilon = 1; \
- static const Type kStdError = 0; \
- DECL_INT_LIMIT_FUNCS \
-};
+#define DECL_SIGNED_INT_LIMITS(IntType, UnsignedIntType) \
+ template <> \
+ struct PROTOBUF_EXPORT MathLimits<IntType> { \
+ typedef IntType Type; \
+ typedef UnsignedIntType UnsignedType; \
+ static const bool kIsSigned = true; \
+ static const bool kIsInteger = true; \
+ static const Type kPosMin = 1; \
+ static const Type kPosMax = SIGNED_INT_MAX(Type); \
+ static const Type kMin = SIGNED_INT_MIN(Type); \
+ static const Type kMax = kPosMax; \
+ static const Type kNegMin = -1; \
+ static const Type kNegMax = kMin; \
+ static const int kMin10Exp = 0; \
+ static const int kMax10Exp = SIGNED_MAX_10_EXP(Type); \
+ static const Type kEpsilon = 1; \
+ static const Type kStdError = 0; \
+ DECL_INT_LIMIT_FUNCS \
+ };
-#define DECL_UNSIGNED_INT_LIMITS(IntType) \
-template<> \
-struct LIBPROTOBUF_EXPORT MathLimits<IntType> { \
- typedef IntType Type; \
- typedef IntType UnsignedType; \
- static const bool kIsSigned = false; \
- static const bool kIsInteger = true; \
- static const Type kPosMin = 1; \
- static const Type kPosMax = UNSIGNED_INT_MAX(Type); \
- static const Type kMin = 0; \
- static const Type kMax = kPosMax; \
- static const int kMin10Exp = 0; \
- static const int kMax10Exp = UNSIGNED_MAX_10_EXP(Type); \
- static const Type kEpsilon = 1; \
- static const Type kStdError = 0; \
- DECL_INT_LIMIT_FUNCS \
-};
+#define DECL_UNSIGNED_INT_LIMITS(IntType) \
+ template <> \
+ struct PROTOBUF_EXPORT MathLimits<IntType> { \
+ typedef IntType Type; \
+ typedef IntType UnsignedType; \
+ static const bool kIsSigned = false; \
+ static const bool kIsInteger = true; \
+ static const Type kPosMin = 1; \
+ static const Type kPosMax = UNSIGNED_INT_MAX(Type); \
+ static const Type kMin = 0; \
+ static const Type kMax = kPosMax; \
+ static const int kMin10Exp = 0; \
+ static const int kMax10Exp = UNSIGNED_MAX_10_EXP(Type); \
+ static const Type kEpsilon = 1; \
+ static const Type kStdError = 0; \
+ DECL_INT_LIMIT_FUNCS \
+ };
DECL_SIGNED_INT_LIMITS(signed char, unsigned char)
DECL_SIGNED_INT_LIMITS(signed short int, unsigned short int)
@@ -263,29 +265,29 @@ DECL_UNSIGNED_INT_LIMITS(unsigned long long int)
// such constants are not considered to be primitive-type constants by gcc.
// CAVEAT: Hence, they are going to be initialized only during
// the global objects construction time.
-#define DECL_FP_LIMITS(FP_Type, PREFIX) \
-template<> \
-struct LIBPROTOBUF_EXPORT MathLimits<FP_Type> { \
- typedef FP_Type Type; \
- typedef FP_Type UnsignedType; \
- static const bool kIsSigned = true; \
- static const bool kIsInteger = false; \
- static const Type kPosMin; \
- static const Type kPosMax; \
- static const Type kMin; \
- static const Type kMax; \
- static const Type kNegMin; \
- static const Type kNegMax; \
- static const int kMin10Exp = PREFIX##_MIN_10_EXP; \
- static const int kMax10Exp = PREFIX##_MAX_10_EXP; \
- static const Type kEpsilon; \
- static const Type kStdError; \
- static const int kPrecisionDigits = PREFIX##_DIG; \
- static const Type kNaN; \
- static const Type kPosInf; \
- static const Type kNegInf; \
- DECL_FP_LIMIT_FUNCS \
-};
+#define DECL_FP_LIMITS(FP_Type, PREFIX) \
+ template <> \
+ struct PROTOBUF_EXPORT MathLimits<FP_Type> { \
+ typedef FP_Type Type; \
+ typedef FP_Type UnsignedType; \
+ static const bool kIsSigned = true; \
+ static const bool kIsInteger = false; \
+ static const Type kPosMin; \
+ static const Type kPosMax; \
+ static const Type kMin; \
+ static const Type kMax; \
+ static const Type kNegMin; \
+ static const Type kNegMax; \
+ static const int kMin10Exp = PREFIX##_MIN_10_EXP; \
+ static const int kMax10Exp = PREFIX##_MAX_10_EXP; \
+ static const Type kEpsilon; \
+ static const Type kStdError; \
+ static const int kPrecisionDigits = PREFIX##_DIG; \
+ static const Type kNaN; \
+ static const Type kPosInf; \
+ static const Type kNegInf; \
+ DECL_FP_LIMIT_FUNCS \
+ };
DECL_FP_LIMITS(float, FLT)
DECL_FP_LIMITS(double, DBL)
@@ -300,4 +302,6 @@ DECL_FP_LIMITS(long double, LDBL)
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // UTIL_MATH_MATHLIMITS_H__
diff --git a/src/google/protobuf/stubs/mutex.h b/src/google/protobuf/stubs/mutex.h
index b9b7d2e1..8c997363 100644
--- a/src/google/protobuf/stubs/mutex.h
+++ b/src/google/protobuf/stubs/mutex.h
@@ -34,6 +34,20 @@
#include <google/protobuf/stubs/macros.h>
+// Define thread-safety annotations for use below, if we are building with
+// Clang.
+#if defined(__clang__) && !defined(SWIG)
+#define GOOGLE_PROTOBUF_ACQUIRE(...) \
+ __attribute__((acquire_capability(__VA_ARGS__)))
+#define GOOGLE_PROTOBUF_RELEASE(...) \
+ __attribute__((release_capability(__VA_ARGS__)))
+#else
+#define GOOGLE_PROTOBUF_ACQUIRE(...)
+#define GOOGLE_PROTOBUF_RELEASE(...)
+#endif
+
+#include <google/protobuf/port_def.inc>
+
// ===================================================================
// emulates google3/base/mutex.h
namespace google {
@@ -45,11 +59,11 @@ namespace internal {
// Mutex is a natural type to wrap. As both google and other organization have
// specialized mutexes. gRPC also provides an injection mechanism for custom
// mutexes.
-class LIBPROTOBUF_EXPORT WrappedMutex {
+class PROTOBUF_EXPORT WrappedMutex {
public:
WrappedMutex() = default;
- void Lock() { mu_.lock(); }
- void Unlock() { mu_.unlock(); }
+ void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); }
+ void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); }
// Crash if this Mutex is not held exclusively by this thread.
// May fail to crash when it should; will never crash when it should not.
void AssertHeld() const {}
@@ -61,7 +75,7 @@ class LIBPROTOBUF_EXPORT WrappedMutex {
using Mutex = WrappedMutex;
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
-class LIBPROTOBUF_EXPORT MutexLock {
+class PROTOBUF_EXPORT MutexLock {
public:
explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); }
~MutexLock() { this->mu_->Unlock(); }
@@ -74,12 +88,12 @@ class LIBPROTOBUF_EXPORT MutexLock {
typedef MutexLock ReaderMutexLock;
typedef MutexLock WriterMutexLock;
-// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL.
-class LIBPROTOBUF_EXPORT MutexLockMaybe {
+// MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr.
+class PROTOBUF_EXPORT MutexLockMaybe {
public:
explicit MutexLockMaybe(Mutex *mu) :
- mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } }
- ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } }
+ mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } }
+ ~MutexLockMaybe() { if (this->mu_ != nullptr) { this->mu_->Unlock(); } }
private:
Mutex *const mu_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
@@ -97,7 +111,7 @@ class ThreadLocalStorage {
}
T* Get() {
T* result = static_cast<T*>(pthread_getspecific(key_));
- if (result == NULL) {
+ if (result == nullptr) {
result = new T();
pthread_setspecific(key_, result);
}
@@ -123,8 +137,12 @@ using internal::ReaderMutexLock;
using internal::WriterMutexLock;
using internal::MutexLockMaybe;
-
} // namespace protobuf
} // namespace google
+#undef GOOGLE_PROTOBUF_ACQUIRE
+#undef GOOGLE_PROTOBUF_RELEASE
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_
diff --git a/src/google/protobuf/stubs/platform_macros.h b/src/google/protobuf/stubs/platform_macros.h
index c3a64dd2..ce1b1e36 100644
--- a/src/google/protobuf/stubs/platform_macros.h
+++ b/src/google/protobuf/stubs/platform_macros.h
@@ -56,7 +56,7 @@
#elif defined(__aarch64__)
#define GOOGLE_PROTOBUF_ARCH_AARCH64 1
#define GOOGLE_PROTOBUF_ARCH_64_BIT 1
-#elif defined(__MIPSEL__)
+#elif defined(__mips__)
#if defined(__LP64__)
#define GOOGLE_PROTOBUF_ARCH_MIPS64 1
#define GOOGLE_PROTOBUF_ARCH_64_BIT 1
@@ -99,6 +99,7 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR
#if defined(__APPLE__)
#define GOOGLE_PROTOBUF_OS_APPLE
+#include <Availability.h>
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
#define GOOGLE_PROTOBUF_OS_IPHONE
@@ -125,4 +126,9 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR
#define GOOGLE_PROTOBUF_NO_THREADLOCAL
#endif
+#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 1070
+// __thread keyword requires at least 10.7
+#define GOOGLE_PROTOBUF_NO_THREADLOCAL
+#endif
+
#endif // GOOGLE_PROTOBUF_PLATFORM_MACROS_H_
diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h
index 6b52305f..4884a277 100644
--- a/src/google/protobuf/stubs/port.h
+++ b/src/google/protobuf/stubs/port.h
@@ -46,6 +46,8 @@
#include <google/protobuf/stubs/platform_macros.h>
+#include <google/protobuf/port_def.inc>
+
#undef PROTOBUF_LITTLE_ENDIAN
#ifdef _WIN32
// Assuming windows is always little-endian.
@@ -72,6 +74,19 @@
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#endif
+
+// These #includes are for the byte swap functions declared later on.
+#ifdef _MSC_VER
+#include <stdlib.h> // NOLINT(build/include)
+#include <intrin.h>
+#elif defined(__APPLE__)
+#include <libkern/OSByteOrder.h>
+#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__)
+#include <byteswap.h> // IWYU pragma: export
+#endif
+
+// Legacy: some users reference these (internal-only) macros even though we
+// don't need them any more.
#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS)
#ifdef LIBPROTOBUF_EXPORTS
#define LIBPROTOBUF_EXPORT __declspec(dllexport)
@@ -88,17 +103,8 @@
#define LIBPROTOC_EXPORT
#endif
-// These #includes are for the byte swap functions declared later on.
-#ifdef _MSC_VER
-#include <stdlib.h> // NOLINT(build/include)
-#include <intrin.h>
-#elif defined(__APPLE__)
-#include <libkern/OSByteOrder.h>
-#elif defined(__GLIBC__) || defined(__BIONIC__) || defined(__CYGWIN__)
-#include <byteswap.h> // IWYU pragma: export
-#endif
-
#define PROTOBUF_RUNTIME_DEPRECATED(message)
+#define GOOGLE_PROTOBUF_RUNTIME_DEPRECATED(message)
// ===================================================================
// from google3/base/port.h
@@ -150,128 +156,12 @@ typedef uint32_t uint32;
typedef uint64_t uint64;
#endif
-// long long macros to be used because gcc and vc++ use different suffixes,
-// and different size specifiers in format strings
-#undef GOOGLE_LONGLONG
-#undef GOOGLE_ULONGLONG
-#undef GOOGLE_LL_FORMAT
-
-#ifdef _MSC_VER
-#define GOOGLE_LONGLONG(x) x##I64
-#define GOOGLE_ULONGLONG(x) x##UI64
-#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...)
-#else
-// By long long, we actually mean int64.
-#define GOOGLE_LONGLONG(x) x##LL
-#define GOOGLE_ULONGLONG(x) x##ULL
-// Used to format real long long integers.
-#define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also.
-#endif
-
static const int32 kint32max = 0x7FFFFFFF;
static const int32 kint32min = -kint32max - 1;
-static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF);
+static const int64 kint64max = PROTOBUF_LONGLONG(0x7FFFFFFFFFFFFFFF);
static const int64 kint64min = -kint64max - 1;
static const uint32 kuint32max = 0xFFFFFFFFu;
-static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF);
-
-// -------------------------------------------------------------------
-// Annotations: Some parts of the code have been annotated in ways that might
-// be useful to some compilers or tools, but are not supported universally.
-// You can #define these annotations yourself if the default implementation
-// is not right for you.
-
-#ifndef GOOGLE_ATTRIBUTE_ALWAYS_INLINE
-#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
-// For functions we want to force inline.
-// Introduced in gcc 3.1.
-#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline))
-#else
-// Other compilers will have to figure it out for themselves.
-#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE
-#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.
-// Introduced in gcc 3.1.
-#define GOOGLE_ATTRIBUTE_NOINLINE __attribute__ ((noinline))
-#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
-// Seems to have been around since at least Visual Studio 2005
-#define GOOGLE_ATTRIBUTE_NOINLINE __declspec(noinline)
-#else
-// Other compilers will have to figure it out for themselves.
-#define GOOGLE_ATTRIBUTE_NOINLINE
-#endif
-#endif
-
-#define GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE GOOGLE_ATTRIBUTE_NOINLINE
-
-#ifndef GOOGLE_ATTRIBUTE_FUNC_ALIGN
-#if defined(__clang__) || \
- defined(__GNUC__) && (__GNUC__ > 4 ||(__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
-// Function alignment attribute introduced in gcc 4.3
-#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__ ((aligned(bytes)))
-#else
-#define GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes)
-#endif
-#endif
-
-#define GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(bytes) \
- GOOGLE_ATTRIBUTE_FUNC_ALIGN(bytes)
-
-#ifndef GOOGLE_PREDICT_TRUE
-#ifdef __GNUC__
-// Provided at least since GCC 3.0.
-#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
-#else
-#define GOOGLE_PREDICT_TRUE(x) (x)
-#endif
-#endif
-
-#ifndef GOOGLE_PREDICT_FALSE
-#ifdef __GNUC__
-// Provided at least since GCC 3.0.
-#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0))
-#else
-#define GOOGLE_PREDICT_FALSE(x) (x)
-#endif
-#endif
-
-#ifndef GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL
-#ifdef __GNUC__
-#define GOOGLE_PROTOBUF_ATTRIBUTE_RETURNS_NONNULL \
- __attribute__((returns_nonnull))
-#endif
-#endif
-
-// Delimits a block of code which may write to memory which is simultaneously
-// written by other threads, but which has been determined to be thread-safe
-// (e.g. because it is an idempotent write).
-#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN
-#define GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN()
-#endif
-#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_END
-#define GOOGLE_SAFE_CONCURRENT_WRITES_END()
-#endif
-
-#define GOOGLE_GUARDED_BY(x)
-#define GOOGLE_ATTRIBUTE_COLD
-
-#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
+static const uint64 kuint64max = PROTOBUF_ULONGLONG(0xFFFFFFFFFFFFFFFF);
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) ||\
defined(MEMORY_SANITIZER)
@@ -382,10 +272,14 @@ inline void GOOGLE_UNALIGNED_STORE64(void *p, uint64 v) {
#elif !defined(__GLIBC__) && !defined(__BIONIC__) && !defined(__CYGWIN__)
+#ifndef bswap_16
static inline uint16 bswap_16(uint16 x) {
return static_cast<uint16>(((x & 0xFF) << 8) | ((x & 0xFF00) >> 8));
}
#define bswap_16(x) bswap_16(x)
+#endif
+
+#ifndef bswap_32
static inline uint32 bswap_32(uint32 x) {
return (((x & 0xFF) << 24) |
((x & 0xFF00) << 8) |
@@ -393,17 +287,21 @@ static inline uint32 bswap_32(uint32 x) {
((x & 0xFF000000) >> 24));
}
#define bswap_32(x) bswap_32(x)
+#endif
+
+#ifndef bswap_64
static inline uint64 bswap_64(uint64 x) {
- return (((x & GOOGLE_ULONGLONG(0xFF)) << 56) |
- ((x & GOOGLE_ULONGLONG(0xFF00)) << 40) |
- ((x & GOOGLE_ULONGLONG(0xFF0000)) << 24) |
- ((x & GOOGLE_ULONGLONG(0xFF000000)) << 8) |
- ((x & GOOGLE_ULONGLONG(0xFF00000000)) >> 8) |
- ((x & GOOGLE_ULONGLONG(0xFF0000000000)) >> 24) |
- ((x & GOOGLE_ULONGLONG(0xFF000000000000)) >> 40) |
- ((x & GOOGLE_ULONGLONG(0xFF00000000000000)) >> 56));
+ return (((x & PROTOBUF_ULONGLONG(0xFF)) << 56) |
+ ((x & PROTOBUF_ULONGLONG(0xFF00)) << 40) |
+ ((x & PROTOBUF_ULONGLONG(0xFF0000)) << 24) |
+ ((x & PROTOBUF_ULONGLONG(0xFF000000)) << 8) |
+ ((x & PROTOBUF_ULONGLONG(0xFF00000000)) >> 8) |
+ ((x & PROTOBUF_ULONGLONG(0xFF0000000000)) >> 24) |
+ ((x & PROTOBUF_ULONGLONG(0xFF000000000000)) >> 40) |
+ ((x & PROTOBUF_ULONGLONG(0xFF00000000000000)) >> 56));
}
#define bswap_64(x) bswap_64(x)
+#endif
#endif
@@ -472,7 +370,7 @@ class Bits {
// ===================================================================
// from google3/util/endian/endian.h
-LIBPROTOBUF_EXPORT uint32 ghtonl(uint32 x);
+PROTOBUF_EXPORT uint32 ghtonl(uint32 x);
class BigEndian {
public:
@@ -530,13 +428,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
+#define GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER 0
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_PORT_H_
diff --git a/src/google/protobuf/stubs/singleton.h b/src/google/protobuf/stubs/singleton.h
index 2e6ccbdb..5f0f4610 100644
--- a/src/google/protobuf/stubs/singleton.h
+++ b/src/google/protobuf/stubs/singleton.h
@@ -45,7 +45,7 @@ class Singleton {
}
static void ShutDown() {
delete instance_;
- instance_ = NULL;
+ instance_ = nullptr;
}
private:
static void Init() {
@@ -59,7 +59,7 @@ template<typename T>
ProtobufOnceType Singleton<T>::once_;
template<typename T>
-T* Singleton<T>::instance_ = NULL;
+T* Singleton<T>::instance_ = nullptr;
} // namespace internal
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/status.h b/src/google/protobuf/stubs/status.h
index c5d38f0b..008416ef 100644
--- a/src/google/protobuf/stubs/status.h
+++ b/src/google/protobuf/stubs/status.h
@@ -36,6 +36,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -62,7 +64,7 @@ enum Code {
};
} // namespace error
-class LIBPROTOBUF_EXPORT Status {
+class PROTOBUF_EXPORT Status {
public:
// Creates a "successful" status.
Status();
@@ -106,11 +108,14 @@ class LIBPROTOBUF_EXPORT Status {
};
// Prints a human-readable representation of 'x' to 'os'.
-LIBPROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x);
+PROTOBUF_EXPORT std::ostream& operator<<(std::ostream& os, const Status& x);
#define EXPECT_OK(value) EXPECT_TRUE((value).ok())
} // namespace util
} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_STATUS_H_
diff --git a/src/google/protobuf/stubs/status_macros.h b/src/google/protobuf/stubs/status_macros.h
index 743e79a7..b3af0dcd 100644
--- a/src/google/protobuf/stubs/status_macros.h
+++ b/src/google/protobuf/stubs/status_macros.h
@@ -46,11 +46,11 @@ namespace util {
//
// Example:
// RETURN_IF_ERROR(DoThings(4));
-#define RETURN_IF_ERROR(expr) \
- do { \
+#define RETURN_IF_ERROR(expr) \
+ do { \
/* Using _status below to avoid capture problems if expr is "status". */ \
- const ::google::protobuf::util::Status _status = (expr); \
- if (GOOGLE_PREDICT_FALSE(!_status.ok())) return _status; \
+ const ::google::protobuf::util::Status _status = (expr); \
+ if (PROTOBUF_PREDICT_FALSE(!_status.ok())) return _status; \
} while (0)
// Internal helper for concatenating macro values.
@@ -67,7 +67,7 @@ Status DoAssignOrReturn(T& lhs, StatusOr<T> result) {
#define ASSIGN_OR_RETURN_IMPL(status, lhs, rexpr) \
Status status = DoAssignOrReturn(lhs, (rexpr)); \
- if (GOOGLE_PREDICT_FALSE(!status.ok())) return status;
+ if (PROTOBUF_PREDICT_FALSE(!status.ok())) return status;
// Executes an expression that returns a util::StatusOr, extracting its value
// into the variable defined by lhs (or returning on error).
diff --git a/src/google/protobuf/stubs/statusor.h b/src/google/protobuf/stubs/statusor.h
index 29f869ad..90fd5f0d 100644
--- a/src/google/protobuf/stubs/statusor.h
+++ b/src/google/protobuf/stubs/statusor.h
@@ -33,7 +33,7 @@
// usable value, or an error Status explaining why such a value is
// not present. To this end, StatusOr<T> does not allow its Status
// value to be Status::OK. Further, StatusOr<T*> does not allow the
-// contained pointer to be NULL.
+// contained pointer to be nullptr.
//
// The primary use-case for StatusOr<T> is as the return value of a
// function which may fail.
@@ -89,6 +89,8 @@
#include <google/protobuf/stubs/status.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -114,15 +116,15 @@ class StatusOr {
StatusOr(const Status& status); // NOLINT
// Construct a new StatusOr with the given value. If T is a plain pointer,
- // value must not be NULL. After calling this constructor, calls to
+ // value must not be nullptr. After calling this constructor, calls to
// ValueOrDie() will succeed, and calls to status() will return OK.
//
// NOTE: Not explicit - we want to use StatusOr<T> as a return type
// so it is convenient and sensible to be able to do 'return T()'
// when when the return type is StatusOr<T>.
//
- // REQUIRES: if T is a plain pointer, value != NULL. This requirement is
- // DCHECKed. In optimized builds, passing a NULL pointer here will have
+ // REQUIRES: if T is a plain pointer, value != nullptr. This requirement is
+ // DCHECKed. In optimized builds, passing a null pointer here will have
// the effect of passing PosixErrorSpace::EINVAL as a fallback.
StatusOr(const T& value); // NOLINT
@@ -162,7 +164,7 @@ class StatusOr {
namespace internal {
-class LIBPROTOBUF_EXPORT StatusOrHelper {
+class PROTOBUF_EXPORT StatusOrHelper {
public:
// Move type-agnostic error handling to the .cc.
static void Crash(const util::Status& status);
@@ -174,13 +176,13 @@ class LIBPROTOBUF_EXPORT StatusOrHelper {
template<typename T>
struct StatusOrHelper::Specialize {
- // For non-pointer T, a reference can never be NULL.
+ // For non-pointer T, a reference can never be nullptr.
static inline bool IsValueNull(const T& t) { return false; }
};
template<typename T>
struct StatusOrHelper::Specialize<T*> {
- static inline bool IsValueNull(const T* t) { return t == NULL; }
+ static inline bool IsValueNull(const T* t) { return t == nullptr; }
};
} // namespace internal
@@ -202,7 +204,7 @@ inline StatusOr<T>::StatusOr(const Status& status) {
template<typename T>
inline StatusOr<T>::StatusOr(const T& value) {
if (internal::StatusOrHelper::Specialize<T>::IsValueNull(value)) {
- status_ = Status(error::INTERNAL, "NULL is not a vaild argument.");
+ status_ = Status(error::INTERNAL, "nullptr is not a vaild argument.");
} else {
status_ = Status::OK;
value_ = value;
@@ -256,4 +258,6 @@ inline const T& StatusOr<T>::ValueOrDie() const {
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_STATUSOR_H_
diff --git a/src/google/protobuf/stubs/stl_util.h b/src/google/protobuf/stubs/stl_util.h
index 9e4c82a4..2c265e92 100644
--- a/src/google/protobuf/stubs/stl_util.h
+++ b/src/google/protobuf/stubs/stl_util.h
@@ -82,7 +82,7 @@ inline void STLStringResizeUninitialized(string* s, size_t new_size) {
// already work on all current implementations.
inline char* string_as_array(string* str) {
// DO NOT USE const_cast<char*>(str->data())! See the unittest for why.
- return str->empty() ? NULL : &*str->begin();
+ return str->empty() ? nullptr : &*str->begin();
}
// STLDeleteElements() deletes all the elements in an STL container and clears
@@ -90,7 +90,7 @@ inline char* string_as_array(string* str) {
// hash_set, or any other STL container which defines sensible begin(), end(),
// and clear() methods.
//
-// If container is NULL, this function is a no-op.
+// If container is nullptr, this function is a no-op.
//
// As an alternative to calling STLDeleteElements() directly, consider
// ElementDeleter (defined below), which ensures that your container's elements
@@ -104,7 +104,7 @@ void STLDeleteElements(T *container) {
// Given an STL container consisting of (key, value) pairs, STLDeleteValues
// deletes all the "value" components and clears the container. Does nothing
-// in the case it's given a NULL pointer.
+// in the case it's given a null pointer.
template <class T>
void STLDeleteValues(T *v) {
diff --git a/src/google/protobuf/stubs/stringpiece.cc b/src/google/protobuf/stubs/stringpiece.cc
index 989474b7..96a7d3da 100644
--- a/src/google/protobuf/stubs/stringpiece.cc
+++ b/src/google/protobuf/stubs/stringpiece.cc
@@ -115,7 +115,7 @@ stringpiece_ssize_type StringPiece::find(char c, size_type pos) const {
}
const char* result = static_cast<const char*>(
memchr(ptr_ + pos, c, length_ - pos));
- return result != NULL ? result - ptr_ : npos;
+ return result != nullptr ? result - ptr_ : npos;
}
stringpiece_ssize_type StringPiece::rfind(StringPiece s, size_type pos) const {
diff --git a/src/google/protobuf/stubs/stringpiece.h b/src/google/protobuf/stubs/stringpiece.h
index 563ff75d..bb5aeed9 100644
--- a/src/google/protobuf/stubs/stringpiece.h
+++ b/src/google/protobuf/stubs/stringpiece.h
@@ -76,30 +76,30 @@
//
// There are several ways to create a null StringPiece:
// StringPiece()
-// StringPiece(NULL)
-// StringPiece(NULL, 0)
-// For all of the above, sp.data() == NULL, sp.length() == 0,
+// StringPiece(nullptr)
+// StringPiece(nullptr, 0)
+// For all of the above, sp.data() == nullptr, sp.length() == 0,
// and sp.empty() == true. Also, if you create a StringPiece with
-// a non-NULL pointer then sp.data() != NULL. Once created,
-// sp.data() will stay either NULL or not-NULL, except if you call
+// a non-null pointer then sp.data() != nullptr. Once created,
+// sp.data() will stay either nullptr or not-nullptr, except if you call
// sp.clear() or sp.set().
//
-// Thus, you can use StringPiece(NULL) to signal an out-of-band value
+// Thus, you can use StringPiece(nullptr) to signal an out-of-band value
// that is different from other StringPiece values. This is similar
-// to the way that const char* p1 = NULL; is different from
+// to the way that const char* p1 = nullptr; is different from
// const char* p2 = "";.
//
// There are many ways to create an empty StringPiece:
// StringPiece()
-// StringPiece(NULL)
-// StringPiece(NULL, 0)
+// StringPiece(nullptr)
+// StringPiece(nullptr, 0)
// StringPiece("")
// StringPiece("", 0)
// StringPiece("abcdef", 0)
// StringPiece("abcdef"+6, 0)
// For all of the above, sp.length() will be 0 and sp.empty() will be true.
-// For some empty StringPiece values, sp.data() will be NULL.
-// For some empty StringPiece values, sp.data() will not be NULL.
+// For some empty StringPiece values, sp.data() will be nullptr.
+// For some empty StringPiece values, sp.data() will not be nullptr.
//
// Be careful not to confuse: null StringPiece and empty StringPiece.
// The set of empty StringPieces properly includes the set of null StringPieces.
@@ -109,20 +109,20 @@
// All empty StringPiece values compare equal to each other.
// Even a null StringPieces compares equal to a non-null empty StringPiece:
// StringPiece() == StringPiece("", 0)
-// StringPiece(NULL) == StringPiece("abc", 0)
-// StringPiece(NULL, 0) == StringPiece("abcdef"+6, 0)
+// StringPiece(nullptr) == StringPiece("abc", 0)
+// StringPiece(nullptr, 0) == StringPiece("abcdef"+6, 0)
//
// Look carefully at this example:
-// StringPiece("") == NULL
+// StringPiece("") == nullptr
// True or false? TRUE, because StringPiece::operator== converts
-// the right-hand side from NULL to StringPiece(NULL),
+// the right-hand side from nullptr to StringPiece(nullptr),
// and then compares two zero-length spans of characters.
// However, we are working to make this example produce a compile error.
//
// Suppose you want to write:
-// bool TestWhat?(StringPiece sp) { return sp == NULL; } // BAD
+// bool TestWhat?(StringPiece sp) { return sp == nullptr; } // BAD
// Do not do that. Write one of these instead:
-// bool TestNull(StringPiece sp) { return sp.data() == NULL; }
+// bool TestNull(StringPiece sp) { return sp.data() == nullptr; }
// bool TestEmpty(StringPiece sp) { return sp.empty(); }
// The intent of TestWhat? is unclear. Did you mean TestNull or TestEmpty?
// Right now, TestWhat? behaves likes TestEmpty.
@@ -151,6 +151,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/hash.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
// StringPiece has *two* size types.
@@ -175,7 +177,7 @@ typedef string::difference_type stringpiece_ssize_type;
#define STRINGPIECE_CHECK_SIZE 0
#endif
-class LIBPROTOBUF_EXPORT StringPiece {
+class PROTOBUF_EXPORT StringPiece {
private:
const char* ptr_;
stringpiece_ssize_type length_;
@@ -207,11 +209,11 @@ class LIBPROTOBUF_EXPORT StringPiece {
//
// Style guide exception granted:
// http://goto/style-guide-exception-20978288
- StringPiece() : ptr_(NULL), length_(0) {}
+ StringPiece() : ptr_(nullptr), length_(0) {}
StringPiece(const char* str) // NOLINT(runtime/explicit)
: ptr_(str), length_(0) {
- if (str != NULL) {
+ if (str != nullptr) {
length_ = CheckedSsizeTFromSizeT(strlen(str));
}
}
@@ -248,7 +250,7 @@ class LIBPROTOBUF_EXPORT StringPiece {
bool empty() const { return length_ == 0; }
void clear() {
- ptr_ = NULL;
+ ptr_ = nullptr;
length_ = 0;
}
@@ -260,7 +262,7 @@ class LIBPROTOBUF_EXPORT StringPiece {
void set(const char* str) {
ptr_ = str;
- if (str != NULL)
+ if (str != nullptr)
length_ = CheckedSsizeTFromSizeT(strlen(str));
else
length_ = 0;
@@ -309,7 +311,7 @@ class LIBPROTOBUF_EXPORT StringPiece {
// for a StringPiece be called "as_string()". We also leave the
// "as_string()" method defined here for existing code.
string ToString() const {
- if (ptr_ == NULL) return string();
+ if (ptr_ == nullptr) return string();
return string(data(), static_cast<size_type>(size()));
}
@@ -463,6 +465,9 @@ struct StringPiecePod {
std::string ToString() const {
return std::string(data_, static_cast<size_t>(size_));
}
+
+ operator string() const { return ToString(); }
+
private:
const char* data_;
stringpiece_ssize_type size_;
@@ -484,4 +489,6 @@ template<> struct hash<StringPiece> {
};
GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END
+#include <google/protobuf/port_undef.inc>
+
#endif // STRINGS_STRINGPIECE_H_
diff --git a/src/google/protobuf/stubs/stringpiece_unittest.cc b/src/google/protobuf/stubs/stringpiece_unittest.cc
index a6a87595..d9a32d03 100644
--- a/src/google/protobuf/stubs/stringpiece_unittest.cc
+++ b/src/google/protobuf/stubs/stringpiece_unittest.cc
@@ -46,7 +46,7 @@ TEST(StringPiece, Ctor) {
{
// Null.
StringPiece s10;
- EXPECT_TRUE(s10.data() == NULL);
+ EXPECT_TRUE(s10.data() == nullptr);
EXPECT_EQ(0, s10.length());
}
@@ -148,8 +148,8 @@ TEST(StringPiece, ComparisonOperators) {
EXPECT_EQ(result, StringPiece((x)).compare(StringPiece((y))) op 0)
COMPARE(true, ==, "", "");
- COMPARE(true, ==, "", NULL);
- COMPARE(true, ==, NULL, "");
+ COMPARE(true, ==, "", nullptr);
+ COMPARE(true, ==, nullptr, "");
COMPARE(true, ==, "a", "a");
COMPARE(true, ==, "aa", "aa");
COMPARE(false, ==, "a", "");
@@ -253,7 +253,7 @@ TEST(StringPiece, STL1) {
EXPECT_EQ(*d.data(), 'f');
EXPECT_EQ(d.data()[5], 'r');
- EXPECT_TRUE(e.data() == NULL);
+ EXPECT_TRUE(e.data() == nullptr);
EXPECT_EQ(*a.begin(), 'a');
EXPECT_EQ(*(b.begin() + 2), 'c');
@@ -312,7 +312,7 @@ TEST(StringPiece, STL2) {
d.clear();
EXPECT_EQ(d.size(), 0);
EXPECT_TRUE(d.empty());
- EXPECT_TRUE(d.data() == NULL);
+ EXPECT_TRUE(d.data() == nullptr);
EXPECT_TRUE(d.begin() == d.end());
EXPECT_EQ(StringPiece::npos, string::npos);
@@ -707,17 +707,17 @@ TEST(StringPiece, Contains) {
EXPECT_TRUE(!a.contains(d));
}
-TEST(StringPiece, NULLInput) {
+TEST(StringPiece, NullInput) {
// we used to crash here, but now we don't.
- StringPiece s(NULL);
- EXPECT_EQ(s.data(), (const char*)NULL);
+ StringPiece s(nullptr);
+ EXPECT_EQ(s.data(), (const char*)nullptr);
EXPECT_EQ(s.size(), 0);
- s.set(NULL);
- EXPECT_EQ(s.data(), (const char*)NULL);
+ s.set(nullptr);
+ EXPECT_EQ(s.data(), (const char*)nullptr);
EXPECT_EQ(s.size(), 0);
- // .ToString() on a StringPiece with NULL should produce the empty string.
+ // .ToString() on a StringPiece with nullptr should produce the empty string.
EXPECT_EQ("", s.ToString());
EXPECT_EQ("", s.as_string());
}
diff --git a/src/google/protobuf/stubs/stringprintf.cc b/src/google/protobuf/stubs/stringprintf.cc
index d98b9b87..820bfe7f 100644
--- a/src/google/protobuf/stubs/stringprintf.cc
+++ b/src/google/protobuf/stubs/stringprintf.cc
@@ -76,7 +76,7 @@ void StringAppendV(string* dst, const char* format, va_list ap) {
// Error or MSVC running out of space. MSVC 8.0 and higher
// can be asked about space needed with the special idiom below:
va_copy(backup_ap, ap);
- result = vsnprintf(NULL, 0, format, backup_ap);
+ result = vsnprintf(nullptr, 0, format, backup_ap);
va_end(backup_ap);
}
diff --git a/src/google/protobuf/stubs/stringprintf.h b/src/google/protobuf/stubs/stringprintf.h
index 7183ec6a..253d736a 100644
--- a/src/google/protobuf/stubs/stringprintf.h
+++ b/src/google/protobuf/stubs/stringprintf.h
@@ -46,31 +46,38 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
// Return a C++ string
-LIBPROTOBUF_EXPORT extern string StringPrintf(const char* format, ...);
+PROTOBUF_EXPORT extern string StringPrintf(const char* format, ...);
// Store result into a supplied string and return it
-LIBPROTOBUF_EXPORT extern const string& SStringPrintf(string* dst, const char* format, ...);
+PROTOBUF_EXPORT extern const string& SStringPrintf(string* dst,
+ const char* format, ...);
// Append result to a supplied string
-LIBPROTOBUF_EXPORT extern void StringAppendF(string* dst, const char* format, ...);
+PROTOBUF_EXPORT extern void StringAppendF(string* dst, const char* format, ...);
// Lower-level routine that takes a va_list and appends to a specified
// string. All other routines are just convenience wrappers around it.
-LIBPROTOBUF_EXPORT extern void StringAppendV(string* dst, const char* format, va_list ap);
+PROTOBUF_EXPORT extern void StringAppendV(string* dst, const char* format,
+ va_list ap);
// The max arguments supported by StringPrintfVector
-LIBPROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs;
+PROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs;
// You can use this version when all your arguments are strings, but
// you don't know how many arguments you'll have at compile time.
// StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs
-LIBPROTOBUF_EXPORT extern string StringPrintfVector(const char* format, const std::vector<string>& v);
+PROTOBUF_EXPORT extern string StringPrintfVector(const char* format,
+ const std::vector<string>& v);
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H
diff --git a/src/google/protobuf/stubs/stringprintf_unittest.cc b/src/google/protobuf/stubs/stringprintf_unittest.cc
index 15895e59..7fcbf500 100644
--- a/src/google/protobuf/stubs/stringprintf_unittest.cc
+++ b/src/google/protobuf/stubs/stringprintf_unittest.cc
@@ -91,7 +91,7 @@ TEST(StringPrintfTest, Multibyte) {
// out of memory while trying to determine destination buffer size.
// see b/4194543.
- char* old_locale = setlocale(LC_CTYPE, NULL);
+ char* old_locale = setlocale(LC_CTYPE, nullptr);
// Push locale with multibyte mode
setlocale(LC_CTYPE, "en_US.utf8");
@@ -120,7 +120,7 @@ TEST(StringPrintfTest, Multibyte) {
TEST(StringPrintfTest, NoMultibyte) {
// No multibyte handling, but the string contains funny chars.
- char* old_locale = setlocale(LC_CTYPE, NULL);
+ char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "POSIX");
string value = StringPrintf("%.*s", 3, "\375\067s");
setlocale(LC_CTYPE, old_locale);
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 552d416f..5bf9f2e6 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -31,14 +31,14 @@
// from google3/strings/strutil.cc
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/stubs/mathlimits.h>
#include <errno.h>
#include <float.h> // FLT_DIG and DBL_DIG
-#include <limits>
#include <limits.h>
#include <stdio.h>
+#include <cmath>
#include <iterator>
+#include <limits>
#include <google/protobuf/stubs/stl_util.h>
@@ -87,7 +87,7 @@ void StripString(string* s, const char* remove, char replacewith) {
const char * str_start = s->c_str();
const char * str = str_start;
for (str = strpbrk(str, remove);
- str != NULL;
+ str != nullptr;
str = strpbrk(str + 1, remove)) {
(*s)[str - str_start] = replacewith;
}
@@ -102,7 +102,7 @@ void ReplaceCharacters(string *s, const char *remove, char replacewith) {
const char *str_start = s->c_str();
const char *str = str_start;
for (str = strpbrk(str, remove);
- str != NULL;
+ str != nullptr;
str = strpbrk(str + 1, remove)) {
(*s)[str - str_start] = replacewith;
}
@@ -280,7 +280,7 @@ static void JoinStringsIterator(const ITERATOR& start,
const ITERATOR& end,
const char* delim,
string* result) {
- GOOGLE_CHECK(result != NULL);
+ GOOGLE_CHECK(result != nullptr);
result->clear();
int delim_length = strlen(delim);
@@ -318,7 +318,7 @@ void JoinStrings(const std::vector<string>& components,
// result is truncated to 8 bits.
//
// The second call stores its errors in a supplied string vector.
-// If the string vector pointer is NULL, it reports the errors with LOG().
+// If the string vector pointer is nullptr, it reports the errors with LOG().
// ----------------------------------------------------------------------
#define IS_OCTAL_DIGIT(c) (((c) >= '0') && ((c) <= '7'))
@@ -328,12 +328,12 @@ void JoinStrings(const std::vector<string>& components,
#define LOG_STRING(LEVEL, VECTOR) GOOGLE_LOG_IF(LEVEL, false)
int UnescapeCEscapeSequences(const char* source, char* dest) {
- return UnescapeCEscapeSequences(source, dest, NULL);
+ return UnescapeCEscapeSequences(source, dest, nullptr);
}
int UnescapeCEscapeSequences(const char* source, char* dest,
std::vector<string> *errors) {
- GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented.";
+ GOOGLE_DCHECK(errors == nullptr) << "Error reporting not implemented.";
char* d = dest;
const char* p = source;
@@ -458,13 +458,13 @@ int UnescapeCEscapeSequences(const char* source, char* dest,
// to be the same.
//
// The second call stores its errors in a supplied string vector.
-// If the string vector pointer is NULL, it reports the errors with LOG().
+// If the string vector pointer is nullptr, it reports the errors with LOG().
//
// In the first and second calls, the length of dest is returned. In the
// the third call, the new string is returned.
// ----------------------------------------------------------------------
int UnescapeCEscapeString(const string& src, string* dest) {
- return UnescapeCEscapeString(src, dest, NULL);
+ return UnescapeCEscapeString(src, dest, nullptr);
}
int UnescapeCEscapeString(const string& src, string* dest,
@@ -478,7 +478,7 @@ int UnescapeCEscapeString(const string& src, string* dest,
string UnescapeCEscapeString(const string& src) {
std::unique_ptr<char[]> unescaped(new char[src.size() + 1]);
- int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL);
+ int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), nullptr);
return string(unescaped.get(), len);
}
@@ -982,7 +982,7 @@ static const char two_ASCII_digits[100][2] = {
char* FastUInt32ToBufferLeft(uint32 u, char* buffer) {
uint32 digits;
- const char *ASCII_digits = NULL;
+ const char *ASCII_digits = nullptr;
// The idea of this implementation is to trim the number of divides to as few
// as possible by using multiplication and subtraction rather than mod (%),
// and by outputting two digits at a time rather than one.
@@ -1073,7 +1073,7 @@ char* FastInt32ToBufferLeft(int32 i, char* buffer) {
char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) {
int digits;
- const char *ASCII_digits = NULL;
+ const char *ASCII_digits = nullptr;
uint32 u = static_cast<uint32>(u64);
if (u == u64) return FastUInt32ToBufferLeft(u, buffer);
@@ -1231,7 +1231,7 @@ static inline bool IsValidFloatChar(char c) {
void DelocalizeRadix(char* buffer) {
// Fast check: if the buffer has a normal decimal point, assume no
// translation is needed.
- if (strchr(buffer, '.') != NULL) return;
+ if (strchr(buffer, '.') != nullptr) return;
// Find the first unknown character.
while (IsValidFloatChar(*buffer)) ++buffer;
@@ -1268,7 +1268,7 @@ char* DoubleToBuffer(double value, char* buffer) {
} else if (value == -std::numeric_limits<double>::infinity()) {
strcpy(buffer, "-inf");
return buffer;
- } else if (MathLimits<double>::IsNaN(value)) {
+ } else if (std::isnan(value)) {
strcpy(buffer, "nan");
return buffer;
}
@@ -1286,7 +1286,7 @@ char* DoubleToBuffer(double value, char* buffer) {
// of a double. This long double may have extra bits that make it compare
// unequal to "value" even though it would be exactly equal if it were
// truncated to a double.
- volatile double parsed_value = strtod(buffer, NULL);
+ volatile double parsed_value = strtod(buffer, nullptr);
if (parsed_value != value) {
int snprintf_result =
snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value);
@@ -1318,7 +1318,7 @@ inline bool CaseEqual(StringPiece s1, StringPiece s2) {
}
bool safe_strtob(StringPiece str, bool* value) {
- GOOGLE_CHECK(value != NULL) << "NULL output boolean given.";
+ GOOGLE_CHECK(value != nullptr) << "nullptr output boolean given.";
if (CaseEqual(str, "true") || CaseEqual(str, "t") ||
CaseEqual(str, "yes") || CaseEqual(str, "y") ||
CaseEqual(str, "1")) {
@@ -1386,7 +1386,7 @@ char* FloatToBuffer(float value, char* buffer) {
} else if (value == -std::numeric_limits<double>::infinity()) {
strcpy(buffer, "-inf");
return buffer;
- } else if (MathLimits<float>::IsNaN(value)) {
+ } else if (std::isnan(value)) {
strcpy(buffer, "nan");
return buffer;
}
@@ -1619,7 +1619,7 @@ void StrAppend(string *result,
int GlobalReplaceSubstring(const string& substring,
const string& replacement,
string* s) {
- GOOGLE_CHECK(s != NULL);
+ GOOGLE_CHECK(s != nullptr);
if (s->empty() || substring.empty())
return 0;
string tmp;
@@ -1969,7 +1969,7 @@ int Base64UnescapeInternal(const char *src_param, int szsrc,
// for (i = 0; i < 255; i += 8) {
// for (j = i; j < i + 8; j++) {
// pos = strchr(Base64, j);
-// if ((pos == NULL) || (j == 0))
+// if ((pos == nullptr) || (j == 0))
// idx = -1;
// else
// idx = pos - Base64;
@@ -2300,5 +2300,110 @@ int UTF8FirstLetterNumBytes(const char* src, int len) {
return kUTF8LenTbl[*reinterpret_cast<const uint8*>(src)];
}
+// ----------------------------------------------------------------------
+// CleanStringLineEndings()
+// Clean up a multi-line string to conform to Unix line endings.
+// Reads from src and appends to dst, so usually dst should be empty.
+//
+// If there is no line ending at the end of a non-empty string, it can
+// be added automatically.
+//
+// Four different types of input are correctly handled:
+//
+// - Unix/Linux files: line ending is LF: pass through unchanged
+//
+// - DOS/Windows files: line ending is CRLF: convert to LF
+//
+// - Legacy Mac files: line ending is CR: convert to LF
+//
+// - Garbled files: random line endings: convert gracefully
+// lonely CR, lonely LF, CRLF: convert to LF
+//
+// @param src The multi-line string to convert
+// @param dst The converted string is appended to this string
+// @param auto_end_last_line Automatically terminate the last line
+//
+// Limitations:
+//
+// This does not do the right thing for CRCRLF files created by
+// broken programs that do another Unix->DOS conversion on files
+// that are already in CRLF format. For this, a two-pass approach
+// brute-force would be needed that
+//
+// (1) determines the presence of LF (first one is ok)
+// (2) if yes, removes any CR, else convert every CR to LF
+
+void CleanStringLineEndings(const string &src, string *dst,
+ bool auto_end_last_line) {
+ if (dst->empty()) {
+ dst->append(src);
+ CleanStringLineEndings(dst, auto_end_last_line);
+ } else {
+ string tmp = src;
+ CleanStringLineEndings(&tmp, auto_end_last_line);
+ dst->append(tmp);
+ }
+}
+
+void CleanStringLineEndings(string *str, bool auto_end_last_line) {
+ ptrdiff_t output_pos = 0;
+ bool r_seen = false;
+ ptrdiff_t len = str->size();
+
+ char *p = &(*str)[0];
+
+ for (ptrdiff_t input_pos = 0; input_pos < len;) {
+ if (!r_seen && input_pos + 8 < len) {
+ uint64_t v = GOOGLE_UNALIGNED_LOAD64(p + input_pos);
+ // Loop over groups of 8 bytes at a time until we come across
+ // a word that has a byte whose value is less than or equal to
+ // '\r' (i.e. could contain a \n (0x0a) or a \r (0x0d) ).
+ //
+ // We use a has_less macro that quickly tests a whole 64-bit
+ // word to see if any of the bytes has a value < N.
+ //
+ // For more details, see:
+ // http://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord
+#define has_less(x, n) (((x) - ~0ULL / 255 * (n)) & ~(x) & ~0ULL / 255 * 128)
+ if (!has_less(v, '\r' + 1)) {
+#undef has_less
+ // No byte in this word has a value that could be a \r or a \n
+ if (output_pos != input_pos) {
+ GOOGLE_UNALIGNED_STORE64(p + output_pos, v);
+ }
+ input_pos += 8;
+ output_pos += 8;
+ continue;
+ }
+ }
+ string::const_reference in = p[input_pos];
+ if (in == '\r') {
+ if (r_seen) p[output_pos++] = '\n';
+ r_seen = true;
+ } else if (in == '\n') {
+ if (input_pos != output_pos)
+ p[output_pos++] = '\n';
+ else
+ output_pos++;
+ r_seen = false;
+ } else {
+ if (r_seen) p[output_pos++] = '\n';
+ r_seen = false;
+ if (input_pos != output_pos)
+ p[output_pos++] = in;
+ else
+ output_pos++;
+ }
+ input_pos++;
+ }
+ if (r_seen ||
+ (auto_end_last_line && output_pos > 0 && p[output_pos - 1] != '\n')) {
+ str->resize(output_pos + 1);
+ str->operator[](output_pos) = '\n';
+ } else if (output_pos < len) {
+ str->resize(output_pos);
+ }
+}
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/stubs/strutil.h b/src/google/protobuf/stubs/strutil.h
index a839b8b3..e567ba7f 100644
--- a/src/google/protobuf/stubs/strutil.h
+++ b/src/google/protobuf/stubs/strutil.h
@@ -38,6 +38,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -155,13 +157,12 @@ inline string StripSuffixString(const string& str, const string& suffix) {
// StripWhitespace
// Removes whitespaces from both ends of the given string.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove,
- char replacewith);
-LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove,
- char replacewith);
-
-LIBPROTOBUF_EXPORT void StripWhitespace(string* s);
+PROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove,
+ char replacewith);
+PROTOBUF_EXPORT void StripString(string* s, const char* remove,
+ char replacewith);
+PROTOBUF_EXPORT void StripWhitespace(string* s);
// ----------------------------------------------------------------------
// LowerString()
@@ -203,8 +204,8 @@ inline string ToUpper(const string& s) {
// happened or not.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
- const string& newsub, bool replace_all);
+PROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
+ const string& newsub, bool replace_all);
// ----------------------------------------------------------------------
// SplitStringUsing()
@@ -212,8 +213,8 @@ LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub,
// to 'result'. If there are consecutive delimiters, this function skips
// over all of them.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
- std::vector<string>* res);
+PROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
+ std::vector<string>* res);
// Split a string using one or more byte delimiters, presented
// as a nul-terminated c string. Append the components to 'result'.
@@ -223,9 +224,9 @@ LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim,
//
// If "full" is the empty string, yields an empty string as the only value.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
- const char* delim,
- std::vector<string>* result);
+PROTOBUF_EXPORT void SplitStringAllowEmpty(const string& full,
+ const char* delim,
+ std::vector<string>* result);
// ----------------------------------------------------------------------
// Split()
@@ -250,8 +251,8 @@ inline std::vector<string> Split(
// another takes a pointer to the target string. In the latter case the
// target string is cleared and overwritten.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components,
- const char* delim, string* result);
+PROTOBUF_EXPORT void JoinStrings(const std::vector<string>& components,
+ const char* delim, string* result);
inline string JoinStrings(const std::vector<string>& components,
const char* delim) {
@@ -285,15 +286,15 @@ inline string JoinStrings(const std::vector<string>& components,
//
// Errors: In the first form of the call, errors are reported with
// LOG(ERROR). The same is true for the second form of the call if
-// the pointer to the string std::vector is NULL; otherwise, error
+// the pointer to the string std::vector is nullptr; otherwise, error
// messages are stored in the std::vector. In either case, the effect on
// the dest array is not defined, but rest of the source will be
// processed.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
-LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
- std::vector<string> *errors);
+PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest);
+PROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
+ std::vector<string>* errors);
// ----------------------------------------------------------------------
// UnescapeCEscapeString()
@@ -304,16 +305,16 @@ LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest,
// to be the same.
//
// The second call stores its errors in a supplied string vector.
-// If the string vector pointer is NULL, it reports the errors with LOG().
+// If the string vector pointer is nullptr, it reports the errors with LOG().
//
// In the first and second calls, the length of dest is returned. In the
// the third call, the new string is returned.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
-LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
- std::vector<string> *errors);
-LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
+PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest);
+PROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest,
+ std::vector<string>* errors);
+PROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
// ----------------------------------------------------------------------
// CEscape()
@@ -322,21 +323,21 @@ LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src);
//
// Escaped chars: \n, \r, \t, ", ', \, and !isprint().
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string CEscape(const string& src);
+PROTOBUF_EXPORT string CEscape(const string& src);
// ----------------------------------------------------------------------
// CEscapeAndAppend()
// Escapes 'src' using C-style escape sequences, and appends the escaped
// string to 'dest'.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest);
+PROTOBUF_EXPORT void CEscapeAndAppend(StringPiece src, string* dest);
namespace strings {
// Like CEscape() but does not escape bytes with the upper bit set.
-LIBPROTOBUF_EXPORT string Utf8SafeCEscape(const string& src);
+PROTOBUF_EXPORT string Utf8SafeCEscape(const string& src);
// Like CEscape() but uses hex (\x) escapes instead of octals.
-LIBPROTOBUF_EXPORT string CHexEscape(const string& src);
+PROTOBUF_EXPORT string CHexEscape(const string& src);
} // namespace strings
// ----------------------------------------------------------------------
@@ -349,10 +350,10 @@ LIBPROTOBUF_EXPORT string CHexEscape(const string& src);
// platforms, so using these is safer, from the point of view of
// overflow behavior, than using the standard libc functions.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int32 strto32_adaptor(const char *nptr, char **endptr,
- int base);
-LIBPROTOBUF_EXPORT uint32 strtou32_adaptor(const char *nptr, char **endptr,
- int base);
+PROTOBUF_EXPORT int32 strto32_adaptor(const char* nptr, char** endptr,
+ int base);
+PROTOBUF_EXPORT uint32 strtou32_adaptor(const char* nptr, char** endptr,
+ int base);
inline int32 strto32(const char *nptr, char **endptr, int base) {
if (sizeof(int32) == sizeof(long))
@@ -391,10 +392,10 @@ inline uint64 strtou64(const char *nptr, char **endptr, int base) {
// safe_strtof()
// safe_strtod()
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value);
+PROTOBUF_EXPORT bool safe_strtob(StringPiece str, bool* value);
-LIBPROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value);
-LIBPROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value);
+PROTOBUF_EXPORT bool safe_strto32(const string& str, int32* value);
+PROTOBUF_EXPORT bool safe_strtou32(const string& str, uint32* value);
inline bool safe_strto32(const char* str, int32* value) {
return safe_strto32(string(str), value);
}
@@ -408,8 +409,8 @@ inline bool safe_strtou32(StringPiece str, uint32* value) {
return safe_strtou32(str.ToString(), value);
}
-LIBPROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value);
-LIBPROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value);
+PROTOBUF_EXPORT bool safe_strto64(const string& str, int64* value);
+PROTOBUF_EXPORT bool safe_strtou64(const string& str, uint64* value);
inline bool safe_strto64(const char* str, int64* value) {
return safe_strto64(string(str), value);
}
@@ -423,8 +424,8 @@ inline bool safe_strtou64(StringPiece str, uint64* value) {
return safe_strtou64(str.ToString(), value);
}
-LIBPROTOBUF_EXPORT bool safe_strtof(const char* str, float* value);
-LIBPROTOBUF_EXPORT bool safe_strtod(const char* str, double* value);
+PROTOBUF_EXPORT bool safe_strtof(const char* str, float* value);
+PROTOBUF_EXPORT bool safe_strtod(const char* str, double* value);
inline bool safe_strtof(const string& str, float* value) {
return safe_strtof(str.c_str(), value);
}
@@ -464,13 +465,13 @@ inline bool safe_strtod(StringPiece str, double* value) {
// DoubleToBuffer() and FloatToBuffer().
static const int kFastToBufferSize = 32;
-LIBPROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer);
+PROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer);
+PROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer);
char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below
char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below
-LIBPROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer);
+PROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer);
+PROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer);
+PROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer);
// at least 22 bytes long
inline char* FastIntToBuffer(int i, char* buffer) {
@@ -506,10 +507,10 @@ inline char* FastULongToBuffer(unsigned long i, char* buffer) {
// terminating the string).
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer);
-LIBPROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer);
+PROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer);
+PROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer);
+PROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer);
+PROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer);
// Just define these in terms of the above.
inline char* FastUInt32ToBuffer(uint32 i, char* buffer) {
@@ -531,12 +532,12 @@ inline string SimpleBtoa(bool value) {
//
// Return value: string
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string SimpleItoa(int i);
-LIBPROTOBUF_EXPORT string SimpleItoa(unsigned int i);
-LIBPROTOBUF_EXPORT string SimpleItoa(long i);
-LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long i);
-LIBPROTOBUF_EXPORT string SimpleItoa(long long i);
-LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
+PROTOBUF_EXPORT string SimpleItoa(int i);
+PROTOBUF_EXPORT string SimpleItoa(unsigned int i);
+PROTOBUF_EXPORT string SimpleItoa(long i);
+PROTOBUF_EXPORT string SimpleItoa(unsigned long i);
+PROTOBUF_EXPORT string SimpleItoa(long long i);
+PROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
// ----------------------------------------------------------------------
// SimpleDtoa()
@@ -557,11 +558,11 @@ LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i);
//
// Return value: string
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string SimpleDtoa(double value);
-LIBPROTOBUF_EXPORT string SimpleFtoa(float value);
+PROTOBUF_EXPORT string SimpleDtoa(double value);
+PROTOBUF_EXPORT string SimpleFtoa(float value);
-LIBPROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer);
-LIBPROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer);
+PROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer);
+PROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer);
// In practice, doubles should never need more than 24 bytes and floats
// should never need more than 14 (including null terminators), but we
@@ -610,7 +611,7 @@ struct Hex {
}
};
-struct LIBPROTOBUF_EXPORT AlphaNum {
+struct PROTOBUF_EXPORT AlphaNum {
const char *piece_data_; // move these to string_ref eventually
size_t piece_size_; // move these to string_ref eventually
@@ -692,30 +693,30 @@ using strings::AlphaNum;
// be a reference into str.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d,
- const AlphaNum& e);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d,
- const AlphaNum& e, const AlphaNum& f);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d,
- const AlphaNum& e, const AlphaNum& f,
- const AlphaNum& g);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d,
- const AlphaNum& e, const AlphaNum& f,
- const AlphaNum& g, const AlphaNum& h);
-LIBPROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
- const AlphaNum& c, const AlphaNum& d,
- const AlphaNum& e, const AlphaNum& f,
- const AlphaNum& g, const AlphaNum& h,
- const AlphaNum& i);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d,
+ const AlphaNum& e);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d,
+ const AlphaNum& e, const AlphaNum& f);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d,
+ const AlphaNum& e, const AlphaNum& f,
+ const AlphaNum& g);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d,
+ const AlphaNum& e, const AlphaNum& f,
+ const AlphaNum& g, const AlphaNum& h);
+PROTOBUF_EXPORT string StrCat(const AlphaNum& a, const AlphaNum& b,
+ const AlphaNum& c, const AlphaNum& d,
+ const AlphaNum& e, const AlphaNum& f,
+ const AlphaNum& g, const AlphaNum& h,
+ const AlphaNum& i);
inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); }
@@ -740,14 +741,14 @@ inline string StrCat(const AlphaNum& a) { return string(a.data(), a.size()); }
// worked around as consecutive calls to StrAppend are quite efficient.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a);
-LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
- const AlphaNum& b);
-LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
- const AlphaNum& b, const AlphaNum& c);
-LIBPROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
- const AlphaNum& b, const AlphaNum& c,
- const AlphaNum& d);
+PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a);
+PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
+ const AlphaNum& b);
+PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
+ const AlphaNum& b, const AlphaNum& c);
+PROTOBUF_EXPORT void StrAppend(string* dest, const AlphaNum& a,
+ const AlphaNum& b, const AlphaNum& c,
+ const AlphaNum& d);
// ----------------------------------------------------------------------
// Join()
@@ -777,7 +778,7 @@ string Join(const Range& components,
// ToHex()
// Return a lower-case hex string representation of the given integer.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT string ToHex(uint64 num);
+PROTOBUF_EXPORT string ToHex(uint64 num);
// ----------------------------------------------------------------------
// GlobalReplaceSubstring()
@@ -786,9 +787,9 @@ LIBPROTOBUF_EXPORT string ToHex(uint64 num);
//
// NOTE: The string pieces must not overlap s.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
- const string& replacement,
- string* s);
+PROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
+ const string& replacement,
+ string* s);
// ----------------------------------------------------------------------
// Base64Unescape()
@@ -796,7 +797,7 @@ LIBPROTOBUF_EXPORT int GlobalReplaceSubstring(const string& substring,
// writes it to "dest". If src contains invalid characters, dest is cleared
// and the function returns false. Returns true on success.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest);
+PROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest);
// ----------------------------------------------------------------------
// WebSafeBase64Unescape()
@@ -809,18 +810,17 @@ LIBPROTOBUF_EXPORT bool Base64Unescape(StringPiece src, string* dest);
// returns false (with dest empty) if src contains invalid chars; for
// this version src and dest must be different strings.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen,
- char* dest, int szdest);
-LIBPROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest);
+PROTOBUF_EXPORT int WebSafeBase64Unescape(const char* src, int slen, char* dest,
+ int szdest);
+PROTOBUF_EXPORT bool WebSafeBase64Unescape(StringPiece src, string* dest);
// Return the length to use for the output buffer given to the base64 escape
// routines. Make sure to use the same value for do_padding in both.
// This function may return incorrect results if given input_len values that
// are extremely high, which should happen rarely.
-LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len,
- bool do_padding);
+PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len, bool do_padding);
// Use this version when calling Base64Escape without a do_padding arg.
-LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len);
+PROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len);
// ----------------------------------------------------------------------
// Base64Escape()
@@ -834,23 +834,23 @@ LIBPROTOBUF_EXPORT int CalculateBase64EscapedLen(int input_len);
// to escape them. It also has an extra parameter "do_padding",
// which when set to false will prevent padding with "=".
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen,
- char* dest, int szdest);
-LIBPROTOBUF_EXPORT int WebSafeBase64Escape(
- const unsigned char* src, int slen, char* dest,
- int szdest, bool do_padding);
+PROTOBUF_EXPORT int Base64Escape(const unsigned char* src, int slen, char* dest,
+ int szdest);
+PROTOBUF_EXPORT int WebSafeBase64Escape(const unsigned char* src, int slen,
+ char* dest, int szdest,
+ bool do_padding);
// Encode src into dest with padding.
-LIBPROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest);
+PROTOBUF_EXPORT void Base64Escape(StringPiece src, string* dest);
// Encode src into dest web-safely without padding.
-LIBPROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest);
+PROTOBUF_EXPORT void WebSafeBase64Escape(StringPiece src, string* dest);
// Encode src into dest web-safely with padding.
-LIBPROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src,
- string* dest);
+PROTOBUF_EXPORT void WebSafeBase64EscapeWithPadding(StringPiece src,
+ string* dest);
-LIBPROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc,
- string* dest, bool do_padding);
-LIBPROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc,
- string* dest, bool do_padding);
+PROTOBUF_EXPORT void Base64Escape(const unsigned char* src, int szsrc,
+ string* dest, bool do_padding);
+PROTOBUF_EXPORT void WebSafeBase64Escape(const unsigned char* src, int szsrc,
+ string* dest, bool do_padding);
inline bool IsValidCodePoint(uint32 code_point) {
return code_point < 0xD800 ||
@@ -864,15 +864,67 @@ static const int UTFmax = 4;
// in any external dependencies. The output buffer must be as least 4 bytes
// large.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output);
+PROTOBUF_EXPORT int EncodeAsUTF8Char(uint32 code_point, char* output);
// ----------------------------------------------------------------------
// UTF8FirstLetterNumBytes()
// Length of the first UTF-8 character.
// ----------------------------------------------------------------------
-LIBPROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len);
+PROTOBUF_EXPORT int UTF8FirstLetterNumBytes(const char* src, int len);
+
+// From google3/third_party/absl/strings/escaping.h
+
+// ----------------------------------------------------------------------
+// CleanStringLineEndings()
+// Clean up a multi-line string to conform to Unix line endings.
+// Reads from src and appends to dst, so usually dst should be empty.
+//
+// If there is no line ending at the end of a non-empty string, it can
+// be added automatically.
+//
+// Four different types of input are correctly handled:
+//
+// - Unix/Linux files: line ending is LF: pass through unchanged
+//
+// - DOS/Windows files: line ending is CRLF: convert to LF
+//
+// - Legacy Mac files: line ending is CR: convert to LF
+//
+// - Garbled files: random line endings: convert gracefully
+// lonely CR, lonely LF, CRLF: convert to LF
+//
+// @param src The multi-line string to convert
+// @param dst The converted string is appended to this string
+// @param auto_end_last_line Automatically terminate the last line
+//
+// Limitations:
+//
+// This does not do the right thing for CRCRLF files created by
+// broken programs that do another Unix->DOS conversion on files
+// that are already in CRLF format. For this, a two-pass approach
+// brute-force would be needed that
+//
+// (1) determines the presence of LF (first one is ok)
+// (2) if yes, removes any CR, else convert every CR to LF
+PROTOBUF_EXPORT void CleanStringLineEndings(const string& src, string* dst,
+ bool auto_end_last_line);
+
+// Same as above, but transforms the argument in place.
+PROTOBUF_EXPORT void CleanStringLineEndings(string* str,
+ bool auto_end_last_line);
+
+namespace strings {
+inline bool EndsWith(StringPiece text, StringPiece suffix) {
+ return suffix.empty() ||
+ (text.size() >= suffix.size() &&
+ memcmp(text.data() + (text.size() - suffix.size()), suffix.data(),
+ suffix.size()) == 0);
+}
+} // namespace strings
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__
diff --git a/src/google/protobuf/stubs/strutil_unittest.cc b/src/google/protobuf/stubs/strutil_unittest.cc
index 6bf0f598..9460a665 100644
--- a/src/google/protobuf/stubs/strutil_unittest.cc
+++ b/src/google/protobuf/stubs/strutil_unittest.cc
@@ -50,18 +50,18 @@ namespace {
TEST(StringUtilityTest, ImmuneToLocales) {
// Remember the old locale.
- char* old_locale_cstr = setlocale(LC_NUMERIC, NULL);
- ASSERT_TRUE(old_locale_cstr != NULL);
+ char* old_locale_cstr = setlocale(LC_NUMERIC, nullptr);
+ ASSERT_TRUE(old_locale_cstr != nullptr);
string old_locale = old_locale_cstr;
// Set the locale to "C".
- ASSERT_TRUE(setlocale(LC_NUMERIC, "C") != NULL);
+ ASSERT_TRUE(setlocale(LC_NUMERIC, "C") != nullptr);
EXPECT_EQ("1.5", SimpleDtoa(1.5));
EXPECT_EQ("1.5", SimpleFtoa(1.5));
- if (setlocale(LC_NUMERIC, "es_ES") == NULL &&
- setlocale(LC_NUMERIC, "es_ES.utf8") == NULL) {
+ if (setlocale(LC_NUMERIC, "es_ES") == nullptr &&
+ setlocale(LC_NUMERIC, "es_ES.utf8") == nullptr) {
// Some systems may not have the desired locale available.
GOOGLE_LOG(WARNING)
<< "Couldn't set locale to es_ES. Skipping this test.";
diff --git a/src/google/protobuf/stubs/substitute.cc b/src/google/protobuf/stubs/substitute.cc
index 7194a5b1..1ac9ab45 100644
--- a/src/google/protobuf/stubs/substitute.cc
+++ b/src/google/protobuf/stubs/substitute.cc
@@ -44,7 +44,7 @@ using internal::SubstituteArg;
// to Substitute().
static int CountSubstituteArgs(const SubstituteArg* const* args_array) {
int count = 0;
- while (args_array[count] != NULL && args_array[count]->size() != -1) {
+ while (args_array[count] != nullptr && args_array[count]->size() != -1) {
++count;
}
return count;
@@ -71,7 +71,7 @@ void SubstituteAndAppend(
const SubstituteArg& arg6, const SubstituteArg& arg7,
const SubstituteArg& arg8, const SubstituteArg& arg9) {
const SubstituteArg* const args_array[] = {
- &arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, NULL
+ &arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, nullptr
};
// Determine total size needed.
diff --git a/src/google/protobuf/stubs/substitute.h b/src/google/protobuf/stubs/substitute.h
index 7ee442af..267dead2 100644
--- a/src/google/protobuf/stubs/substitute.h
+++ b/src/google/protobuf/stubs/substitute.h
@@ -38,6 +38,8 @@
#ifndef GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
#define GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace strings {
@@ -93,7 +95,7 @@ class SubstituteArg {
// Indicates that no argument was given.
inline explicit SubstituteArg()
- : text_(NULL), size_(-1) {}
+ : text_(nullptr), size_(-1) {}
// Primitives
// We don't overload for signed and unsigned char because if people are
@@ -137,34 +139,36 @@ class SubstituteArg {
} // namespace internal
-LIBPROTOBUF_EXPORT string Substitute(
- const char* format,
- const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg9 = internal::SubstituteArg());
-
-LIBPROTOBUF_EXPORT void SubstituteAndAppend(
- string* output, const char* format,
- const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
- const internal::SubstituteArg& arg9 = internal::SubstituteArg());
+PROTOBUF_EXPORT string
+Substitute(const char* format,
+ const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg9 = internal::SubstituteArg());
+
+PROTOBUF_EXPORT void SubstituteAndAppend(
+ string* output, const char* format,
+ const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
+ const internal::SubstituteArg& arg9 = internal::SubstituteArg());
} // namespace strings
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
diff --git a/src/google/protobuf/stubs/time.cc b/src/google/protobuf/stubs/time.cc
index 6def637e..a1e5e1e2 100644
--- a/src/google/protobuf/stubs/time.cc
+++ b/src/google/protobuf/stubs/time.cc
@@ -142,12 +142,12 @@ string FormatNanos(int32 nanos) {
// Parses an integer from a null-terminated char sequence. The method
// consumes at most "width" chars. Returns a pointer after the consumed
-// integer, or NULL if the data does not start with an integer or the
+// integer, or nullptr if the data does not start with an integer or the
// integer value does not fall in the range of [min_value, max_value].
const char* ParseInt(const char* data, int width, int min_value,
int max_value, int* result) {
if (!ascii_isdigit(*data)) {
- return NULL;
+ return nullptr;
}
int value = 0;
for (int i = 0; i < width; ++i, ++data) {
@@ -161,7 +161,7 @@ const char* ParseInt(const char* data, int width, int min_value,
*result = value;
return data;
} else {
- return NULL;
+ return nullptr;
}
}
@@ -169,7 +169,7 @@ const char* ParseInt(const char* data, int width, int min_value,
// "010" will be parsed to 10000000 nanos.
const char* ParseNanos(const char* data, int32* nanos) {
if (!ascii_isdigit(*data)) {
- return NULL;
+ return nullptr;
}
int value = 0;
int len = 0;
@@ -193,15 +193,15 @@ const char* ParseNanos(const char* data, int32* nanos) {
const char* ParseTimezoneOffset(const char* data, int64* offset) {
// Accept format "HH:MM". E.g., "08:00"
int hour;
- if ((data = ParseInt(data, 2, 0, 23, &hour)) == NULL) {
- return NULL;
+ if ((data = ParseInt(data, 2, 0, 23, &hour)) == nullptr) {
+ return nullptr;
}
if (*data++ != ':') {
- return NULL;
+ return nullptr;
}
int minute;
- if ((data = ParseInt(data, 2, 0, 59, &minute)) == NULL) {
- return NULL;
+ if ((data = ParseInt(data, 2, 0, 59, &minute)) == nullptr) {
+ return nullptr;
}
*offset = (hour * 60 + minute) * 60;
return data;
@@ -264,7 +264,7 @@ bool DateTimeToSeconds(const DateTime& time, int64* seconds) {
void GetCurrentTime(int64* seconds, int32* nanos) {
// TODO(xiaofeng): Improve the accuracy of this implementation (or just
// remove this method from protobuf).
- *seconds = time(NULL);
+ *seconds = time(nullptr);
*nanos = 0;
}
@@ -290,37 +290,37 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) {
// With UTC offset: 2015-05-20T13:29:35.120-08:00
// Parse year
- if ((data = ParseInt(data, 4, 1, 9999, &time.year)) == NULL) {
+ if ((data = ParseInt(data, 4, 1, 9999, &time.year)) == nullptr) {
return false;
}
// Expect '-'
if (*data++ != '-') return false;
// Parse month
- if ((data = ParseInt(data, 2, 1, 12, &time.month)) == NULL) {
+ if ((data = ParseInt(data, 2, 1, 12, &time.month)) == nullptr) {
return false;
}
// Expect '-'
if (*data++ != '-') return false;
// Parse day
- if ((data = ParseInt(data, 2, 1, 31, &time.day)) == NULL) {
+ if ((data = ParseInt(data, 2, 1, 31, &time.day)) == nullptr) {
return false;
}
// Expect 'T'
if (*data++ != 'T') return false;
// Parse hour
- if ((data = ParseInt(data, 2, 0, 23, &time.hour)) == NULL) {
+ if ((data = ParseInt(data, 2, 0, 23, &time.hour)) == nullptr) {
return false;
}
// Expect ':'
if (*data++ != ':') return false;
// Parse minute
- if ((data = ParseInt(data, 2, 0, 59, &time.minute)) == NULL) {
+ if ((data = ParseInt(data, 2, 0, 59, &time.minute)) == nullptr) {
return false;
}
// Expect ':'
if (*data++ != ':') return false;
// Parse second
- if ((data = ParseInt(data, 2, 0, 59, &time.second)) == NULL) {
+ if ((data = ParseInt(data, 2, 0, 59, &time.second)) == nullptr) {
return false;
}
if (!DateTimeToSeconds(time, seconds)) {
@@ -330,7 +330,7 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) {
if (*data == '.') {
++data;
// Parse nanoseconds.
- if ((data = ParseNanos(data, nanos)) == NULL) {
+ if ((data = ParseNanos(data, nanos)) == nullptr) {
return false;
}
} else {
@@ -342,14 +342,14 @@ bool ParseTime(const string& value, int64* seconds, int32* nanos) {
} else if (*data == '+') {
++data;
int64 offset;
- if ((data = ParseTimezoneOffset(data, &offset)) == NULL) {
+ if ((data = ParseTimezoneOffset(data, &offset)) == nullptr) {
return false;
}
*seconds -= offset;
} else if (*data == '-') {
++data;
int64 offset;
- if ((data = ParseTimezoneOffset(data, &offset)) == NULL) {
+ if ((data = ParseTimezoneOffset(data, &offset)) == nullptr) {
return false;
}
*seconds += offset;
diff --git a/src/google/protobuf/stubs/time.h b/src/google/protobuf/stubs/time.h
index 45607ca9..12091de3 100644
--- a/src/google/protobuf/stubs/time.h
+++ b/src/google/protobuf/stubs/time.h
@@ -32,6 +32,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -49,12 +51,12 @@ struct DateTime {
// negative to represent time before 1970-01-01) to DateTime. Returns false
// if the timestamp is not in the range between 0001-01-01T00:00:00 and
// 9999-12-31T23:59:59.
-bool LIBPROTOBUF_EXPORT SecondsToDateTime(int64 seconds, DateTime* time);
+bool PROTOBUF_EXPORT SecondsToDateTime(int64 seconds, DateTime* time);
// Converts DateTime to a timestamp (seconds since 1970-01-01T00:00:00).
// Returns false if the DateTime is not valid or is not in the valid range.
-bool LIBPROTOBUF_EXPORT DateTimeToSeconds(const DateTime& time, int64* seconds);
+bool PROTOBUF_EXPORT DateTimeToSeconds(const DateTime& time, int64* seconds);
-void LIBPROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos);
+void PROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos);
// Formats a time string in RFC3339 fromat.
//
@@ -63,13 +65,16 @@ void LIBPROTOBUF_EXPORT GetCurrentTime(int64* seconds, int32* nanos);
// value.
//
// Note that "nanos" must in the range of [0, 999999999].
-string LIBPROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos);
+string PROTOBUF_EXPORT FormatTime(int64 seconds, int32 nanos);
// Parses a time string. This method accepts RFC3339 date/time string with UTC
// offset. For example, "2015-05-20T13:29:35.120-08:00".
-bool LIBPROTOBUF_EXPORT ParseTime(const string& value, int64* seconds, int32* nanos);
+bool PROTOBUF_EXPORT ParseTime(const string& value, int64* seconds,
+ int32* nanos);
} // namespace internal
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_STUBS_TIME_H_
diff --git a/src/google/protobuf/test_util.h b/src/google/protobuf/test_util.h
index b9abb671..5d22a763 100644
--- a/src/google/protobuf/test_util.h
+++ b/src/google/protobuf/test_util.h
@@ -44,6 +44,7 @@
#undef UNITTEST
#undef UNITTEST_IMPORT
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -94,7 +95,7 @@ class ReflectionTester {
static void ExpectOneofSetViaReflection(const Message& message);
private:
- const FieldDescriptor* F(const string& name);
+ const FieldDescriptor* F(const std::string& name);
const Descriptor* base_descriptor_;
@@ -128,10 +129,10 @@ inline TestUtil::ReflectionTester::ReflectionTester(
const Descriptor* base_descriptor)
: base_descriptor_(base_descriptor) {
const DescriptorPool* pool = base_descriptor->file()->pool();
- string package = base_descriptor->file()->package();
+ std::string package = base_descriptor->file()->package();
const FieldDescriptor* import_descriptor =
pool->FindFieldByName(package + ".TestAllTypes.optional_import_message");
- string import_package = import_descriptor->message_type()->file()->package();
+ std::string import_package = import_descriptor->message_type()->file()->package();
nested_b_ = pool->FindFieldByName(package + ".TestAllTypes.NestedMessage.bb");
foreign_c_ = pool->FindFieldByName(package + ".ForeignMessage.c");
@@ -176,7 +177,7 @@ inline TestUtil::ReflectionTester::ReflectionTester(
// Shorthand to get a FieldDescriptor for a field of TestAllTypes.
inline const FieldDescriptor* TestUtil::ReflectionTester::F(
- const string& name) {
+ const std::string& name) {
const FieldDescriptor* result = nullptr;
if (base_descriptor_->name() == "TestAllExtensions" ||
base_descriptor_->name() == "TestPackedExtensions") {
@@ -361,7 +362,7 @@ inline void TestUtil::ReflectionTester::ExpectOneofSetViaReflection(
const Message& message) {
const Descriptor* descriptor = message.GetDescriptor();
const Reflection* reflection = message.GetReflection();
- string scratch;
+ std::string scratch;
EXPECT_TRUE(reflection->HasField(
message, descriptor->FindFieldByName("foo_lazy_message")));
EXPECT_TRUE(
@@ -441,7 +442,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection(
inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1(
const Message& message) {
const Reflection* reflection = message.GetReflection();
- string scratch;
+ std::string scratch;
const Message* sub_message;
EXPECT_TRUE(reflection->HasField(message, F("optional_int32")));
@@ -565,7 +566,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1(
inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2(
const Message& message) {
const Reflection* reflection = message.GetReflection();
- string scratch;
+ std::string scratch;
const Message* sub_message;
// -----------------------------------------------------------------
@@ -740,7 +741,7 @@ inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2(
inline void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3(
const Message& message) {
const Reflection* reflection = message.GetReflection();
- string scratch;
+ std::string scratch;
// -----------------------------------------------------------------
@@ -869,7 +870,7 @@ inline void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection(
inline void TestUtil::ReflectionTester::ExpectClearViaReflection(
const Message& message) {
const Reflection* reflection = message.GetReflection();
- string scratch;
+ std::string scratch;
const Message* sub_message;
// has_blah() should initially be false for all optional fields.
@@ -1269,10 +1270,10 @@ inline void TestUtil::ReflectionTester::ExpectMessagesReleasedViaReflection(
// expect for a TestFieldOrderings message filled in by
// SetAllFieldsAndExtensions().
inline void ExpectAllFieldsAndExtensionsInOrder(
- const string& serialized) {
+ const std::string& serialized) {
// We set each field individually, serialize separately, and concatenate all
// the strings in canonical order to determine the expected serialization.
- string expected;
+ std::string expected;
unittest::TestFieldOrderings message;
message.set_my_int(1); // Field 1.
message.AppendToString(&expected);
@@ -1296,6 +1297,8 @@ inline void ExpectAllFieldsAndExtensionsInOrder(
} // namespace TestUtil
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_TEST_UTIL_H__
diff --git a/src/google/protobuf/test_util2.h b/src/google/protobuf/test_util2.h
new file mode 100644
index 00000000..d729808d
--- /dev/null
+++ b/src/google/protobuf/test_util2.h
@@ -0,0 +1,73 @@
+// 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_TEST_UTIL2_H__
+#define GOOGLE_PROTOBUF_TEST_UTIL2_H__
+
+#include <google/protobuf/stubs/strutil.h>
+
+#include <google/protobuf/testing/googletest.h>
+
+
+namespace google {
+namespace protobuf {
+namespace TestUtil {
+
+// Translate net/proto2/* -> google/protobuf/*
+inline ::std::string TranslatePathToOpensource(const ::std::string& google3_path) {
+ const ::std::string prefix = "net/proto2/";
+ GOOGLE_CHECK(google3_path.find(prefix) == 0) << google3_path;
+ ::std::string path = google3_path.substr(prefix.size());
+
+ path = StringReplace(path, "internal/", "", false);
+ path = StringReplace(path, "proto/", "", false);
+ path = StringReplace(path, "public/", "", false);
+ return "google/protobuf/" + path;
+}
+
+inline ::std::string MaybeTranslatePath(const ::std::string& google3_path) {
+ std::string path = google3_path;
+ path = TranslatePathToOpensource(path);
+ return path;
+}
+
+inline ::std::string TestSourceDir() {
+ return google::protobuf::TestSourceDir();
+}
+
+inline ::std::string GetTestDataPath(const ::std::string& google3_path) {
+ return TestSourceDir() + "/" + MaybeTranslatePath(google3_path);
+}
+
+} // namespace TestUtil
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_TEST_UTIL2_H__
diff --git a/src/google/protobuf/test_util_lite.h b/src/google/protobuf/test_util_lite.h
index 47a2269d..34edf944 100644
--- a/src/google/protobuf/test_util_lite.h
+++ b/src/google/protobuf/test_util_lite.h
@@ -96,6 +96,6 @@ class TestUtilLite {
};
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__
diff --git a/src/google/protobuf/testing/file.cc b/src/google/protobuf/testing/file.cc
index 26cb0a67..def92a00 100644
--- a/src/google/protobuf/testing/file.cc
+++ b/src/google/protobuf/testing/file.cc
@@ -69,9 +69,9 @@ bool File::Exists(const string& name) {
return access(name.c_str(), F_OK) == 0;
}
-bool File::ReadFileToString(const string& name, string* output) {
+bool File::ReadFileToString(const string& name, string* output, bool text_mode) {
char buffer[1024];
- FILE* file = fopen(name.c_str(), "rb");
+ FILE* file = fopen(name.c_str(), text_mode ? "rt" : "rb");
if (file == NULL) return false;
while (true) {
diff --git a/src/google/protobuf/testing/file.h b/src/google/protobuf/testing/file.h
index 2f63f80e..45989967 100644
--- a/src/google/protobuf/testing/file.h
+++ b/src/google/protobuf/testing/file.h
@@ -50,7 +50,7 @@ class File {
// Read an entire file to a string. Return true if successful, false
// otherwise.
- static bool ReadFileToString(const string& name, string* output);
+ static bool ReadFileToString(const string& name, string* output, bool text_mode = false);
// Same as above, but crash on failure.
static void ReadFileToStringOrDie(const string& name, string* output);
@@ -85,6 +85,11 @@ class File {
return ReadFileToString(name, output);
}
+ static bool GetContentsAsText(
+ const string& name, string* output, bool /*is_default*/) {
+ return ReadFileToString(name, output, true);
+ }
+
static bool SetContents(
const string& name, const string& contents, bool /*is_default*/) {
return WriteStringToFile(contents, name);
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index 0965fd7a..c8de875d 100644
--- a/src/google/protobuf/text_format.cc
+++ b/src/google/protobuf/text_format.cc
@@ -33,6 +33,7 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <algorithm>
+#include <climits>
#include <float.h>
#include <math.h>
#include <stdio.h>
@@ -44,23 +45,27 @@
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/any.h>
+#include <google/protobuf/descriptor.pb.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/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/map_field.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>
+
namespace google {
namespace protobuf {
@@ -212,7 +217,7 @@ const Descriptor* DefaultFinderFindAnyType(const Message& message,
// ===========================================================================
// Internal class for parsing an ASCII representation of a Protocol Message.
// This class makes use of the Protocol Message compiler's tokenizer found
-// in //google/protobuf/io/tokenizer.h. Note that class's Parse
+// in //net/proto2/io/public/tokenizer.h. Note that class's Parse
// method is *not* thread-safe and should only be used in a single thread at
// a time.
@@ -241,6 +246,7 @@ class TextFormat::Parser::ParserImpl {
SingularOverwritePolicy singular_overwrite_policy,
bool allow_case_insensitive_field,
bool allow_unknown_field,
+ bool allow_unknown_extension,
bool allow_unknown_enum,
bool allow_field_number,
bool allow_relaxed_whitespace,
@@ -254,6 +260,7 @@ class TextFormat::Parser::ParserImpl {
singular_overwrite_policy_(singular_overwrite_policy),
allow_case_insensitive_field_(allow_case_insensitive_field),
allow_unknown_field_(allow_unknown_field),
+ allow_unknown_extension_(allow_unknown_extension),
allow_unknown_enum_(allow_unknown_enum),
allow_field_number_(allow_field_number),
allow_partial_(allow_partial),
@@ -433,7 +440,7 @@ class TextFormat::Parser::ParserImpl {
: DefaultFinderFindExtension(message, field_name);
if (field == NULL) {
- if (!allow_unknown_field_) {
+ if (!allow_unknown_field_ && !allow_unknown_extension_) {
ReportError("Extension \"" + field_name + "\" is not defined or "
"is not an extension of \"" +
descriptor->full_name() + "\".");
@@ -448,7 +455,8 @@ class TextFormat::Parser::ParserImpl {
DO(ConsumeIdentifier(&field_name));
int32 field_number;
- if (allow_field_number_ && safe_strto32(field_name, &field_number)) {
+ 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)) {
@@ -501,7 +509,7 @@ class TextFormat::Parser::ParserImpl {
// Skips unknown or reserved fields.
if (field == NULL) {
- GOOGLE_CHECK(allow_unknown_field_ || reserved_field);
+ GOOGLE_CHECK(allow_unknown_field_ || allow_unknown_extension_ || reserved_field);
// Try to guess the type of this field.
// If this field is not a message, there should be a ":" between the
@@ -758,7 +766,7 @@ label_skip_parsing:
LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
int64 int_value;
DO(ConsumeSignedInteger(&int_value, kint32max));
- value = SimpleItoa(int_value); // for error reporting
+ value = SimpleItoa(int_value); // for error reporting
enum_value = enum_type->FindValueByNumber(int_value);
} else {
ReportError("Expected integer or identifier, got: " +
@@ -882,8 +890,9 @@ label_skip_parsing:
// If allow_field_numer_ or allow_unknown_field_ is true, we should able
// to parse integer identifiers.
- if ((allow_field_number_ || allow_unknown_field_)
- && LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
+ if ((allow_field_number_ || allow_unknown_field_ ||
+ allow_unknown_extension_) &&
+ LookingAtType(io::Tokenizer::TYPE_INTEGER)) {
*identifier = tokenizer_.current().text;
tokenizer_.Next();
return true;
@@ -1138,13 +1147,13 @@ label_skip_parsing:
explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser) :
parser_(parser) { }
- virtual ~ParserErrorCollector() { }
+ ~ParserErrorCollector() override {}
- virtual void AddError(int line, int column, const string& message) {
+ void AddError(int line, int column, const string& message) override {
parser_->ReportError(line, column, message);
}
- virtual void AddWarning(int line, int column, const string& message) {
+ void AddWarning(int line, int column, const string& message) override {
parser_->ReportWarning(line, column, message);
}
@@ -1162,17 +1171,16 @@ label_skip_parsing:
SingularOverwritePolicy singular_overwrite_policy_;
const bool allow_case_insensitive_field_;
const bool allow_unknown_field_;
+ const bool allow_unknown_extension_;
const bool allow_unknown_enum_;
const bool allow_field_number_;
const bool allow_partial_;
bool had_errors_;
};
-#undef DO
-
// ===========================================================================
// Internal class for writing text to the io::ZeroCopyOutputStream. Adapted
-// from the Printer found in //google/protobuf/io/printer.h
+// from the Printer found in //net/proto2/io/public/printer.h
class TextFormat::Printer::TextGenerator
: public TextFormat::BaseTextGenerator {
public:
@@ -1334,6 +1342,7 @@ TextFormat::Parser::Parser()
allow_partial_(false),
allow_case_insensitive_field_(false),
allow_unknown_field_(false),
+ allow_unknown_extension_(false),
allow_unknown_enum_(false),
allow_field_number_(false),
allow_relaxed_whitespace_(false),
@@ -1342,6 +1351,22 @@ TextFormat::Parser::Parser()
TextFormat::Parser::~Parser() {}
+namespace {
+
+bool CheckParseInputSize(StringPiece input,
+ io::ErrorCollector* error_collector) {
+ if (input.size() > INT_MAX) {
+ error_collector->AddError(
+ -1, 0,
+ StrCat("Input size too large: ", static_cast<int64>(input.size()),
+ " bytes", " > ", INT_MAX, " bytes."));
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input,
Message* output) {
output->Clear();
@@ -1351,17 +1376,17 @@ bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input,
? ParserImpl::ALLOW_SINGULAR_OVERWRITES
: ParserImpl::FORBID_SINGULAR_OVERWRITES;
- ParserImpl parser(output->GetDescriptor(), input, error_collector_,
- finder_, parse_info_tree_,
- overwrites_policy,
- allow_case_insensitive_field_, allow_unknown_field_,
- allow_unknown_enum_, allow_field_number_,
- allow_relaxed_whitespace_, allow_partial_);
+ ParserImpl parser(
+ output->GetDescriptor(), input, error_collector_, finder_,
+ parse_info_tree_, overwrites_policy, allow_case_insensitive_field_,
+ allow_unknown_field_, allow_unknown_extension_, allow_unknown_enum_,
+ allow_field_number_, allow_relaxed_whitespace_, allow_partial_);
return MergeUsingImpl(input, output, &parser);
}
bool TextFormat::Parser::ParseFromString(const string& input,
Message* output) {
+ DO(CheckParseInputSize(input, error_collector_));
io::ArrayInputStream input_stream(input.data(), input.size());
return Parse(&input_stream, output);
}
@@ -1369,17 +1394,18 @@ bool TextFormat::Parser::ParseFromString(const string& input,
bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input,
Message* output) {
- ParserImpl parser(output->GetDescriptor(), input, error_collector_,
- finder_, parse_info_tree_,
- ParserImpl::ALLOW_SINGULAR_OVERWRITES,
+ ParserImpl parser(output->GetDescriptor(), input, error_collector_, finder_,
+ parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES,
allow_case_insensitive_field_, allow_unknown_field_,
- allow_unknown_enum_, allow_field_number_,
- allow_relaxed_whitespace_, allow_partial_);
+ allow_unknown_extension_, allow_unknown_enum_,
+ allow_field_number_, allow_relaxed_whitespace_,
+ allow_partial_);
return MergeUsingImpl(input, output, &parser);
}
bool TextFormat::Parser::MergeFromString(const string& input,
Message* output) {
+ DO(CheckParseInputSize(input, error_collector_));
io::ArrayInputStream input_stream(input.data(), input.size());
return Merge(&input_stream, output);
}
@@ -1405,12 +1431,12 @@ bool TextFormat::Parser::ParseFieldValueFromString(
const FieldDescriptor* field,
Message* output) {
io::ArrayInputStream input_stream(input.data(), input.size());
- ParserImpl parser(output->GetDescriptor(), &input_stream, error_collector_,
- finder_, parse_info_tree_,
- ParserImpl::ALLOW_SINGULAR_OVERWRITES,
- allow_case_insensitive_field_, allow_unknown_field_,
- allow_unknown_enum_, allow_field_number_,
- allow_relaxed_whitespace_, allow_partial_);
+ ParserImpl parser(
+ output->GetDescriptor(), &input_stream, error_collector_, finder_,
+ parse_info_tree_, ParserImpl::ALLOW_SINGULAR_OVERWRITES,
+ allow_case_insensitive_field_, allow_unknown_field_,
+ allow_unknown_extension_, allow_unknown_enum_, allow_field_number_,
+ allow_relaxed_whitespace_, allow_partial_);
return parser.ParseField(field, output);
}
@@ -1435,6 +1461,8 @@ bool TextFormat::Parser::ParseFieldValueFromString(
}
+#undef DO
+
// ===========================================================================
TextFormat::BaseTextGenerator::~BaseTextGenerator() {}
@@ -1444,7 +1472,9 @@ 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); }
+ void Print(const char* text, size_t size) override {
+ 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.
@@ -1642,61 +1672,70 @@ class FieldValuePrinterWrapper : public TextFormat::FastFieldValuePrinter {
delegate_.reset(delegate);
}
- void PrintBool(bool val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintBool(bool val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintBool(val));
}
- void PrintInt32(int32 val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintInt32(int32 val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintInt32(val));
}
- void PrintUInt32(uint32 val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintUInt32(uint32 val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintUInt32(val));
}
- void PrintInt64(int64 val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintInt64(int64 val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintInt64(val));
}
- void PrintUInt64(uint64 val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintUInt64(uint64 val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintUInt64(val));
}
- void PrintFloat(float val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintFloat(float val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintFloat(val));
}
- void PrintDouble(double val, TextFormat::BaseTextGenerator* generator) const {
+ void PrintDouble(double val,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintDouble(val));
}
void PrintString(const string& val,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintString(val));
}
void PrintBytes(const string& val,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintBytes(val));
}
void PrintEnum(int32 val, const string& name,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintEnum(val, name));
}
void PrintFieldName(const Message& message, int field_index, int field_count,
const Reflection* reflection,
const FieldDescriptor* field,
- TextFormat::BaseTextGenerator* generator) const {
- generator->PrintString(delegate_->PrintFieldName(
- message, reflection, field));
+ TextFormat::BaseTextGenerator* generator) const override {
+ generator->PrintString(
+ delegate_->PrintFieldName(message, reflection, field));
}
void PrintFieldName(const Message& message, const Reflection* reflection,
const FieldDescriptor* field,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
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 {
+ void PrintMessageStart(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const override {
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 {
+ void PrintMessageEnd(
+ const Message& message, int field_index, int field_count,
+ bool single_line_mode,
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintString(delegate_->PrintMessageEnd(
message, field_index, field_count, single_line_mode));
}
@@ -1710,13 +1749,13 @@ class FastFieldValuePrinterUtf8Escaping
: public TextFormat::FastFieldValuePrinter {
public:
void PrintString(const string& val,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
generator->PrintLiteral("\"");
generator->PrintString(strings::Utf8SafeCEscape(val));
generator->PrintLiteral("\"");
}
void PrintBytes(const string& val,
- TextFormat::BaseTextGenerator* generator) const {
+ TextFormat::BaseTextGenerator* generator) const override {
return FastFieldValuePrinter::PrintString(val, generator);
}
};
@@ -1867,7 +1906,7 @@ bool TextFormat::Printer::PrintAny(const Message& message,
}
// Print the "value" in text.
- const google::protobuf::Descriptor* value_descriptor =
+ const Descriptor* value_descriptor =
finder_ ? finder_->FindAnyType(message, url_prefix, full_type_name)
: DefaultFinderFindAnyType(message, url_prefix, full_type_name);
if (value_descriptor == NULL) {
@@ -1875,7 +1914,7 @@ bool TextFormat::Printer::PrintAny(const Message& message,
return false;
}
DynamicMessageFactory factory;
- std::unique_ptr<google::protobuf::Message> value_message(
+ std::unique_ptr<Message> value_message(
factory.GetPrototype(value_descriptor)->New());
string serialized_value = reflection->GetString(message, value_field);
if (!value_message->ParseFromString(serialized_value)) {
@@ -1909,7 +1948,13 @@ void TextFormat::Printer::Print(const Message& message,
return;
}
std::vector<const FieldDescriptor*> fields;
- reflection->ListFields(message, &fields);
+ if (descriptor->options().map_entry()) {
+ fields.push_back(descriptor->field(0));
+ fields.push_back(descriptor->field(1));
+ } else {
+ reflection->ListFields(message, &fields);
+ }
+
if (print_message_fields_in_index_order_) {
std::sort(fields.begin(), fields.end(), FieldIndexSorter());
}
@@ -1935,6 +1980,181 @@ void TextFormat::Printer::PrintFieldValueToString(
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_;
+};
+
+namespace internal {
+class MapFieldPrinterHelper {
+ public:
+ // DynamicMapSorter::Sort cannot be used because it enfores syncing with
+ // repeated field.
+ static bool SortMap(const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field, MessageFactory* factory,
+ std::vector<const Message*>* sorted_map_field);
+ static void CopyKey(const MapKey& key, Message* message,
+ const FieldDescriptor* field_desc);
+ static void CopyValue(const MapValueRef& value, Message* message,
+ const FieldDescriptor* field_desc);
+};
+
+// Returns true if elements contained in sorted_map_field need to be released.
+bool MapFieldPrinterHelper::SortMap(
+ const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field, MessageFactory* factory,
+ std::vector<const Message*>* sorted_map_field) {
+ bool need_release = false;
+ const MapFieldBase& base =
+ *reflection->MapData(const_cast<Message*>(&message), field);
+
+ if (base.IsRepeatedFieldValid()) {
+ const RepeatedPtrField<Message>& map_field =
+ reflection->GetRepeatedPtrField<Message>(message, field);
+ for (int i = 0; i < map_field.size(); ++i) {
+ sorted_map_field->push_back(
+ const_cast<RepeatedPtrField<Message>*>(&map_field)->Mutable(i));
+ }
+ } else {
+ // TODO(teboring): For performance, instead of creating map entry message
+ // for each element, just store map keys and sort them.
+ const Descriptor* map_entry_desc = field->message_type();
+ const Message* prototype = factory->GetPrototype(map_entry_desc);
+ for (MapIterator iter =
+ reflection->MapBegin(const_cast<Message*>(&message), field);
+ iter != reflection->MapEnd(const_cast<Message*>(&message), field);
+ ++iter) {
+ Message* map_entry_message = prototype->New();
+ CopyKey(iter.GetKey(), map_entry_message, map_entry_desc->field(0));
+ CopyValue(iter.GetValueRef(), map_entry_message,
+ map_entry_desc->field(1));
+ sorted_map_field->push_back(map_entry_message);
+ }
+ need_release = true;
+ }
+
+ MapEntryMessageComparator comparator(field->message_type());
+ std::stable_sort(sorted_map_field->begin(), sorted_map_field->end(),
+ comparator);
+ return need_release;
+}
+
+void MapFieldPrinterHelper::CopyKey(const MapKey& key, Message* message,
+ const FieldDescriptor* field_desc) {
+ const Reflection* reflection = message->GetReflection();
+ switch (field_desc->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ case FieldDescriptor::CPPTYPE_ENUM:
+ case FieldDescriptor::CPPTYPE_MESSAGE:
+ GOOGLE_LOG(ERROR) << "Not supported.";
+ break;
+ case FieldDescriptor::CPPTYPE_STRING:
+ reflection->SetString(message, field_desc, key.GetStringValue());
+ return;
+ case FieldDescriptor::CPPTYPE_INT64:
+ reflection->SetInt64(message, field_desc, key.GetInt64Value());
+ return;
+ case FieldDescriptor::CPPTYPE_INT32:
+ reflection->SetInt32(message, field_desc, key.GetInt32Value());
+ return;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ reflection->SetUInt64(message, field_desc, key.GetUInt64Value());
+ return;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ reflection->SetUInt32(message, field_desc, key.GetUInt32Value());
+ return;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ reflection->SetBool(message, field_desc, key.GetBoolValue());
+ return;
+ }
+}
+
+void MapFieldPrinterHelper::CopyValue(const MapValueRef& value,
+ Message* message,
+ const FieldDescriptor* field_desc) {
+ const Reflection* reflection = message->GetReflection();
+ switch (field_desc->cpp_type()) {
+ case FieldDescriptor::CPPTYPE_DOUBLE:
+ reflection->SetDouble(message, field_desc, value.GetDoubleValue());
+ return;
+ case FieldDescriptor::CPPTYPE_FLOAT:
+ reflection->SetFloat(message, field_desc, value.GetFloatValue());
+ return;
+ case FieldDescriptor::CPPTYPE_ENUM:
+ reflection->SetEnumValue(message, field_desc, value.GetEnumValue());
+ return;
+ case FieldDescriptor::CPPTYPE_MESSAGE: {
+ Message* sub_message = value.GetMessageValue().New();
+ sub_message->CopyFrom(value.GetMessageValue());
+ reflection->SetAllocatedMessage(message, sub_message, field_desc);
+ return;
+ }
+ case FieldDescriptor::CPPTYPE_STRING:
+ reflection->SetString(message, field_desc, value.GetStringValue());
+ return;
+ case FieldDescriptor::CPPTYPE_INT64:
+ reflection->SetInt64(message, field_desc, value.GetInt64Value());
+ return;
+ case FieldDescriptor::CPPTYPE_INT32:
+ reflection->SetInt32(message, field_desc, value.GetInt32Value());
+ return;
+ case FieldDescriptor::CPPTYPE_UINT64:
+ reflection->SetUInt64(message, field_desc, value.GetUInt64Value());
+ return;
+ case FieldDescriptor::CPPTYPE_UINT32:
+ reflection->SetUInt32(message, field_desc, value.GetUInt32Value());
+ return;
+ case FieldDescriptor::CPPTYPE_BOOL:
+ reflection->SetBool(message, field_desc, value.GetBoolValue());
+ return;
+ }
+}
+} // namespace internal
+
void TextFormat::Printer::PrintField(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
@@ -1951,14 +2171,18 @@ void TextFormat::Printer::PrintField(const Message& message,
if (field->is_repeated()) {
count = reflection->FieldSize(message, field);
- } else if (reflection->HasField(message, field)) {
+ } else if (reflection->HasField(message, field) ||
+ field->containing_type()->options().map_entry()) {
count = 1;
}
- std::vector<const Message*> map_entries;
- const bool is_map = field->is_map();
+ DynamicMessageFactory factory;
+ std::vector<const Message*> sorted_map_field;
+ bool need_release = false;
+ bool is_map = field->is_map();
if (is_map) {
- map_entries = DynamicMapSorter::Sort(message, count, reflection, field);
+ need_release = internal::MapFieldPrinterHelper::SortMap(
+ message, reflection, field, &factory, &sorted_map_field);
}
for (int j = 0; j < count; ++j) {
@@ -1971,7 +2195,7 @@ void TextFormat::Printer::PrintField(const Message& message,
custom_printers_, field, default_field_value_printer_.get());
const Message& sub_message =
field->is_repeated()
- ? (is_map ? *map_entries[j]
+ ? (is_map ? *sorted_map_field[j]
: reflection->GetRepeatedMessage(message, field, j))
: reflection->GetMessage(message, field);
printer->PrintMessageStart(sub_message, field_index, count,
@@ -1992,6 +2216,12 @@ void TextFormat::Printer::PrintField(const Message& message,
}
}
}
+
+ if (need_release) {
+ for (int j = 0; j < sorted_map_field.size(); ++j) {
+ delete sorted_map_field[j];
+ }
+ }
}
void TextFormat::Printer::PrintShortRepeatedField(
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h
index d6f3e16b..d185bfd9 100644
--- a/src/google/protobuf/text_format.h
+++ b/src/google/protobuf/text_format.h
@@ -47,6 +47,13 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/message_lite.h>
+#include <google/protobuf/port.h>
+
+#include <google/protobuf/port_def.inc>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
namespace google {
namespace protobuf {
@@ -60,7 +67,7 @@ namespace io {
// of messages.
//
// This class is really a namespace that contains only static methods.
-class LIBPROTOBUF_EXPORT TextFormat {
+class PROTOBUF_EXPORT TextFormat {
public:
// Outputs a textual representation of the given message to the given
// output stream. Returns false if printing fails.
@@ -75,12 +82,12 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Like Print(), but outputs directly to a string.
// 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);
+ static bool PrintToString(const Message& message, std::string* output);
// Like PrintUnknownFields(), but outputs directly to a string. Returns false
// if printing fails.
static bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields,
- string* output);
+ std::string* output);
// Outputs a textual representation of the value of the field supplied on
// the message supplied. For non-repeated fields, an index of -1 must
@@ -89,9 +96,9 @@ class LIBPROTOBUF_EXPORT TextFormat {
static void PrintFieldValueToString(const Message& message,
const FieldDescriptor* field,
int index,
- string* output);
+ std::string* output);
- class LIBPROTOBUF_EXPORT BaseTextGenerator {
+ class PROTOBUF_EXPORT BaseTextGenerator {
public:
virtual ~BaseTextGenerator();
@@ -101,7 +108,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// 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()); }
+ void PrintString(const std::string& str) { Print(str.data(), str.size()); }
template <size_t n>
void PrintLiteral(const char (&text)[n]) {
@@ -113,7 +120,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// 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 {
+ class PROTOBUF_EXPORT FastFieldValuePrinter {
public:
FastFieldValuePrinter();
virtual ~FastFieldValuePrinter();
@@ -124,11 +131,11 @@ class LIBPROTOBUF_EXPORT TextFormat {
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,
+ virtual void PrintString(const std::string& val,
BaseTextGenerator* generator) const;
- virtual void PrintBytes(const string& val,
+ virtual void PrintBytes(const std::string& val,
BaseTextGenerator* generator) const;
- virtual void PrintEnum(int32 val, const string& name,
+ virtual void PrintEnum(int32 val, const std::string& name,
BaseTextGenerator* generator) const;
virtual void PrintFieldName(const Message& message, int field_index,
int field_count, const Reflection* reflection,
@@ -149,29 +156,29 @@ class LIBPROTOBUF_EXPORT TextFormat {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FastFieldValuePrinter);
};
- class LIBPROTOBUF_EXPORT PROTOBUF_RUNTIME_DEPRECATED("Please use FastFieldValuePrinter")
- FieldValuePrinter {
+ class PROTOBUF_EXPORT PROTOBUF_DEPRECATED_MSG(
+ "Please use FastFieldValuePrinter") FieldValuePrinter {
public:
FieldValuePrinter();
virtual ~FieldValuePrinter();
- virtual string PrintBool(bool val) const;
- virtual string PrintInt32(int32 val) const;
- virtual string PrintUInt32(uint32 val) const;
- virtual string PrintInt64(int64 val) const;
- virtual string PrintUInt64(uint64 val) const;
- virtual string PrintFloat(float val) const;
- virtual string PrintDouble(double val) const;
- virtual string PrintString(const string& val) const;
- virtual string PrintBytes(const string& val) const;
- virtual string PrintEnum(int32 val, const string& name) const;
- virtual string PrintFieldName(const Message& message,
+ virtual std::string PrintBool(bool val) const;
+ virtual std::string PrintInt32(int32 val) const;
+ virtual std::string PrintUInt32(uint32 val) const;
+ virtual std::string PrintInt64(int64 val) const;
+ virtual std::string PrintUInt64(uint64 val) const;
+ virtual std::string PrintFloat(float val) const;
+ virtual std::string PrintDouble(double val) const;
+ virtual std::string PrintString(const std::string& val) const;
+ virtual std::string PrintBytes(const std::string& val) const;
+ virtual std::string PrintEnum(int32 val, const std::string& name) const;
+ virtual std::string PrintFieldName(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field) const;
- virtual string PrintMessageStart(const Message& message,
+ virtual std::string PrintMessageStart(const Message& message,
int field_index,
int field_count,
bool single_line_mode) const;
- virtual string PrintMessageEnd(const Message& message,
+ virtual std::string PrintMessageEnd(const Message& message,
int field_index,
int field_count,
bool single_line_mode) const;
@@ -181,7 +188,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldValuePrinter);
};
- class LIBPROTOBUF_EXPORT MessagePrinter {
+ class PROTOBUF_EXPORT MessagePrinter {
public:
MessagePrinter() {}
virtual ~MessagePrinter() {}
@@ -194,7 +201,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Interface that Printers or Parsers can use to find extensions, or types
// referenced in Any messages.
- class LIBPROTOBUF_EXPORT Finder {
+ class PROTOBUF_EXPORT Finder {
public:
virtual ~Finder();
@@ -203,7 +210,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// The base implementation uses the extensions already known by the message.
virtual const FieldDescriptor* FindExtension(
Message* message,
- const string& name) const;
+ const std::string& name) const;
// Find the message type for an Any proto.
// Returns NULL if no message is known for this name.
@@ -211,13 +218,13 @@ class LIBPROTOBUF_EXPORT TextFormat {
// type.googleapis.com/, and searches the DescriptorPool of the parent
// message.
virtual const Descriptor* FindAnyType(const Message& message,
- const string& prefix,
- const string& name) const;
+ const std::string& prefix,
+ const std::string& name) const;
};
// Class for those users which require more fine-grained control over how
// a protobuffer message is printed out.
- class LIBPROTOBUF_EXPORT Printer {
+ class PROTOBUF_EXPORT Printer {
public:
Printer();
~Printer();
@@ -228,15 +235,15 @@ class LIBPROTOBUF_EXPORT TextFormat {
bool PrintUnknownFields(const UnknownFieldSet& unknown_fields,
io::ZeroCopyOutputStream* output) const;
// Like TextFormat::PrintToString
- bool PrintToString(const Message& message, string* output) const;
+ bool PrintToString(const Message& message, std::string* output) const;
// Like TextFormat::PrintUnknownFieldsToString
bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields,
- string* output) const;
+ std::string* output) const;
// Like TextFormat::PrintFieldValueToString
void PrintFieldValueToString(const Message& message,
const FieldDescriptor* field,
int index,
- string* output) const;
+ std::string* output) const;
// Adjust the initial indent level of all output. Each indent level is
// equal to two spaces.
@@ -313,9 +320,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
}
// Set how parser finds message for Any payloads.
- void SetFinder(Finder* finder) {
- finder_ = finder;
- }
+ void SetFinder(const Finder* finder) { finder_ = finder; }
// If non-zero, we truncate all string fields that are longer than this
// threshold. This is useful when the proto message has very long strings,
@@ -432,18 +437,18 @@ class LIBPROTOBUF_EXPORT TextFormat {
// google::protobuf::MessageLite::ParseFromString().
static bool Parse(io::ZeroCopyInputStream* input, Message* output);
// Like Parse(), but reads directly from a string.
- static bool ParseFromString(const string& input, Message* output);
+ static bool ParseFromString(const std::string& input, Message* output);
// Like Parse(), but the data is merged into the given message, as if
// using Message::MergeFrom().
static bool Merge(io::ZeroCopyInputStream* input, Message* output);
// Like Merge(), but reads directly from a string.
- static bool MergeFromString(const string& input, Message* output);
+ static bool MergeFromString(const std::string& input, Message* output);
// Parse the given text as a single field value and store it into the
// given field of the given message. If the field is a repeated field,
// the new value will be added to the end
- static bool ParseFieldValueFromString(const string& input,
+ static bool ParseFieldValueFromString(const std::string& input,
const FieldDescriptor* field,
Message* message);
@@ -459,7 +464,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Data structure which is populated with the locations of each field
// value parsed from the text.
- class LIBPROTOBUF_EXPORT ParseInfoTree {
+ class PROTOBUF_EXPORT ParseInfoTree {
public:
ParseInfoTree();
~ParseInfoTree();
@@ -501,7 +506,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
};
// For more control over parsing, use this class.
- class LIBPROTOBUF_EXPORT Parser {
+ class PROTOBUF_EXPORT Parser {
public:
Parser();
~Parser();
@@ -509,11 +514,11 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Like TextFormat::Parse().
bool Parse(io::ZeroCopyInputStream* input, Message* output);
// Like TextFormat::ParseFromString().
- bool ParseFromString(const string& input, Message* output);
+ bool ParseFromString(const std::string& input, Message* output);
// Like TextFormat::Merge().
bool Merge(io::ZeroCopyInputStream* input, Message* output);
// Like TextFormat::MergeFromString().
- bool MergeFromString(const string& input, Message* output);
+ bool MergeFromString(const std::string& input, Message* output);
// Set where to report parse errors. If NULL (the default), errors will
// be printed to stderr.
@@ -524,9 +529,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
// Set how parser finds extensions. If NULL (the default), the
// parser will use the standard Reflection object associated with
// the message being parsed.
- void SetFinder(Finder* finder) {
- finder_ = finder;
- }
+ void SetFinder(const Finder* finder) { finder_ = finder; }
// Sets where location information about the parse will be written. If NULL
// (the default), then no location will be written.
@@ -549,10 +552,17 @@ class LIBPROTOBUF_EXPORT TextFormat {
}
// Like TextFormat::ParseFieldValueFromString
- bool ParseFieldValueFromString(const string& input,
+ bool ParseFieldValueFromString(const std::string& input,
const FieldDescriptor* field,
Message* output);
+ // When an unknown extension is met, parsing will fail if this option is set
+ // to false (the default). If true, unknown extensions will be ignored and
+ // a warning message will be generated.
+ void AllowUnknownExtension(bool allow) {
+ allow_unknown_extension_ = allow;
+ }
+
void AllowFieldNumber(bool allow) {
allow_field_number_ = allow;
@@ -575,6 +585,7 @@ class LIBPROTOBUF_EXPORT TextFormat {
bool allow_partial_;
bool allow_case_insensitive_field_;
bool allow_unknown_field_;
+ bool allow_unknown_extension_;
bool allow_unknown_enum_;
bool allow_field_number_;
bool allow_relaxed_whitespace_;
@@ -609,6 +620,8 @@ inline TextFormat::ParseInfoTree* TextFormat::CreateNested(
}
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_TEXT_FORMAT_H__
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc
index 544c37e2..d64cd2eb 100644
--- a/src/google/protobuf/text_format_unittest.cc
+++ b/src/google/protobuf/text_format_unittest.cc
@@ -44,20 +44,24 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
+#include <google/protobuf/map_unittest.pb.h>
#include <google/protobuf/test_util.h>
+#include <google/protobuf/test_util2.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_mset.pb.h>
#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/strutil.h>
+
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
#include <google/protobuf/stubs/mathlimits.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -78,10 +82,11 @@ class TextFormatTest : public testing::Test {
public:
static void SetUpTestCase() {
GOOGLE_CHECK_OK(File::GetContents(
- TestSourceDir() +
- "/google/protobuf/"
- "testdata/text_format_unittest_data_oneof_implemented.txt",
+ TestUtil::GetTestDataPath(
+ "net/proto2/internal/"
+ "testdata/text_format_unittest_data_oneof_implemented.txt"),
&static_proto_debug_string_, true));
+ CleanStringLineEndings(&static_proto_debug_string_, false);
}
TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {}
@@ -99,10 +104,11 @@ string TextFormatTest::static_proto_debug_string_;
class TextFormatExtensionsTest : public testing::Test {
public:
static void SetUpTestCase() {
- GOOGLE_CHECK_OK(File::GetContents(TestSourceDir() +
- "/google/protobuf/testdata/"
- "text_format_unittest_extensions_data.txt",
- &static_proto_debug_string_, true));
+ GOOGLE_CHECK_OK(File::GetContents(
+ TestUtil::GetTestDataPath("net/proto2/internal/testdata/"
+ "text_format_unittest_extensions_data.txt"),
+ &static_proto_debug_string_, true));
+ CleanStringLineEndings(&static_proto_debug_string_, false);
}
TextFormatExtensionsTest()
@@ -484,7 +490,8 @@ TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) {
class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter {
public:
virtual string PrintInt32(int32 v) const {
- return StrCat(FieldValuePrinter::PrintInt32(v), " # x", strings::Hex(v));
+ return StrCat(FieldValuePrinter::PrintInt32(v), " # x",
+ strings::Hex(v));
}
virtual string PrintMessageStart(const Message& message,
@@ -494,8 +501,8 @@ class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter {
if (single_line_mode) {
return " { ";
}
- return StrCat(
- " { # ", message.GetDescriptor()->name(), ": ", field_index, "\n");
+ return StrCat(" { # ", message.GetDescriptor()->name(), ": ",
+ field_index, "\n");
}
};
@@ -574,6 +581,11 @@ class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter {
generator->PrintString(field->name());
}
}
+ // To prevent compiler complaining about Woverloaded-virtual
+ void PrintFieldName(const Message& message, const Reflection* reflection,
+ const FieldDescriptor* field,
+ TextFormat::BaseTextGenerator* generator) const override {
+ }
void PrintMessageStart(
const Message& message, int field_index, int field_count,
bool single_line_mode,
@@ -954,8 +966,8 @@ TEST_F(TextFormatTest, PrintExotic) {
// 9223372036854775808 is outside the range of int64. However, it is not
// outside the range of uint64. Confusingly, this means that everything
// works if we make the literal unsigned, even though we are negating it.
- message.add_repeated_int64(-GOOGLE_ULONGLONG(9223372036854775808));
- message.add_repeated_uint64(GOOGLE_ULONGLONG(18446744073709551615));
+ message.add_repeated_int64(-PROTOBUF_ULONGLONG(9223372036854775808));
+ message.add_repeated_uint64(PROTOBUF_ULONGLONG(18446744073709551615));
message.add_repeated_double(123.456);
message.add_repeated_double(1.23e21);
message.add_repeated_double(1.23e-18);
@@ -991,6 +1003,7 @@ TEST_F(TextFormatTest, PrintExotic) {
TEST_F(TextFormatTest, PrintFloatPrecision) {
unittest::TestAllTypes message;
+ message.add_repeated_float(1.0);
message.add_repeated_float(1.2);
message.add_repeated_float(1.23);
message.add_repeated_float(1.234);
@@ -1031,6 +1044,7 @@ TEST_F(TextFormatTest, PrintFloatPrecision) {
message.add_repeated_double(1.23456789876543e100);
EXPECT_EQ(
+ "repeated_float: 1\n"
"repeated_float: 1.2\n"
"repeated_float: 1.23\n"
"repeated_float: 1.234\n"
@@ -1126,15 +1140,18 @@ TEST_F(TextFormatTest, ParseExotic) {
// 9223372036854775808 is outside the range of int64. However, it is not
// outside the range of uint64. Confusingly, this means that everything
// works if we make the literal unsigned, even though we are negating it.
- EXPECT_EQ(-GOOGLE_ULONGLONG(9223372036854775808), message.repeated_int64(1));
+ EXPECT_EQ(-PROTOBUF_ULONGLONG(9223372036854775808),
+ message.repeated_int64(1));
ASSERT_EQ(2, message.repeated_uint32_size());
EXPECT_EQ(4294967295u, message.repeated_uint32(0));
EXPECT_EQ(2147483648u, message.repeated_uint32(1));
ASSERT_EQ(2, message.repeated_uint64_size());
- EXPECT_EQ(GOOGLE_ULONGLONG(18446744073709551615), message.repeated_uint64(0));
- EXPECT_EQ(GOOGLE_ULONGLONG(9223372036854775808), message.repeated_uint64(1));
+ EXPECT_EQ(PROTOBUF_ULONGLONG(18446744073709551615),
+ message.repeated_uint64(0));
+ EXPECT_EQ(PROTOBUF_ULONGLONG(9223372036854775808),
+ message.repeated_uint64(1));
ASSERT_EQ(13, message.repeated_double_size());
EXPECT_EQ(123.0 , message.repeated_double(0));
@@ -1267,7 +1284,8 @@ class TextFormatParserTest : public testing::Test {
parser.RecordErrorsTo(&error_collector);
EXPECT_EQ(expected_result, parser.ParseFromString(input, proto))
<< input << " -> " << proto->DebugString();
- EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) + ": " + message + "\n",
+ EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) +
+ ": " + message + "\n",
error_collector.text_);
}
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc
index 8e6b5f23..4a962e3b 100644
--- a/src/google/protobuf/timestamp.pb.cc
+++ b/src/google/protobuf/timestamp.pb.cc
@@ -6,30 +6,25 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class TimestampDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Timestamp>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Timestamp> _instance;
} _Timestamp_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto {
-static void InitDefaultsTimestamp() {
+static void InitDefaultsTimestamp_google_2fprotobuf_2ftimestamp_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -40,25 +35,27 @@ static void InitDefaultsTimestamp() {
::google::protobuf::Timestamp::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTimestamp_google_2fprotobuf_2ftimestamp_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Timestamp.base);
+void InitDefaults_google_2fprotobuf_2ftimestamp_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[1];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto[1];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Timestamp, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Timestamp, seconds_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Timestamp, nanos_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Timestamp)},
};
@@ -66,51 +63,33 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Timestamp_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/timestamp.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2ftimestamp_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2ftimestamp_2eproto, "google/protobuf/timestamp.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto,
+};
-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);
-}
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2ftimestamp_2eproto,
+ "\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"
+ "TimestampProtoP\001Z+github.com/golang/prot"
+ "obuf/ptypes/timestamp\370\001\001\242\002\003GPB\252\002\036Google."
+ "Protobuf.WellKnownTypesb\006proto3"
+,
+ "google/protobuf/timestamp.proto", &assign_descriptors_table_google_2fprotobuf_2ftimestamp_2eproto, 231,
+};
-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"
- "TimestampProtoP\001Z+github.com/golang/prot"
- "obuf/ptypes/timestamp\370\001\001\242\002\003GPB\252\002\036Google."
- "Protobuf.WellKnownTypesb\006proto3"
+void AddDescriptors_google_2fprotobuf_2ftimestamp_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 231);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/timestamp.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto = []() { AddDescriptors_google_2fprotobuf_2ftimestamp_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -118,6 +97,10 @@ namespace protobuf {
void Timestamp::InitAsDefaultInstance() {
}
+class Timestamp::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Timestamp::kSecondsFieldNumber;
const int Timestamp::kNanosFieldNumber;
@@ -125,15 +108,12 @@ const int Timestamp::kNanosFieldNumber;
Timestamp::Timestamp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Timestamp)
}
Timestamp::Timestamp(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp)
@@ -167,18 +147,13 @@ void Timestamp::ArenaDtor(void* object) {
Timestamp* _this = reinterpret_cast< Timestamp* >(object);
(void)_this;
}
-void Timestamp::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Timestamp::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Timestamp::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Timestamp::descriptor() {
- ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Timestamp& Timestamp::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftimestamp_2eproto::scc_info_Timestamp.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base);
return *internal_default_instance();
}
@@ -195,9 +170,66 @@ void Timestamp::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Timestamp::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Timestamp*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // int64 seconds = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int64 value = val;
+ msg->set_seconds(value);
+ break;
+ }
+ // int32 nanos = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_nanos(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Timestamp::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Timestamp)
for (;;) {
@@ -207,8 +239,7 @@ bool Timestamp::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 seconds = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -221,8 +252,7 @@ bool Timestamp::MergePartialFromCodedStream(
// int32 nanos = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -252,6 +282,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Timestamp::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -269,9 +300,9 @@ void Timestamp::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->nanos(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Timestamp)
}
@@ -293,9 +324,9 @@ void Timestamp::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->nanos(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Timestamp)
return target;
@@ -305,11 +336,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// int64 seconds = 1;
if (this->seconds() != 0) {
total_size += 1 +
@@ -333,7 +368,7 @@ void Timestamp::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Timestamp)
GOOGLE_DCHECK_NE(&from, this);
const Timestamp* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Timestamp>(
+ ::google::protobuf::DynamicCastToGenerated<Timestamp>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Timestamp)
@@ -398,14 +433,14 @@ void Timestamp::UnsafeArenaSwap(Timestamp* other) {
}
void Timestamp::InternalSwap(Timestamp* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
swap(seconds_, other->seconds_);
swap(nanos_, other->nanos_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Timestamp::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftimestamp_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftimestamp_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto[kIndexInFileMessages];
}
@@ -414,10 +449,11 @@ void Timestamp::InternalSwap(Timestamp* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Timestamp* Arena::CreateMaybeMessage< ::google::protobuf::Timestamp >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Timestamp >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index 6e79b733..9839e92a 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,30 +32,28 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftimestamp_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftimestamp_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftimestamp_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[1]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2ftimestamp_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2ftimestamp_2eproto();
namespace google {
namespace protobuf {
class Timestamp;
class TimestampDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*);
+PROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Timestamp* Arena::CreateMaybeMessage<::google::protobuf::Timestamp>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -62,7 +61,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ {
+class PROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ {
public:
Timestamp();
virtual ~Timestamp();
@@ -94,7 +93,9 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Timestamp& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -128,8 +129,13 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -175,6 +181,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
// @@protoc_insertion_point(class_scope:google.protobuf.Timestamp)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -183,7 +190,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftimestamp_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftimestamp_2eproto;
};
// ===================================================================
@@ -198,7 +205,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
// int64 seconds = 1;
inline void Timestamp::clear_seconds() {
- seconds_ = GOOGLE_LONGLONG(0);
+ seconds_ = PROTOBUF_LONGLONG(0);
}
inline ::google::protobuf::int64 Timestamp::seconds() const {
// @@protoc_insertion_point(field_get:google.protobuf.Timestamp.seconds)
@@ -235,4 +242,5 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto
diff --git a/src/google/protobuf/timestamp.proto b/src/google/protobuf/timestamp.proto
index eafb3fa0..3faa3ab7 100644
--- a/src/google/protobuf/timestamp.proto
+++ b/src/google/protobuf/timestamp.proto
@@ -116,7 +116,7 @@ option objc_class_prefix = "GPB";
// 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--
+// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
// ) to obtain a formatter capable of generating timestamps in this format.
//
//
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index 130af52a..2d00a8ff 100644
--- a/src/google/protobuf/type.pb.cc
+++ b/src/google/protobuf/type.pb.cc
@@ -6,61 +6,46 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
-namespace protobuf_google_2fprotobuf_2fany_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any;
-} // namespace protobuf_google_2fprotobuf_2fany_2eproto
-namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext;
-} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto
-namespace protobuf_google_2fprotobuf_2ftype_2eproto {
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Field;
-extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option;
-} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Field_google_2fprotobuf_2ftype_2eproto;
+extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto;
namespace google {
namespace protobuf {
class TypeDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Type>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Type> _instance;
} _Type_default_instance_;
class FieldDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Field>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Field> _instance;
} _Field_default_instance_;
class EnumDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Enum>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Enum> _instance;
} _Enum_default_instance_;
class EnumValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<EnumValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<EnumValue> _instance;
} _EnumValue_default_instance_;
class OptionDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Option>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Option> _instance;
} _Option_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2ftype_2eproto {
-static void InitDefaultsType() {
+static void InitDefaultsType_google_2fprotobuf_2ftype_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -71,13 +56,13 @@ static void InitDefaultsType() {
::google::protobuf::Type::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Type =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsType}, {
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base,
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,
- &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Type_google_2fprotobuf_2ftype_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsType_google_2fprotobuf_2ftype_2eproto}, {
+ &scc_info_Field_google_2fprotobuf_2ftype_2eproto.base,
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,
+ &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base,}};
-static void InitDefaultsField() {
+static void InitDefaultsField_google_2fprotobuf_2ftype_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -88,11 +73,11 @@ static void InitDefaultsField() {
::google::protobuf::Field::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Field =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsField}, {
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Field_google_2fprotobuf_2ftype_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsField_google_2fprotobuf_2ftype_2eproto}, {
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}};
-static void InitDefaultsEnum() {
+static void InitDefaultsEnum_google_2fprotobuf_2ftype_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -103,13 +88,13 @@ static void InitDefaultsEnum() {
::google::protobuf::Enum::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Enum =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnum}, {
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base,
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,
- &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<3> scc_info_Enum_google_2fprotobuf_2ftype_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsEnum_google_2fprotobuf_2ftype_2eproto}, {
+ &scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto.base,
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,
+ &scc_info_SourceContext_google_2fprotobuf_2fsource_5fcontext_2eproto.base,}};
-static void InitDefaultsEnumValue() {
+static void InitDefaultsEnumValue_google_2fprotobuf_2ftype_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -120,11 +105,11 @@ static void InitDefaultsEnumValue() {
::google::protobuf::EnumValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValue}, {
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEnumValue_google_2fprotobuf_2ftype_2eproto}, {
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base,}};
-static void InitDefaultsOption() {
+static void InitDefaultsOption_google_2fprotobuf_2ftype_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -135,75 +120,76 @@ static void InitDefaultsOption() {
::google::protobuf::Option::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Option =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOption}, {
- &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base,}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Option_google_2fprotobuf_2ftype_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsOption_google_2fprotobuf_2ftype_2eproto}, {
+ &scc_info_Any_google_2fprotobuf_2fany_2eproto.base,}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_Type.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Field.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Enum.base);
- ::google::protobuf::internal::InitSCC(&scc_info_EnumValue.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Option.base);
+void InitDefaults_google_2fprotobuf_2ftype_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_Type_google_2fprotobuf_2ftype_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Field_google_2fprotobuf_2ftype_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Enum_google_2fprotobuf_2ftype_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Option_google_2fprotobuf_2ftype_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[5];
-const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[3];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2ftype_2eproto[5];
+const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto[3];
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2ftype_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Type, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, fields_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, oneofs_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, source_context_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Type, syntax_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Field, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, kind_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, cardinality_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, number_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, type_url_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, oneof_index_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, packed_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, json_name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Field, default_value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Enum, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Enum, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Enum, enumvalue_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Enum, options_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Enum, source_context_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Enum, syntax_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::EnumValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValue, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValue, number_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::EnumValue, options_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Option, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Option, name_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Option, value_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Type)},
{ 11, -1, sizeof(::google::protobuf::Field)},
{ 26, -1, sizeof(::google::protobuf::Enum)},
@@ -219,92 +205,74 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Option_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/type.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, file_level_enum_descriptors, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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);
-}
-
-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"
- "\014\n\004name\030\001 \001(\t\022&\n\006fields\030\002 \003(\0132\026.google.p"
- "rotobuf.Field\022\016\n\006oneofs\030\003 \003(\t\022(\n\007options"
- "\030\004 \003(\0132\027.google.protobuf.Option\0226\n\016sourc"
- "e_context\030\005 \001(\0132\036.google.protobuf.Source"
- "Context\022\'\n\006syntax\030\006 \001(\0162\027.google.protobu"
- "f.Syntax\"\325\005\n\005Field\022)\n\004kind\030\001 \001(\0162\033.googl"
- "e.protobuf.Field.Kind\0227\n\013cardinality\030\002 \001"
- "(\0162\".google.protobuf.Field.Cardinality\022\016"
- "\n\006number\030\003 \001(\005\022\014\n\004name\030\004 \001(\t\022\020\n\010type_url"
- "\030\006 \001(\t\022\023\n\013oneof_index\030\007 \001(\005\022\016\n\006packed\030\010 "
- "\001(\010\022(\n\007options\030\t \003(\0132\027.google.protobuf.O"
- "ption\022\021\n\tjson_name\030\n \001(\t\022\025\n\rdefault_valu"
- "e\030\013 \001(\t\"\310\002\n\004Kind\022\020\n\014TYPE_UNKNOWN\020\000\022\017\n\013TY"
- "PE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT6"
- "4\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014"
- "TYPE_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\013TY"
- "PE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXE"
- "D32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020"
- "\021\022\017\n\013TYPE_SINT64\020\022\"t\n\013Cardinality\022\027\n\023CAR"
- "DINALITY_UNKNOWN\020\000\022\030\n\024CARDINALITY_OPTION"
- "AL\020\001\022\030\n\024CARDINALITY_REQUIRED\020\002\022\030\n\024CARDIN"
- "ALITY_REPEATED\020\003\"\316\001\n\004Enum\022\014\n\004name\030\001 \001(\t\022"
- "-\n\tenumvalue\030\002 \003(\0132\032.google.protobuf.Enu"
- "mValue\022(\n\007options\030\003 \003(\0132\027.google.protobu"
- "f.Option\0226\n\016source_context\030\004 \001(\0132\036.googl"
- "e.protobuf.SourceContext\022\'\n\006syntax\030\005 \001(\016"
- "2\027.google.protobuf.Syntax\"S\n\tEnumValue\022\014"
- "\n\004name\030\001 \001(\t\022\016\n\006number\030\002 \001(\005\022(\n\007options\030"
- "\003 \003(\0132\027.google.protobuf.Option\";\n\006Option"
- "\022\014\n\004name\030\001 \001(\t\022#\n\005value\030\002 \001(\0132\024.google.p"
- "rotobuf.Any*.\n\006Syntax\022\021\n\rSYNTAX_PROTO2\020\000"
- "\022\021\n\rSYNTAX_PROTO3\020\001B}\n\023com.google.protob"
- "ufB\tTypeProtoP\001Z/google.golang.org/genpr"
- "oto/protobuf/ptype;ptype\370\001\001\242\002\003GPB\252\002\036Goog"
- "le.Protobuf.WellKnownTypesb\006proto3"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2ftype_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2ftype_2eproto, "google/protobuf/type.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2ftype_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2ftype_2eproto, 5, file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftype_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2ftype_2eproto,
+ "\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"
+ "\014\n\004name\030\001 \001(\t\022&\n\006fields\030\002 \003(\0132\026.google.p"
+ "rotobuf.Field\022\016\n\006oneofs\030\003 \003(\t\022(\n\007options"
+ "\030\004 \003(\0132\027.google.protobuf.Option\0226\n\016sourc"
+ "e_context\030\005 \001(\0132\036.google.protobuf.Source"
+ "Context\022\'\n\006syntax\030\006 \001(\0162\027.google.protobu"
+ "f.Syntax\"\325\005\n\005Field\022)\n\004kind\030\001 \001(\0162\033.googl"
+ "e.protobuf.Field.Kind\0227\n\013cardinality\030\002 \001"
+ "(\0162\".google.protobuf.Field.Cardinality\022\016"
+ "\n\006number\030\003 \001(\005\022\014\n\004name\030\004 \001(\t\022\020\n\010type_url"
+ "\030\006 \001(\t\022\023\n\013oneof_index\030\007 \001(\005\022\016\n\006packed\030\010 "
+ "\001(\010\022(\n\007options\030\t \003(\0132\027.google.protobuf.O"
+ "ption\022\021\n\tjson_name\030\n \001(\t\022\025\n\rdefault_valu"
+ "e\030\013 \001(\t\"\310\002\n\004Kind\022\020\n\014TYPE_UNKNOWN\020\000\022\017\n\013TY"
+ "PE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT6"
+ "4\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014"
+ "TYPE_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\013TY"
+ "PE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXE"
+ "D32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020"
+ "\021\022\017\n\013TYPE_SINT64\020\022\"t\n\013Cardinality\022\027\n\023CAR"
+ "DINALITY_UNKNOWN\020\000\022\030\n\024CARDINALITY_OPTION"
+ "AL\020\001\022\030\n\024CARDINALITY_REQUIRED\020\002\022\030\n\024CARDIN"
+ "ALITY_REPEATED\020\003\"\316\001\n\004Enum\022\014\n\004name\030\001 \001(\t\022"
+ "-\n\tenumvalue\030\002 \003(\0132\032.google.protobuf.Enu"
+ "mValue\022(\n\007options\030\003 \003(\0132\027.google.protobu"
+ "f.Option\0226\n\016source_context\030\004 \001(\0132\036.googl"
+ "e.protobuf.SourceContext\022\'\n\006syntax\030\005 \001(\016"
+ "2\027.google.protobuf.Syntax\"S\n\tEnumValue\022\014"
+ "\n\004name\030\001 \001(\t\022\016\n\006number\030\002 \001(\005\022(\n\007options\030"
+ "\003 \003(\0132\027.google.protobuf.Option\";\n\006Option"
+ "\022\014\n\004name\030\001 \001(\t\022#\n\005value\030\002 \001(\0132\024.google.p"
+ "rotobuf.Any*.\n\006Syntax\022\021\n\rSYNTAX_PROTO2\020\000"
+ "\022\021\n\rSYNTAX_PROTO3\020\001B}\n\023com.google.protob"
+ "ufB\tTypeProtoP\001Z/google.golang.org/genpr"
+ "oto/protobuf/ptype;ptype\370\001\001\242\002\003GPB\252\002\036Goog"
+ "le.Protobuf.WellKnownTypesb\006proto3"
+,
+ "google/protobuf/type.proto", &assign_descriptors_table_google_2fprotobuf_2ftype_2eproto, 1594,
+};
+
+void AddDescriptors_google_2fprotobuf_2ftype_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[2] =
+ {
+ ::AddDescriptors_google_2fprotobuf_2fany_2eproto,
+ ::AddDescriptors_google_2fprotobuf_2fsource_5fcontext_2eproto,
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 1594);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/type.proto", &protobuf_RegisterTypes);
- ::protobuf_google_2fprotobuf_2fany_2eproto::AddDescriptors();
- ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors();
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2ftype_2eproto, deps, 2);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2ftype_2eproto = []() { AddDescriptors_google_2fprotobuf_2ftype_2eproto(); return true; }();
namespace google {
namespace protobuf {
const ::google::protobuf::EnumDescriptor* Field_Kind_descriptor() {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[0];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto[0];
}
bool Field_Kind_IsValid(int value) {
switch (value) {
@@ -358,8 +326,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_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[1];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto[1];
}
bool Field_Cardinality_IsValid(int value) {
switch (value) {
@@ -383,8 +351,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_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return protobuf_google_2fprotobuf_2ftype_2eproto::file_level_enum_descriptors[2];
+ ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto[2];
}
bool Syntax_IsValid(int value) {
switch (value) {
@@ -403,6 +371,15 @@ void Type::InitAsDefaultInstance() {
::google::protobuf::_Type_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
+class Type::HasBitSetters {
+ public:
+ static const ::google::protobuf::SourceContext& source_context(const Type* msg);
+};
+
+const ::google::protobuf::SourceContext&
+Type::HasBitSetters::source_context(const Type* msg) {
+ return *msg->source_context_;
+}
void Type::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -433,8 +410,6 @@ const int Type::kSyntaxFieldNumber;
Type::Type()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Type)
}
@@ -444,7 +419,6 @@ Type::Type(::google::protobuf::Arena* arena)
fields_(arena),
oneofs_(arena),
options_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Type)
@@ -471,6 +445,8 @@ Type::Type(const Type& from)
}
void Type::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Type_google_2fprotobuf_2ftype_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
@@ -492,18 +468,13 @@ void Type::ArenaDtor(void* object) {
Type* _this = reinterpret_cast< Type* >(object);
(void)_this;
}
-void Type::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Type::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Type::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Type::descriptor() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Type& Type::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Type.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Type_google_2fprotobuf_2ftype_2eproto.base);
return *internal_default_instance();
}
@@ -526,9 +497,142 @@ void Type::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Type::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Type*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Type.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.Field fields = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Field::_InternalParse;
+ object = msg->add_fields();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // repeated string oneofs = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Type.oneofs");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->add_oneofs();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.Option options = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 34 && (ptr += 1));
+ break;
+ }
+ // .google.protobuf.SourceContext source_context = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::SourceContext::_InternalParse;
+ object = msg->mutable_source_context();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // .google.protobuf.Syntax syntax = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
+ msg->set_syntax(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Type::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Type)
for (;;) {
@@ -538,8 +642,7 @@ bool Type::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -554,8 +657,7 @@ bool Type::MergePartialFromCodedStream(
// repeated .google.protobuf.Field fields = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_fields()));
} else {
@@ -566,8 +668,7 @@ bool Type::MergePartialFromCodedStream(
// repeated string oneofs = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_oneofs()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -583,8 +684,7 @@ bool Type::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -595,8 +695,7 @@ bool Type::MergePartialFromCodedStream(
// .google.protobuf.SourceContext source_context = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
@@ -607,9 +706,8 @@ bool Type::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -639,6 +737,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Type::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -687,7 +786,7 @@ void Type::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 5, this->_internal_source_context(), output);
+ 5, HasBitSetters::source_context(this), output);
}
// .google.protobuf.Syntax syntax = 6;
@@ -696,9 +795,9 @@ void Type::SerializeWithCachedSizes(
6, this->syntax(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Type)
}
@@ -751,7 +850,7 @@ void Type::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 5, this->_internal_source_context(), deterministic, target);
+ 5, HasBitSetters::source_context(this), deterministic, target);
}
// .google.protobuf.Syntax syntax = 6;
@@ -760,9 +859,9 @@ void Type::SerializeWithCachedSizes(
6, this->syntax(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Type)
return target;
@@ -772,11 +871,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Field fields = 2;
{
unsigned int count = static_cast<unsigned int>(this->fields_size());
@@ -836,7 +939,7 @@ void Type::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Type)
GOOGLE_DCHECK_NE(&from, this);
const Type* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Type>(
+ ::google::protobuf::DynamicCastToGenerated<Type>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Type)
@@ -907,6 +1010,7 @@ void Type::UnsafeArenaSwap(Type* other) {
}
void Type::InternalSwap(Type* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&fields_)->InternalSwap(CastToBase(&other->fields_));
oneofs_.InternalSwap(CastToBase(&other->oneofs_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
@@ -914,12 +1018,11 @@ void Type::InternalSwap(Type* other) {
GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Type::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftype_2eproto[kIndexInFileMessages];
}
@@ -927,6 +1030,10 @@ void Type::InternalSwap(Type* other) {
void Field::InitAsDefaultInstance() {
}
+class Field::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Field::kKindFieldNumber;
const int Field::kCardinalityFieldNumber;
@@ -942,8 +1049,6 @@ const int Field::kDefaultValueFieldNumber;
Field::Field()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Field)
}
@@ -951,7 +1056,6 @@ Field::Field(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Field)
@@ -988,6 +1092,8 @@ Field::Field(const Field& from)
}
void Field::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Field_google_2fprotobuf_2ftype_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -1014,18 +1120,13 @@ void Field::ArenaDtor(void* object) {
Field* _this = reinterpret_cast< Field* >(object);
(void)_this;
}
-void Field::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Field::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Field::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Field::descriptor() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Field& Field::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Field.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Field_google_2fprotobuf_2ftype_2eproto.base);
return *internal_default_instance();
}
@@ -1047,9 +1148,178 @@ void Field::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Field::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Field*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // .google.protobuf.Field.Kind kind = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Field_Kind value = static_cast<::google::protobuf::Field_Kind>(val);
+ msg->set_kind(value);
+ break;
+ }
+ // .google.protobuf.Field.Cardinality cardinality = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Field_Cardinality value = static_cast<::google::protobuf::Field_Cardinality>(val);
+ msg->set_cardinality(value);
+ break;
+ }
+ // int32 number = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_number(value);
+ break;
+ }
+ // string name = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Field.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // string type_url = 6;
+ case 6: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Field.type_url");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_type_url();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // int32 oneof_index = 7;
+ case 7: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_oneof_index(value);
+ break;
+ }
+ // bool packed = 8;
+ case 8: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 64) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_packed(value);
+ break;
+ }
+ // repeated .google.protobuf.Option options = 9;
+ case 9: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 74 && (ptr += 1));
+ break;
+ }
+ // string json_name = 10;
+ case 10: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 82) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Field.json_name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_json_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // string default_value = 11;
+ case 11: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 90) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Field.default_value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_default_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Field::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Field)
for (;;) {
@@ -1059,9 +1329,8 @@ bool Field::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .google.protobuf.Field.Kind kind = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1074,9 +1343,8 @@ bool Field::MergePartialFromCodedStream(
// .google.protobuf.Field.Cardinality cardinality = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1089,8 +1357,7 @@ bool Field::MergePartialFromCodedStream(
// int32 number = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1103,8 +1370,7 @@ bool Field::MergePartialFromCodedStream(
// string name = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1119,8 +1385,7 @@ bool Field::MergePartialFromCodedStream(
// string type_url = 6;
case 6: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1135,8 +1400,7 @@ bool Field::MergePartialFromCodedStream(
// int32 oneof_index = 7;
case 7: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1149,8 +1413,7 @@ bool Field::MergePartialFromCodedStream(
// bool packed = 8;
case 8: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(64u /* 64 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (64 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1163,8 +1426,7 @@ bool Field::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 9;
case 9: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (74 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -1175,8 +1437,7 @@ bool Field::MergePartialFromCodedStream(
// string json_name = 10;
case 10: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (82 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_json_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1191,8 +1452,7 @@ bool Field::MergePartialFromCodedStream(
// string default_value = 11;
case 11: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (90 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_default_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1224,6 +1484,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Field::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1307,9 +1568,9 @@ void Field::SerializeWithCachedSizes(
11, this->default_value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Field)
}
@@ -1400,9 +1661,9 @@ void Field::SerializeWithCachedSizes(
11, this->default_value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Field)
return target;
@@ -1412,11 +1673,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Option options = 9;
{
unsigned int count = static_cast<unsigned int>(this->options_size());
@@ -1496,7 +1761,7 @@ void Field::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Field)
GOOGLE_DCHECK_NE(&from, this);
const Field* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Field>(
+ ::google::protobuf::DynamicCastToGenerated<Field>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Field)
@@ -1583,6 +1848,7 @@ void Field::UnsafeArenaSwap(Field* other) {
}
void Field::InternalSwap(Field* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
@@ -1597,12 +1863,11 @@ void Field::InternalSwap(Field* other) {
swap(number_, other->number_);
swap(oneof_index_, other->oneof_index_);
swap(packed_, other->packed_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Field::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftype_2eproto[kIndexInFileMessages];
}
@@ -1612,6 +1877,15 @@ void Enum::InitAsDefaultInstance() {
::google::protobuf::_Enum_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>(
::google::protobuf::SourceContext::internal_default_instance());
}
+class Enum::HasBitSetters {
+ public:
+ static const ::google::protobuf::SourceContext& source_context(const Enum* msg);
+};
+
+const ::google::protobuf::SourceContext&
+Enum::HasBitSetters::source_context(const Enum* msg) {
+ return *msg->source_context_;
+}
void Enum::unsafe_arena_set_allocated_source_context(
::google::protobuf::SourceContext* source_context) {
if (GetArenaNoVirtual() == NULL) {
@@ -1641,8 +1915,6 @@ const int Enum::kSyntaxFieldNumber;
Enum::Enum()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Enum)
}
@@ -1651,7 +1923,6 @@ Enum::Enum(::google::protobuf::Arena* arena)
_internal_metadata_(arena),
enumvalue_(arena),
options_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Enum)
@@ -1677,6 +1948,8 @@ Enum::Enum(const Enum& from)
}
void Enum::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Enum_google_2fprotobuf_2ftype_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
@@ -1698,18 +1971,13 @@ void Enum::ArenaDtor(void* object) {
Enum* _this = reinterpret_cast< Enum* >(object);
(void)_this;
}
-void Enum::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Enum::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Enum::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Enum::descriptor() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Enum& Enum::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Enum.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Enum_google_2fprotobuf_2ftype_2eproto.base);
return *internal_default_instance();
}
@@ -1731,9 +1999,123 @@ void Enum::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Enum::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Enum*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Enum.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // repeated .google.protobuf.EnumValue enumvalue = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::EnumValue::_InternalParse;
+ object = msg->add_enumvalue();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
+ break;
+ }
+ // repeated .google.protobuf.Option options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ // .google.protobuf.SourceContext source_context = 4;
+ case 4: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::SourceContext::_InternalParse;
+ object = msg->mutable_source_context();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ // .google.protobuf.Syntax syntax = 5;
+ case 5: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::Syntax value = static_cast<::google::protobuf::Syntax>(val);
+ msg->set_syntax(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Enum::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Enum)
for (;;) {
@@ -1743,8 +2125,7 @@ bool Enum::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -1759,8 +2140,7 @@ bool Enum::MergePartialFromCodedStream(
// repeated .google.protobuf.EnumValue enumvalue = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_enumvalue()));
} else {
@@ -1771,8 +2151,7 @@ bool Enum::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -1783,8 +2162,7 @@ bool Enum::MergePartialFromCodedStream(
// .google.protobuf.SourceContext source_context = 4;
case 4: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_source_context()));
} else {
@@ -1795,9 +2173,8 @@ bool Enum::MergePartialFromCodedStream(
// .google.protobuf.Syntax syntax = 5;
case 5: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
- int value;
+ if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
+ int value = 0;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
@@ -1827,6 +2204,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Enum::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1865,7 +2243,7 @@ void Enum::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 4;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 4, this->_internal_source_context(), output);
+ 4, HasBitSetters::source_context(this), output);
}
// .google.protobuf.Syntax syntax = 5;
@@ -1874,9 +2252,9 @@ void Enum::SerializeWithCachedSizes(
5, this->syntax(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Enum)
}
@@ -1919,7 +2297,7 @@ void Enum::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 4, this->_internal_source_context(), deterministic, target);
+ 4, HasBitSetters::source_context(this), deterministic, target);
}
// .google.protobuf.Syntax syntax = 5;
@@ -1928,9 +2306,9 @@ void Enum::SerializeWithCachedSizes(
5, this->syntax(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Enum)
return target;
@@ -1940,11 +2318,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.EnumValue enumvalue = 2;
{
unsigned int count = static_cast<unsigned int>(this->enumvalue_size());
@@ -1996,7 +2378,7 @@ void Enum::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Enum)
GOOGLE_DCHECK_NE(&from, this);
const Enum* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Enum>(
+ ::google::protobuf::DynamicCastToGenerated<Enum>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Enum)
@@ -2066,18 +2448,18 @@ void Enum::UnsafeArenaSwap(Enum* other) {
}
void Enum::InternalSwap(Enum* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&enumvalue_)->InternalSwap(CastToBase(&other->enumvalue_));
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(source_context_, other->source_context_);
swap(syntax_, other->syntax_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Enum::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftype_2eproto[kIndexInFileMessages];
}
@@ -2085,6 +2467,10 @@ void Enum::InternalSwap(Enum* other) {
void EnumValue::InitAsDefaultInstance() {
}
+class EnumValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EnumValue::kNameFieldNumber;
const int EnumValue::kNumberFieldNumber;
@@ -2093,8 +2479,6 @@ const int EnumValue::kOptionsFieldNumber;
EnumValue::EnumValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValue)
}
@@ -2102,7 +2486,6 @@ EnumValue::EnumValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
options_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue)
@@ -2122,6 +2505,8 @@ EnumValue::EnumValue(const EnumValue& from)
}
void EnumValue::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
number_ = 0;
}
@@ -2140,18 +2525,13 @@ void EnumValue::ArenaDtor(void* object) {
EnumValue* _this = reinterpret_cast< EnumValue* >(object);
(void)_this;
}
-void EnumValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void EnumValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void EnumValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* EnumValue::descriptor() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const EnumValue& EnumValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_EnumValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_EnumValue_google_2fprotobuf_2ftype_2eproto.base);
return *internal_default_instance();
}
@@ -2168,9 +2548,90 @@ void EnumValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* EnumValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<EnumValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.EnumValue.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // int32 number = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_number(value);
+ break;
+ }
+ // repeated .google.protobuf.Option options = 3;
+ case 3: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual;
+ do {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Option::_InternalParse;
+ object = msg->add_options();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ if (ptr >= end) break;
+ } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1));
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EnumValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.EnumValue)
for (;;) {
@@ -2180,8 +2641,7 @@ bool EnumValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -2196,8 +2656,7 @@ bool EnumValue::MergePartialFromCodedStream(
// int32 number = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -2210,8 +2669,7 @@ bool EnumValue::MergePartialFromCodedStream(
// repeated .google.protobuf.Option options = 3;
case 3: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
@@ -2239,6 +2697,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EnumValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2270,9 +2729,9 @@ void EnumValue::SerializeWithCachedSizes(
output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.EnumValue)
}
@@ -2308,9 +2767,9 @@ void EnumValue::SerializeWithCachedSizes(
3, this->options(static_cast<int>(i)), deterministic, target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.EnumValue)
return target;
@@ -2320,11 +2779,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// repeated .google.protobuf.Option options = 3;
{
unsigned int count = static_cast<unsigned int>(this->options_size());
@@ -2359,7 +2822,7 @@ void EnumValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValue)
GOOGLE_DCHECK_NE(&from, this);
const EnumValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const EnumValue>(
+ ::google::protobuf::DynamicCastToGenerated<EnumValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.EnumValue)
@@ -2425,16 +2888,16 @@ void EnumValue::UnsafeArenaSwap(EnumValue* other) {
}
void EnumValue::InternalSwap(EnumValue* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&options_)->InternalSwap(CastToBase(&other->options_));
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(number_, other->number_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata EnumValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftype_2eproto[kIndexInFileMessages];
}
@@ -2444,6 +2907,15 @@ void Option::InitAsDefaultInstance() {
::google::protobuf::_Option_default_instance_._instance.get_mutable()->value_ = const_cast< ::google::protobuf::Any*>(
::google::protobuf::Any::internal_default_instance());
}
+class Option::HasBitSetters {
+ public:
+ static const ::google::protobuf::Any& value(const Option* msg);
+};
+
+const ::google::protobuf::Any&
+Option::HasBitSetters::value(const Option* msg) {
+ return *msg->value_;
+}
void Option::unsafe_arena_set_allocated_value(
::google::protobuf::Any* value) {
if (GetArenaNoVirtual() == NULL) {
@@ -2470,15 +2942,12 @@ const int Option::kValueFieldNumber;
Option::Option()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Option)
}
Option::Option(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Option)
@@ -2501,6 +2970,8 @@ Option::Option(const Option& from)
}
void Option::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_Option_google_2fprotobuf_2ftype_2eproto.base);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_ = NULL;
}
@@ -2520,18 +2991,13 @@ void Option::ArenaDtor(void* object) {
Option* _this = reinterpret_cast< Option* >(object);
(void)_this;
}
-void Option::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Option::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Option::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Option::descriptor() {
- ::protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Option& Option::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Option_google_2fprotobuf_2ftype_2eproto.base);
return *internal_default_instance();
}
@@ -2550,9 +3016,77 @@ void Option::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Option::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Option*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string name = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.Option.name");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_name();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ // .google.protobuf.Any value = 2;
+ case 2: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::Any::_InternalParse;
+ object = msg->mutable_value();
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({parser_till_end, object},
+ ptr, newend);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ ptr = newend;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Option::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Option)
for (;;) {
@@ -2562,8 +3096,7 @@ bool Option::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -2578,8 +3111,7 @@ bool Option::MergePartialFromCodedStream(
// .google.protobuf.Any value = 2;
case 2: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_value()));
} else {
@@ -2607,6 +3139,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Option::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2627,12 +3160,12 @@ void Option::SerializeWithCachedSizes(
// .google.protobuf.Any value = 2;
if (this->has_value()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
- 2, this->_internal_value(), output);
+ 2, HasBitSetters::value(this), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Option)
}
@@ -2659,12 +3192,12 @@ void Option::SerializeWithCachedSizes(
if (this->has_value()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
- 2, this->_internal_value(), deterministic, target);
+ 2, HasBitSetters::value(this), deterministic, target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Option)
return target;
@@ -2674,11 +3207,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
@@ -2702,7 +3239,7 @@ void Option::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Option)
GOOGLE_DCHECK_NE(&from, this);
const Option* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Option>(
+ ::google::protobuf::DynamicCastToGenerated<Option>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Option)
@@ -2767,15 +3304,15 @@ void Option::UnsafeArenaSwap(Option* other) {
}
void Option::InternalSwap(Option* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(value_, other->value_);
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata Option::GetMetadata() const {
- protobuf_google_2fprotobuf_2ftype_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2ftype_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2ftype_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2ftype_2eproto[kIndexInFileMessages];
}
@@ -2784,22 +3321,23 @@ void Option::InternalSwap(Option* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Type* Arena::CreateMaybeMessage< ::google::protobuf::Type >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Type* Arena::CreateMaybeMessage< ::google::protobuf::Type >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Type >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Field* Arena::CreateMaybeMessage< ::google::protobuf::Field >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Field* Arena::CreateMaybeMessage< ::google::protobuf::Field >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Field >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Enum* Arena::CreateMaybeMessage< ::google::protobuf::Enum >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Enum* Arena::CreateMaybeMessage< ::google::protobuf::Enum >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Enum >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMaybeMessage< ::google::protobuf::EnumValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::EnumValue* Arena::CreateMaybeMessage< ::google::protobuf::EnumValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::EnumValue >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Option* Arena::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Option* Arena::CreateMaybeMessage< ::google::protobuf::Option >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Option >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index 468c88dc..63d71e6b 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -34,46 +35,44 @@
#include <google/protobuf/any.pb.h>
#include <google/protobuf/source_context.pb.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftype_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[5]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2ftype_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2ftype_2eproto();
namespace google {
namespace protobuf {
class Enum;
class EnumDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_;
+PROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_;
class EnumValue;
class EnumValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern EnumValueDefaultTypeInternal _EnumValue_default_instance_;
+PROTOBUF_EXPORT extern EnumValueDefaultTypeInternal _EnumValue_default_instance_;
class Field;
class FieldDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_;
+PROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_;
class Option;
class OptionDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_;
+PROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_;
class Type;
class TypeDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMaybeMessage<::google::protobuf::Enum>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMaybeMessage<::google::protobuf::EnumValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMaybeMessage<::google::protobuf::Field>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMaybeMessage<::google::protobuf::Option>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMaybeMessage<::google::protobuf::Type>(Arena*);
+PROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::Enum* Arena::CreateMaybeMessage<::google::protobuf::Enum>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::EnumValue* Arena::CreateMaybeMessage<::google::protobuf::EnumValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Field* Arena::CreateMaybeMessage<::google::protobuf::Field>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Option* Arena::CreateMaybeMessage<::google::protobuf::Option>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Type* Arena::CreateMaybeMessage<::google::protobuf::Type>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -99,15 +98,15 @@ enum Field_Kind {
Field_Kind_TYPE_SFIXED64 = 16,
Field_Kind_TYPE_SINT32 = 17,
Field_Kind_TYPE_SINT64 = 18,
- Field_Kind_Field_Kind_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
- Field_Kind_Field_Kind_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
+ Field_Kind_Field_Kind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::min(),
+ Field_Kind_Field_Kind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::max()
};
-LIBPROTOBUF_EXPORT bool Field_Kind_IsValid(int value);
+PROTOBUF_EXPORT bool Field_Kind_IsValid(int value);
const Field_Kind Field_Kind_Kind_MIN = Field_Kind_TYPE_UNKNOWN;
const Field_Kind Field_Kind_Kind_MAX = Field_Kind_TYPE_SINT64;
const int Field_Kind_Kind_ARRAYSIZE = Field_Kind_Kind_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Field_Kind_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Field_Kind_descriptor();
inline const ::std::string& Field_Kind_Name(Field_Kind value) {
return ::google::protobuf::internal::NameOfEnum(
Field_Kind_descriptor(), value);
@@ -122,15 +121,15 @@ enum Field_Cardinality {
Field_Cardinality_CARDINALITY_OPTIONAL = 1,
Field_Cardinality_CARDINALITY_REQUIRED = 2,
Field_Cardinality_CARDINALITY_REPEATED = 3,
- Field_Cardinality_Field_Cardinality_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
- Field_Cardinality_Field_Cardinality_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
+ Field_Cardinality_Field_Cardinality_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::min(),
+ Field_Cardinality_Field_Cardinality_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::max()
};
-LIBPROTOBUF_EXPORT bool Field_Cardinality_IsValid(int value);
+PROTOBUF_EXPORT bool Field_Cardinality_IsValid(int value);
const Field_Cardinality Field_Cardinality_Cardinality_MIN = Field_Cardinality_CARDINALITY_UNKNOWN;
const Field_Cardinality Field_Cardinality_Cardinality_MAX = Field_Cardinality_CARDINALITY_REPEATED;
const int Field_Cardinality_Cardinality_ARRAYSIZE = Field_Cardinality_Cardinality_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Field_Cardinality_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Field_Cardinality_descriptor();
inline const ::std::string& Field_Cardinality_Name(Field_Cardinality value) {
return ::google::protobuf::internal::NameOfEnum(
Field_Cardinality_descriptor(), value);
@@ -143,15 +142,15 @@ inline bool Field_Cardinality_Parse(
enum Syntax {
SYNTAX_PROTO2 = 0,
SYNTAX_PROTO3 = 1,
- Syntax_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
- Syntax_INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
+ Syntax_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::min(),
+ Syntax_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits<::google::protobuf::int32>::max()
};
-LIBPROTOBUF_EXPORT bool Syntax_IsValid(int value);
+PROTOBUF_EXPORT bool Syntax_IsValid(int value);
const Syntax Syntax_MIN = SYNTAX_PROTO2;
const Syntax Syntax_MAX = SYNTAX_PROTO3;
const int Syntax_ARRAYSIZE = Syntax_MAX + 1;
-LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Syntax_descriptor();
+PROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* Syntax_descriptor();
inline const ::std::string& Syntax_Name(Syntax value) {
return ::google::protobuf::internal::NameOfEnum(
Syntax_descriptor(), value);
@@ -163,7 +162,7 @@ inline bool Syntax_Parse(
}
// ===================================================================
-class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Type) */ {
+class PROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Type) */ {
public:
Type();
virtual ~Type();
@@ -195,7 +194,9 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Type& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -229,8 +230,13 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -293,8 +299,8 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
#endif
void add_oneofs(const char* value);
void add_oneofs(const char* value, size_t size);
- const ::google::protobuf::RepeatedPtrField< ::std::string>& oneofs() const;
- ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_oneofs();
+ const ::google::protobuf::RepeatedPtrField<::std::string>& oneofs() const;
+ ::google::protobuf::RepeatedPtrField<::std::string>* mutable_oneofs();
// repeated .google.protobuf.Option options = 4;
int options_size() const;
@@ -321,11 +327,11 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -335,9 +341,6 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
- private:
- const ::google::protobuf::SourceContext& _internal_source_context() const;
- public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
::google::protobuf::SourceContext* mutable_source_context();
@@ -354,23 +357,24 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
// @@protoc_insertion_point(class_scope:google.protobuf.Type)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Field > fields_;
- ::google::protobuf::RepeatedPtrField< ::std::string> oneofs_;
+ ::google::protobuf::RepeatedPtrField<::std::string> oneofs_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ {
+class PROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ {
public:
Field();
virtual ~Field();
@@ -402,7 +406,9 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Field& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -436,8 +442,13 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -584,11 +595,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -607,11 +618,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -630,11 +641,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -653,11 +664,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::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"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -695,6 +706,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
// @@protoc_insertion_point(class_scope:google.protobuf.Field)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -711,11 +723,11 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::int32 oneof_index_;
bool packed_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ {
+class PROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ {
public:
Enum();
virtual ~Enum();
@@ -747,7 +759,9 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Enum& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -781,8 +795,13 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -851,11 +870,11 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -865,9 +884,6 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 4;
- private:
- const ::google::protobuf::SourceContext& _internal_source_context() const;
- public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
::google::protobuf::SourceContext* mutable_source_context();
@@ -884,6 +900,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
// @@protoc_insertion_point(class_scope:google.protobuf.Enum)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -895,11 +912,11 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ {
+class PROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ {
public:
EnumValue();
virtual ~EnumValue();
@@ -931,7 +948,9 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const EnumValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -965,8 +984,13 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1023,11 +1047,11 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1041,6 +1065,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
// @@protoc_insertion_point(class_scope:google.protobuf.EnumValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1050,11 +1075,11 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::int32 number_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ {
+class PROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ {
public:
Option();
virtual ~Option();
@@ -1086,7 +1111,9 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Option& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1120,8 +1147,13 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1166,11 +1198,11 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1180,9 +1212,6 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
bool has_value() const;
void clear_value();
static const int kValueFieldNumber = 2;
- private:
- const ::google::protobuf::Any& _internal_value() const;
- public:
const ::google::protobuf::Any& value() const;
::google::protobuf::Any* release_value();
::google::protobuf::Any* mutable_value();
@@ -1193,6 +1222,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
// @@protoc_insertion_point(class_scope:google.protobuf.Option)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1201,7 +1231,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::Any* value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2ftype_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto;
};
// ===================================================================
@@ -1377,12 +1407,12 @@ inline 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)
}
-inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
+inline const ::google::protobuf::RepeatedPtrField<::std::string>&
Type::oneofs() const {
// @@protoc_insertion_point(field_list:google.protobuf.Type.oneofs)
return oneofs_;
}
-inline ::google::protobuf::RepeatedPtrField< ::std::string>*
+inline ::google::protobuf::RepeatedPtrField<::std::string>*
Type::mutable_oneofs() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.oneofs)
return &oneofs_;
@@ -1422,9 +1452,6 @@ Type::options() const {
inline bool Type::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
-inline const ::google::protobuf::SourceContext& Type::_internal_source_context() const {
- return *source_context_;
-}
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)
@@ -2037,9 +2064,6 @@ Enum::options() const {
inline bool Enum::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
-inline const ::google::protobuf::SourceContext& Enum::_internal_source_context() const {
- return *source_context_;
-}
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)
@@ -2311,9 +2335,6 @@ inline void Option::unsafe_arena_set_allocated_name(
inline bool Option::has_value() const {
return this != internal_default_instance() && value_ != NULL;
}
-inline const ::google::protobuf::Any& Option::_internal_value() const {
- return *value_;
-}
inline const ::google::protobuf::Any& Option::value() const {
const ::google::protobuf::Any* p = value_;
// @@protoc_insertion_point(field_get:google.protobuf.Option.value)
@@ -2406,4 +2427,5 @@ inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::Syntax>() {
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto
diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto
index 84815d42..1c3bf91d 100644
--- a/src/google/protobuf/unittest_proto3.proto
+++ b/src/google/protobuf/unittest_proto3.proto
@@ -206,3 +206,17 @@ enum ForeignEnum {
message TestEmptyMessage {
}
+// Same layout as TestOneof2 in unittest.proto to test unknown enum value
+// parsing behavior in oneof.
+message TestOneof2 {
+ oneof foo {
+ NestedEnum foo_enum = 6;
+ }
+
+ enum NestedEnum {
+ UNKNOWN = 0;
+ FOO = 1;
+ BAR = 2;
+ BAZ = 3;
+ }
+}
diff --git a/src/google/protobuf/unknown_field_set.cc b/src/google/protobuf/unknown_field_set.cc
index 35f24e7a..0226c76b 100644
--- a/src/google/protobuf/unknown_field_set.cc
+++ b/src/google/protobuf/unknown_field_set.cc
@@ -43,6 +43,8 @@
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -317,5 +319,134 @@ uint8* UnknownField::SerializeLengthDelimitedNoTagToArray(uint8* target) const {
return target;
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+namespace internal {
+
+const char* PackedValidEnumParser(const char* begin, const char* end,
+ void* object, ParseContext* ctx) {
+ auto repeated_field = static_cast<RepeatedField<int>*>(object);
+ auto ptr = begin;
+ while (ptr < end) {
+ uint64 varint;
+ ptr = Varint::Parse64(ptr, &varint);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ int val = varint;
+ if (ctx->extra_parse_data().ValidateEnum<UnknownFieldSet>(val))
+ repeated_field->Add(val);
+ }
+ return ptr;
+}
+
+const char* PackedValidEnumParserArg(const char* begin, const char* end,
+ void* object, ParseContext* ctx) {
+ auto repeated_field = static_cast<RepeatedField<int>*>(object);
+ auto ptr = begin;
+ while (ptr < end) {
+ uint64 varint;
+ ptr = Varint::Parse64(ptr, &varint);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ int val = varint;
+ if (ctx->extra_parse_data().ValidateEnumArg<UnknownFieldSet>(val))
+ repeated_field->Add(val);
+ }
+ return ptr;
+}
+
+const char* UnknownGroupParse(const char* begin, const char* end, void* object,
+ ParseContext* ctx) {
+ auto unknown = static_cast<UnknownFieldSet*>(object);
+
+ auto ptr = begin;
+ while (ptr < end) {
+ uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ GOOGLE_PROTOBUF_PARSER_ASSERT((tag >> 3) != 0);
+
+ auto res = UnknownFieldParse(tag, {UnknownGroupParse, unknown}, ptr, end,
+ unknown, ctx);
+ ptr = res.first;
+ if (res.second) break;
+ }
+ return ptr;
+}
+
+std::pair<const char*, bool> UnknownFieldParse(uint64 tag, ParseClosure parent,
+ const char* begin,
+ const char* end,
+ UnknownFieldSet* unknown,
+ ParseContext* ctx) {
+ uint32 size;
+ int depth;
+ void* object;
+ auto ptr = begin;
+
+ uint32 field_num = tag >> 3;
+ GOOGLE_PROTOBUF_ASSERT_RETURN(field_num != 0, std::make_pair(nullptr, true));
+ switch (tag & 7) {
+ case 0: {
+ uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ unknown->AddVarint(field_num, val);
+ break;
+ }
+ case 1: {
+ uint64 val = UNALIGNED_LOAD64(ptr);
+ ptr = ptr + 8;
+ unknown->AddFixed64(field_num, val);
+ break;
+ }
+ case 2: {
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ object = unknown->AddLengthDelimited(field_num);
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ bool ok = ctx->ParseExactRange({StringParser, object}, ptr, newend);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = newend;
+ break;
+ }
+ case 3: {
+ object = unknown->AddGroup(field_num);
+ bool ok = ctx->PrepareGroup(tag, &depth);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ ptr = UnknownGroupParse(ptr, end, object, ctx);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ptr, std::make_pair(nullptr, true));
+ if (ctx->GroupContinues(depth)) goto group_continues;
+ break;
+ }
+ case 4: {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_ASSERT_RETURN(ok, std::make_pair(nullptr, true));
+ return std::make_pair(ptr, true);
+ }
+ case 5: {
+ uint32 val = UNALIGNED_LOAD32(ptr);
+ ptr = ptr + 4;
+ unknown->AddFixed32(field_num, val);
+ break;
+ }
+ default:
+ GOOGLE_PROTOBUF_ASSERT_RETURN(false, std::make_pair(nullptr, true));
+ }
+ return std::make_pair(ptr, false);
+len_delim_till_end:
+ // Length delimited field crosses end
+ return std::make_pair(
+ ctx->StoreAndTailCall(ptr, end, parent, {StringParser, object}, size),
+ true);
+group_continues:
+ GOOGLE_DCHECK(ptr >= end);
+ // Group crossed end and must be continued. Either this a parse failure
+ // or we need to resume on the next chunk and thus save the state.
+ ctx->StoreGroup(parent, {UnknownGroupParse, object}, depth);
+ return std::make_pair(ptr, true);
+}
+
+} // namespace internal
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/unknown_field_set.h b/src/google/protobuf/unknown_field_set.h
index 619855ed..7ba33da5 100644
--- a/src/google/protobuf/unknown_field_set.h
+++ b/src/google/protobuf/unknown_field_set.h
@@ -43,7 +43,19 @@
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/message_lite.h>
+#include <google/protobuf/port.h>
+
+#include <google/protobuf/port_def.inc>
+
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+#include <google/protobuf/parse_context.h>
+#endif
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
namespace google {
namespace protobuf {
@@ -74,7 +86,7 @@ class UnknownField; // below
//
// This class is necessarily tied to the protocol buffer wire format, unlike
// the Reflection interface which is independent of any serialization scheme.
-class LIBPROTOBUF_EXPORT UnknownFieldSet {
+class PROTOBUF_EXPORT UnknownFieldSet {
public:
UnknownFieldSet();
~UnknownFieldSet();
@@ -135,8 +147,8 @@ class LIBPROTOBUF_EXPORT UnknownFieldSet {
void AddVarint(int number, uint64 value);
void AddFixed32(int number, uint32 value);
void AddFixed64(int number, uint64 value);
- void AddLengthDelimited(int number, const string& value);
- string* AddLengthDelimited(int number);
+ void AddLengthDelimited(int number, const std::string& value);
+ std::string* AddLengthDelimited(int number);
UnknownFieldSet* AddGroup(int number);
// Adds an unknown field from another set.
@@ -158,7 +170,7 @@ class LIBPROTOBUF_EXPORT UnknownFieldSet {
bool ParseFromCodedStream(io::CodedInputStream* input);
bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input);
bool ParseFromArray(const void* data, int size);
- inline bool ParseFromString(const string& data) {
+ inline bool ParseFromString(const std::string& data) {
return ParseFromArray(data.data(), static_cast<int>(data.size()));
}
@@ -181,8 +193,34 @@ class LIBPROTOBUF_EXPORT UnknownFieldSet {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UnknownFieldSet);
};
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+namespace internal {
+inline void WriteVarint(uint32 num, uint64 val, UnknownFieldSet* unknown) {
+ unknown->AddVarint(num, val);
+}
+inline void WriteLengthDelimited(uint32 num, StringPiece val,
+ UnknownFieldSet* unknown) {
+ unknown->AddLengthDelimited(num)->assign(val.data(), val.size());
+}
+
+const char* PackedValidEnumParser(const char* begin, const char* end,
+ void* object, ParseContext* ctx);
+const char* PackedValidEnumParserArg(const char* begin, const char* end,
+ void* object, ParseContext* ctx);
+
+const char* UnknownGroupParse(const char* begin, const char* end, void* object,
+ ParseContext* ctx);
+std::pair<const char*, bool> UnknownFieldParse(uint64 tag, ParseClosure parent,
+ const char* begin,
+ const char* end,
+ UnknownFieldSet* unknown,
+ ParseContext* ctx);
+
+} // namespace internal
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+
// Represents one field in an UnknownFieldSet.
-class LIBPROTOBUF_EXPORT UnknownField {
+class PROTOBUF_EXPORT UnknownField {
public:
enum Type {
TYPE_VARINT,
@@ -204,14 +242,14 @@ class LIBPROTOBUF_EXPORT UnknownField {
inline uint64 varint() const;
inline uint32 fixed32() const;
inline uint64 fixed64() const;
- inline const string& length_delimited() const;
+ inline const std::string& length_delimited() const;
inline const UnknownFieldSet& group() const;
inline void set_varint(uint64 value);
inline void set_fixed32(uint32 value);
inline void set_fixed64(uint64 value);
- inline void set_length_delimited(const string& value);
- inline string* mutable_length_delimited();
+ inline void set_length_delimited(const std::string& value);
+ inline std::string* mutable_length_delimited();
inline UnknownFieldSet* mutable_group();
// Serialization API.
@@ -239,7 +277,7 @@ class LIBPROTOBUF_EXPORT UnknownField {
inline void SetType(Type type);
union LengthDelimited {
- string* string_value_;
+ std::string* string_value_;
};
uint32 number_;
@@ -289,7 +327,7 @@ inline UnknownField* UnknownFieldSet::mutable_field(int index) {
}
inline void UnknownFieldSet::AddLengthDelimited(
- int number, const string& value) {
+ int number, const std::string& value) {
AddLengthDelimited(number)->assign(value);
}
@@ -313,7 +351,7 @@ inline uint64 UnknownField::fixed64() const {
assert(type() == TYPE_FIXED64);
return data_.fixed64_;
}
-inline const string& UnknownField::length_delimited() const {
+inline const std::string& UnknownField::length_delimited() const {
assert(type() == TYPE_LENGTH_DELIMITED);
return *data_.length_delimited_.string_value_;
}
@@ -334,11 +372,11 @@ inline void UnknownField::set_fixed64(uint64 value) {
assert(type() == TYPE_FIXED64);
data_.fixed64_ = value;
}
-inline void UnknownField::set_length_delimited(const string& value) {
+inline void UnknownField::set_length_delimited(const std::string& value) {
assert(type() == TYPE_LENGTH_DELIMITED);
data_.length_delimited_.string_value_->assign(value);
}
-inline string* UnknownField::mutable_length_delimited() {
+inline std::string* UnknownField::mutable_length_delimited() {
assert(type() == TYPE_LENGTH_DELIMITED);
return data_.length_delimited_.string_value_;
}
@@ -358,6 +396,7 @@ inline void UnknownField::SetType(Type type) {
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__
diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc
index a64769e7..5dad1d05 100644
--- a/src/google/protobuf/unknown_field_set_unittest.cc
+++ b/src/google/protobuf/unknown_field_set_unittest.cc
@@ -35,6 +35,7 @@
// This test is testing a lot more than just the UnknownFieldSet class. It
// tests handling of unknown fields throughout the system.
+#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/coded_stream.h>
@@ -46,10 +47,10 @@
#include <google/protobuf/stubs/callback.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
-#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+
#include <google/protobuf/stubs/stl_util.h>
namespace google {
@@ -195,13 +196,14 @@ TEST_F(UnknownFieldSetTest, SerializeFastAndSlowAreEquivalent) {
slow_buffer.resize(size);
fast_buffer.resize(size);
- uint8* target = reinterpret_cast<uint8*>(string_as_array(&fast_buffer));
+ uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&fast_buffer));
uint8* result = WireFormat::SerializeUnknownFieldsToArray(
empty_message_.unknown_fields(), target);
EXPECT_EQ(size, result - target);
{
- io::ArrayOutputStream raw_stream(string_as_array(&slow_buffer), size, 1);
+ io::ArrayOutputStream raw_stream(::google::protobuf::string_as_array(&slow_buffer), size,
+ 1);
io::CodedOutputStream output_stream(&raw_stream);
WireFormat::SerializeUnknownFields(empty_message_.unknown_fields(),
&output_stream);
diff --git a/src/google/protobuf/util/delimited_message_util.cc b/src/google/protobuf/util/delimited_message_util.cc
index 3ba930e7..51e99e57 100644
--- a/src/google/protobuf/util/delimited_message_util.cc
+++ b/src/google/protobuf/util/delimited_message_util.cc
@@ -1,5 +1,5 @@
// Adapted from the patch of kenton@google.com (Kenton Varda)
-// See https://github.com/google/protobuf/pull/710 for details.
+// See https://github.com/protocolbuffers/protobuf/pull/710 for details.
#include <google/protobuf/util/delimited_message_util.h>
diff --git a/src/google/protobuf/util/delimited_message_util.h b/src/google/protobuf/util/delimited_message_util.h
index e8a7204a..5f2d94cd 100644
--- a/src/google/protobuf/util/delimited_message_util.h
+++ b/src/google/protobuf/util/delimited_message_util.h
@@ -1,5 +1,5 @@
// Adapted from the patch of kenton@google.com (Kenton Varda)
-// See https://github.com/google/protobuf/pull/710 for details.
+// See https://github.com/protocolbuffers/protobuf/pull/710 for details.
#ifndef GOOGLE_PROTOBUF_UTIL_DELIMITED_MESSAGE_UTIL_H__
#define GOOGLE_PROTOBUF_UTIL_DELIMITED_MESSAGE_UTIL_H__
@@ -10,6 +10,8 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -30,9 +32,11 @@ namespace util {
// 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 PROTOBUF_EXPORT SerializeDelimitedToFileDescriptor(
+ const MessageLite& message, int file_descriptor);
-bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message, std::ostream* output);
+bool PROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message,
+ std::ostream* output);
// Read a single size-delimited message from the given stream. Delimited
// format allows a single file or stream to contain multiple messages,
@@ -46,21 +50,28 @@ bool LIBPROTOBUF_EXPORT SerializeDelimitedToOstream(const MessageLite& message,
// 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 PROTOBUF_EXPORT ParseDelimitedFromZeroCopyStream(
+ MessageLite* message, io::ZeroCopyInputStream* input, bool* clean_eof);
-bool LIBPROTOBUF_EXPORT ParseDelimitedFromCodedStream(MessageLite* message, io::CodedInputStream* input, bool* clean_eof);
+bool PROTOBUF_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 PROTOBUF_EXPORT SerializeDelimitedToZeroCopyStream(
+ const MessageLite& message, io::ZeroCopyOutputStream* output);
-bool LIBPROTOBUF_EXPORT SerializeDelimitedToCodedStream(const MessageLite& message, io::CodedOutputStream* output);
+bool PROTOBUF_EXPORT SerializeDelimitedToCodedStream(
+ const MessageLite& message, io::CodedOutputStream* output);
} // namespace util
} // namespace protobuf
} // namespace google
+#include <google/protobuf/port_undef.inc>
+
#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
index 157a8411..5a311c0d 100644
--- a/src/google/protobuf/util/delimited_message_util_test.cc
+++ b/src/google/protobuf/util/delimited_message_util_test.cc
@@ -1,5 +1,5 @@
// Adapted from the patch of kenton@google.com (Kenton Varda)
-// See https://github.com/google/protobuf/pull/710 for details.
+// See https://github.com/protocolbuffers/protobuf/pull/710 for details.
#include <google/protobuf/util/delimited_message_util.h>
diff --git a/src/google/protobuf/util/field_comparator.cc b/src/google/protobuf/util/field_comparator.cc
index 86ddf06a..ed02ac4a 100644
--- a/src/google/protobuf/util/field_comparator.cc
+++ b/src/google/protobuf/util/field_comparator.cc
@@ -57,11 +57,9 @@ DefaultFieldComparator::DefaultFieldComparator()
DefaultFieldComparator::~DefaultFieldComparator() {}
FieldComparator::ComparisonResult DefaultFieldComparator::Compare(
- const google::protobuf::Message& message_1,
- const google::protobuf::Message& message_2,
- const google::protobuf::FieldDescriptor* field,
- int index_1, int index_2,
- const google::protobuf::util::FieldContext* field_context) {
+ const Message& message_1, const Message& message_2,
+ const FieldDescriptor* field, int index_1, int index_2,
+ const util::FieldContext* field_context) {
const Reflection* reflection_1 = message_1.GetReflection();
const Reflection* reflection_2 = message_2.GetReflection();
@@ -131,11 +129,10 @@ FieldComparator::ComparisonResult DefaultFieldComparator::Compare(
}
}
-bool DefaultFieldComparator::Compare(
- MessageDifferencer* differencer,
- const Message& message1,
- const Message& message2,
- const google::protobuf::util::FieldContext* field_context) {
+bool DefaultFieldComparator::Compare(MessageDifferencer* differencer,
+ const Message& message1,
+ const Message& message2,
+ const util::FieldContext* field_context) {
return differencer->Compare(
message1, message2, field_context->parent_fields());
}
diff --git a/src/google/protobuf/util/field_comparator.h b/src/google/protobuf/util/field_comparator.h
index 27ef4c77..8c952831 100644
--- a/src/google/protobuf/util/field_comparator.h
+++ b/src/google/protobuf/util/field_comparator.h
@@ -39,6 +39,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -55,7 +57,7 @@ class MessageDifferencer;
// Regular users should consider using or subclassing DefaultFieldComparator
// rather than this interface.
// Currently, this does not support comparing unknown fields.
-class LIBPROTOBUF_EXPORT FieldComparator {
+class PROTOBUF_EXPORT FieldComparator {
public:
FieldComparator();
virtual ~FieldComparator();
@@ -82,12 +84,11 @@ class LIBPROTOBUF_EXPORT FieldComparator {
// FieldContext contains information about the specific instances of the
// fields being compared, versus FieldDescriptor which only contains general
// type information about the fields.
- virtual ComparisonResult Compare(
- const google::protobuf::Message& message_1,
- const google::protobuf::Message& message_2,
- const google::protobuf::FieldDescriptor* field,
- int index_1, int index_2,
- const google::protobuf::util::FieldContext* field_context) = 0;
+ virtual ComparisonResult Compare(const Message& message_1,
+ const Message& message_2,
+ const FieldDescriptor* field, int index_1,
+ int index_2,
+ const util::FieldContext* field_context) = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldComparator);
@@ -96,7 +97,7 @@ class LIBPROTOBUF_EXPORT FieldComparator {
// Basic implementation of FieldComparator. Supports three modes of floating
// point value comparison: exact, approximate using MathUtil::AlmostEqual
// method, and arbitrarily precise using MathUtil::WithinFractionOrMargin.
-class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
+class PROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
public:
enum FloatComparison {
EXACT, // Floats and doubles are compared exactly.
@@ -110,14 +111,12 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// Creates new comparator with float comparison set to EXACT.
DefaultFieldComparator();
- virtual ~DefaultFieldComparator();
+ ~DefaultFieldComparator() override;
- virtual ComparisonResult Compare(
- const google::protobuf::Message& message_1,
- const google::protobuf::Message& message_2,
- const google::protobuf::FieldDescriptor* field,
- int index_1, int index_2,
- const google::protobuf::util::FieldContext* field_context);
+ ComparisonResult Compare(const Message& message_1, const Message& message_2,
+ const FieldDescriptor* field, int index_1,
+ int index_2,
+ const util::FieldContext* field_context) override;
void set_float_comparison(FloatComparison float_comparison) {
float_comparison_ = float_comparison;
@@ -159,10 +158,9 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// Compare using the provided message_differencer. For example, a subclass can
// use this method to compare some field in a certain way using the same
// message_differencer instance and the field context.
- bool Compare(MessageDifferencer* differencer,
- const google::protobuf::Message& message1,
- const google::protobuf::Message& message2,
- const google::protobuf::util::FieldContext* field_context);
+ bool Compare(MessageDifferencer* differencer, const Message& message1,
+ const Message& message2,
+ const util::FieldContext* field_context);
private:
// Defines the tolerance for floating point comparison (fraction and margin).
@@ -184,56 +182,53 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
// basic types (instead of submessages). They return true on success. One
// can use ResultFromBoolean() to convert that boolean to a ComparisonResult
// value.
- bool CompareBool(const google::protobuf::FieldDescriptor& field,
- bool value_1, bool value_2) {
+ bool CompareBool(const FieldDescriptor& field, bool value_1, bool value_2) {
return value_1 == value_2;
}
// Uses CompareDoubleOrFloat, a helper function used by both CompareDouble and
// CompareFloat.
- bool CompareDouble(const google::protobuf::FieldDescriptor& field,
- double value_1, double value_2);
+ bool CompareDouble(const FieldDescriptor& field, double value_1,
+ double value_2);
- bool CompareEnum(const google::protobuf::FieldDescriptor& field,
+ bool CompareEnum(const FieldDescriptor& field,
const EnumValueDescriptor* value_1,
const EnumValueDescriptor* value_2);
// Uses CompareDoubleOrFloat, a helper function used by both CompareDouble and
// CompareFloat.
- bool CompareFloat(const google::protobuf::FieldDescriptor& field,
- float value_1, float value_2);
+ bool CompareFloat(const FieldDescriptor& field, float value_1, float value_2);
- bool CompareInt32(const google::protobuf::FieldDescriptor& field,
- int32 value_1, int32 value_2) {
+ bool CompareInt32(const FieldDescriptor& field, int32 value_1,
+ int32 value_2) {
return value_1 == value_2;
}
- bool CompareInt64(const google::protobuf::FieldDescriptor& field,
- int64 value_1, int64 value_2) {
+ bool CompareInt64(const FieldDescriptor& field, int64 value_1,
+ int64 value_2) {
return value_1 == value_2;
}
- bool CompareString(const google::protobuf::FieldDescriptor& field,
- const string& value_1, const string& value_2) {
+ bool CompareString(const FieldDescriptor& field, const std::string& value_1,
+ const std::string& value_2) {
return value_1 == value_2;
}
- bool CompareUInt32(const google::protobuf::FieldDescriptor& field,
- uint32 value_1, uint32 value_2) {
+ bool CompareUInt32(const FieldDescriptor& field, uint32 value_1,
+ uint32 value_2) {
return value_1 == value_2;
}
- bool CompareUInt64(const google::protobuf::FieldDescriptor& field,
- uint64 value_1, uint64 value_2) {
+ bool CompareUInt64(const FieldDescriptor& field, uint64 value_1,
+ uint64 value_2) {
return value_1 == value_2;
}
// This function is used by CompareDouble and CompareFloat to avoid code
// duplication. There are no checks done against types of the values passed,
// but it's likely to fail if passed non-numeric arguments.
- template<typename T>
- bool CompareDoubleOrFloat(const google::protobuf::FieldDescriptor& field,
- T value_1, T value_2);
+ template <typename T>
+ bool CompareDoubleOrFloat(const FieldDescriptor& field, T value_1, T value_2);
// Returns FieldComparator::SAME if boolean_result is true and
// FieldComparator::DIFFERENT otherwise.
@@ -265,6 +260,8 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_FIELD_COMPARATOR_H__
diff --git a/src/google/protobuf/util/field_comparator_test.cc b/src/google/protobuf/util/field_comparator_test.cc
index 249b8d54..00de96d6 100644
--- a/src/google/protobuf/util/field_comparator_test.cc
+++ b/src/google/protobuf/util/field_comparator_test.cc
@@ -38,7 +38,7 @@
// This gtest header is put after mathutil.h intentionally. We have to do
// this because mathutil.h includes mathlimits.h which requires cmath not
// being included to compile on some versions of gcc:
-// https://github.com/google/protobuf/blob/818c5eee08840355d70d2f3bdf1a2f17986a5e70/src/google/protobuf/stubs/mathlimits.h#L48
+// https://github.com/protocolbuffers/protobuf/blob/818c5eee08840355d70d2f3bdf1a2f17986a5e70/src/google/protobuf/stubs/mathlimits.h#L48
// and the opensource version gtest.h header includes cmath transitively
// somehow.
#include <gtest/gtest.h>
@@ -482,7 +482,7 @@ TEST_F(DefaultFieldComparatorTest, RepeatedFieldComparison) {
comparator_.Compare(message_1_, message_2_, field, 1, 0, NULL));
}
+} // namespace
} // namespace util
} // namespace protobuf
-} // namespace
} // namespace google
diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc
index a2e2a388..7cd652b1 100644
--- a/src/google/protobuf/util/field_mask_util.cc
+++ b/src/google/protobuf/util/field_mask_util.cc
@@ -53,7 +53,8 @@ void FieldMaskUtil::FromString(StringPiece str, FieldMask* out) {
}
}
-bool FieldMaskUtil::SnakeCaseToCamelCase(StringPiece input, string* output) {
+bool FieldMaskUtil::SnakeCaseToCamelCase(StringPiece input,
+ string* output) {
output->clear();
bool after_underscore = false;
for (int i = 0; i < input.size(); ++i) {
@@ -82,7 +83,8 @@ bool FieldMaskUtil::SnakeCaseToCamelCase(StringPiece input, string* output) {
return true;
}
-bool FieldMaskUtil::CamelCaseToSnakeCase(StringPiece input, string* output) {
+bool FieldMaskUtil::CamelCaseToSnakeCase(StringPiece input,
+ string* output) {
output->clear();
for (int i = 0; i < input.size(); ++i) {
if (input[i] == '_') {
@@ -158,7 +160,7 @@ bool FieldMaskUtil::GetFieldDescriptors(
return true;
}
-void FieldMaskUtil::InternalGetFieldMaskForAllFields(
+void FieldMaskUtil::GetFieldMaskForAllFields(
const Descriptor* descriptor, FieldMask* out) {
for (int i = 0; i < descriptor->field_count(); ++i) {
out->add_paths(descriptor->field(i)->name());
@@ -228,12 +230,13 @@ class FieldMaskTree {
}
// Trims all fields not specified by this tree from the given message.
- void TrimMessage(Message* message) {
+ // Returns true if the message is modified.
+ bool TrimMessage(Message* message) {
// Do nothing if the tree is empty.
if (root_.children.empty()) {
- return;
+ return false;
}
- TrimMessage(&root_, message);
+ return TrimMessage(&root_, message);
}
private:
@@ -276,7 +279,8 @@ class FieldMaskTree {
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);
+ // Returns true if the message is actually modified
+ bool TrimMessage(const Node* node, Message* message);
Node root_;
@@ -576,26 +580,39 @@ void FieldMaskTree::AddRequiredFieldPath(
}
}
-void FieldMaskTree::TrimMessage(const Node* node, Message* message) {
+bool FieldMaskTree::TrimMessage(const Node* node, Message* message) {
GOOGLE_DCHECK(!node->children.empty());
const Reflection* reflection = message->GetReflection();
const Descriptor* descriptor = message->GetDescriptor();
const int32 field_count = descriptor->field_count();
+ bool modified = false;
for (int index = 0; index < field_count; ++index) {
const FieldDescriptor* field = descriptor->field(index);
std::map<string, Node*>::const_iterator it =
node->children.find(field->name());
if (it == node->children.end()) {
+ if (field->is_repeated()) {
+ if (reflection->FieldSize(*message, field) != 0) {
+ modified = true;
+ }
+ } else {
+ if (reflection->HasField(*message, field)) {
+ modified = true;
+ }
+ }
reflection->ClearField(message, field);
} else {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
Node* child = it->second;
if (!child->children.empty() && reflection->HasField(*message, field)) {
- TrimMessage(child, reflection->MutableMessage(message, field));
+ bool nestedMessageChanged =
+ TrimMessage(child, reflection->MutableMessage(message, field));
+ modified = nestedMessageChanged || modified;
}
}
}
}
+ return modified;
}
} // namespace
@@ -627,9 +644,9 @@ 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) {
+void FieldMaskUtil::Subtract(const Descriptor* descriptor,
+ const FieldMask& mask1, const FieldMask& mask2,
+ FieldMask* out) {
if (mask1.paths().empty()) {
out->Clear();
return;
@@ -643,7 +660,8 @@ void FieldMaskUtil::InternalSubtract(const Descriptor* descriptor,
tree.MergeToFieldMask(out);
}
-bool FieldMaskUtil::IsPathInFieldMask(StringPiece path, const FieldMask& mask) {
+bool FieldMaskUtil::IsPathInFieldMask(StringPiece path,
+ const FieldMask& mask) {
for (int i = 0; i < mask.paths_size(); ++i) {
const string& mask_path = mask.paths(i);
if (path == mask_path) {
@@ -670,15 +688,15 @@ void FieldMaskUtil::MergeMessageTo(const Message& source, const FieldMask& mask,
tree.MergeMessage(source, options, destination);
}
-void FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* destination) {
+bool FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* message) {
// Build a FieldMaskTree and walk through the tree to merge all specified
// fields.
FieldMaskTree tree;
tree.MergeFromFieldMask(mask);
- tree.TrimMessage(GOOGLE_CHECK_NOTNULL(destination));
+ return tree.TrimMessage(GOOGLE_CHECK_NOTNULL(message));
}
-void FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* destination,
+bool FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* message,
const TrimOptions& options) {
// Build a FieldMaskTree and walk through the tree to merge all specified
// fields.
@@ -687,9 +705,9 @@ void FieldMaskUtil::TrimMessage(const FieldMask& mask, Message* destination,
// 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.AddRequiredFieldPath(GOOGLE_CHECK_NOTNULL(message->GetDescriptor()));
}
- tree.TrimMessage(GOOGLE_CHECK_NOTNULL(destination));
+ return tree.TrimMessage(GOOGLE_CHECK_NOTNULL(message));
}
} // namespace util
diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h
index f0299de9..7031442d 100644
--- a/src/google/protobuf/util/field_mask_util.h
+++ b/src/google/protobuf/util/field_mask_util.h
@@ -39,24 +39,26 @@
#include <google/protobuf/field_mask.pb.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
-class LIBPROTOBUF_EXPORT FieldMaskUtil {
+class PROTOBUF_EXPORT FieldMaskUtil {
typedef google::protobuf::FieldMask FieldMask;
public:
// Converts FieldMask to/from string, formatted by separating each path
// with a comma (e.g., "foo_bar,baz.quz").
- static string ToString(const FieldMask& mask);
+ static std::string ToString(const FieldMask& mask);
static void FromString(StringPiece str, FieldMask* out);
// Converts FieldMask to/from string, formatted according to proto3 JSON
// spec for FieldMask (e.g., "fooBar,baz.quz"). If the field name is not
// style conforming (i.e., not snake_case when converted to string, or not
// camelCase when converted from string), the conversion will fail.
- static bool ToJsonString(const FieldMask& mask, string* out);
+ static bool ToJsonString(const FieldMask& mask, std::string* out);
static bool FromJsonString(StringPiece str, FieldMask* out);
// Get the descriptors of the fields which the given path from the message
@@ -96,14 +98,18 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
template <typename T>
static FieldMask GetFieldMaskForAllFields() {
FieldMask out;
- InternalGetFieldMaskForAllFields(T::descriptor(), &out);
+ GetFieldMaskForAllFields(T::descriptor(), &out);
return out;
}
template <typename T>
- PROTOBUF_RUNTIME_DEPRECATED("Use *out = GetFieldMaskForAllFields() instead")
+ PROTOBUF_DEPRECATED_MSG("Use *out = GetFieldMaskForAllFields() instead")
static void GetFieldMaskForAllFields(FieldMask* out) {
- InternalGetFieldMaskForAllFields(T::descriptor(), out);
+ GetFieldMaskForAllFields(T::descriptor(), out);
}
+ // This flavor takes the protobuf type descriptor as an argument.
+ // Useful when the type is not known at compile time.
+ static void GetFieldMaskForAllFields(const Descriptor* descriptor,
+ FieldMask* out);
// Converts a FieldMask to the canonical form. It will:
// 1. Remove paths that are covered by another path. For example,
@@ -124,8 +130,13 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
template <typename T>
static void Subtract(const FieldMask& mask1, const FieldMask& mask2,
FieldMask* out) {
- InternalSubtract(T::descriptor(), mask1, mask2, out);
+ Subtract(T::descriptor(), mask1, mask2, out);
}
+ // This flavor takes the protobuf type descriptor as an argument.
+ // Useful when the type is not known at compile time.
+ static void Subtract(const Descriptor* descriptor,
+ const FieldMask& mask1, const FieldMask& mask2,
+ FieldMask* 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.
@@ -134,21 +145,21 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
static bool IsPathInFieldMask(StringPiece path, const FieldMask& mask);
class MergeOptions;
- // Merges fields specified in a FieldMask into another message. See the
- // comments in MergeOptions regarding compatibility with
- // google/protobuf/field_mask.proto
+ // Merges fields specified in a FieldMask into another message.
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);
+ // Returns true if the message is modified.
+ static bool 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,
+ // Returns true if the message is modified.
+ static bool TrimMessage(const FieldMask& mask, Message* message,
const TrimOptions& options);
private:
@@ -166,7 +177,7 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
// Note that the input can contain characters not allowed in C identifiers.
// For example, "foo_bar,baz_quz" will be converted to "fooBar,bazQuz"
// successfully.
- static bool SnakeCaseToCamelCase(StringPiece input, string* output);
+ static bool SnakeCaseToCamelCase(StringPiece input, std::string* output);
// Converts a field name from camelCase to snake_case:
// 1. Every uppercase letter is converted to lowercase with a additional
// preceding "-".
@@ -179,21 +190,10 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil {
// Note that the input can contain characters not allowed in C identifiers.
// For example, "fooBar,bazQuz" will be converted to "foo_bar,baz_quz"
// successfully.
- static bool CamelCaseToSnakeCase(StringPiece input, string* output);
-
- static void InternalGetFieldMaskForAllFields(const Descriptor* descriptor,
- FieldMask* out);
-
- static void InternalSubtract(const Descriptor* descriptor,
- const FieldMask& mask1, const FieldMask& mask2,
- FieldMask* out);
+ static bool CamelCaseToSnakeCase(StringPiece input, std::string* output);
};
-// Note that for compatibility with the defined behaviour for FieldMask in
-// google/protobuf/field_mask.proto, set replace_message_fields and
-// replace_repeated_fields to 'true'. The default options are not compatible
-// with google/protobuf/field_mask.proto.
-class LIBPROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
+class PROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
public:
MergeOptions()
: replace_message_fields_(false), replace_repeated_fields_(false) {}
@@ -221,7 +221,7 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil::MergeOptions {
bool replace_repeated_fields_;
};
-class LIBPROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
+class PROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
public:
TrimOptions()
: keep_required_fields_(false) {}
@@ -240,6 +240,8 @@ class LIBPROTOBUF_EXPORT FieldMaskUtil::TrimOptions {
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc
index 3ba30aa3..93ad9552 100644
--- a/src/google/protobuf/util/field_mask_util_test.cc
+++ b/src/google/protobuf/util/field_mask_util_test.cc
@@ -747,6 +747,75 @@ TEST(FieldMaskUtilTest, TrimMessage) {
EXPECT_EQ(11, oneof_msg.oneof_uint32());
}
+TEST(FieldMaskUtilTest, TrimMessageReturnValue) {
+ FieldMask mask;
+ TestAllTypes trimed_msg;
+ TestAllTypes default_msg;
+
+ // Field mask on optional field.
+ FieldMaskUtil::FromString("optional_int32", &mask);
+
+ // Verify that if a message is updted by FieldMaskUtil::TrimMessage(), the
+ // function returns true.
+ // Test on primary field.
+ trimed_msg.set_optional_string("abc");
+ EXPECT_TRUE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.DebugString(), default_msg.DebugString());
+ trimed_msg.Clear();
+
+ // Test on repeated primary field.
+ trimed_msg.add_repeated_string("abc");
+ trimed_msg.add_repeated_string("def");
+ EXPECT_TRUE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.DebugString(), default_msg.DebugString());
+ trimed_msg.Clear();
+
+ // Test on nested message.
+ trimed_msg.mutable_optional_nested_message()->set_bb(123);
+ EXPECT_TRUE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.DebugString(), default_msg.DebugString());
+ trimed_msg.Clear();
+
+ // Test on repeated nested message.
+ trimed_msg.add_repeated_nested_message()->set_bb(123);
+ trimed_msg.add_repeated_nested_message()->set_bb(456);
+ EXPECT_TRUE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.DebugString(), default_msg.DebugString());
+ trimed_msg.Clear();
+
+ // Test on oneof field.
+ trimed_msg.set_oneof_uint32(123);
+ EXPECT_TRUE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.DebugString(), default_msg.DebugString());
+ trimed_msg.Clear();
+
+ // If there is no field set other then those whitelisted,
+ // FieldMaskUtil::TrimMessage() should return false.
+ trimed_msg.set_optional_int32(123);
+ EXPECT_FALSE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.optional_int32(), 123);
+ trimed_msg.Clear();
+
+ // Field mask on repated field.
+ FieldMaskUtil::FromString("repeated_string", &mask);
+ trimed_msg.add_repeated_string("abc");
+ trimed_msg.add_repeated_string("def");
+ EXPECT_FALSE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.repeated_string(0), "abc");
+ EXPECT_EQ(trimed_msg.repeated_string(1), "def");
+ trimed_msg.Clear();
+
+ // Field mask on nested message.
+ FieldMaskUtil::FromString("optional_nested_message.bb", &mask);
+ trimed_msg.mutable_optional_nested_message()->set_bb(123);
+ EXPECT_FALSE(FieldMaskUtil::TrimMessage(mask, &trimed_msg));
+ EXPECT_EQ(trimed_msg.optional_nested_message().bb(), 123);
+ trimed_msg.Clear();
+
+ // TODO(b/32443320): field mask on repeated nested message is not yet
+ // supported.
+}
+
} // namespace
} // namespace util
diff --git a/src/google/protobuf/util/internal/constants.h b/src/google/protobuf/util/internal/constants.h
index a018a09e..3ace10cf 100644
--- a/src/google/protobuf/util/internal/constants.h
+++ b/src/google/protobuf/util/internal/constants.h
@@ -96,6 +96,9 @@ const char kAnyType[] = "google.protobuf.Any";
const char kFieldMaskTypeUrl[] =
"type.googleapis.com/google.protobuf.FieldMask";
+// The protobuf option name of jspb.message_id;
+const char kOptionJspbMessageId[] = "jspb.message_id";
+
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/datapiece.cc b/src/google/protobuf/util/internal/datapiece.cc
index 59bc28ae..72b7d17a 100644
--- a/src/google/protobuf/util/internal/datapiece.cc
+++ b/src/google/protobuf/util/internal/datapiece.cc
@@ -43,8 +43,6 @@ namespace protobuf {
namespace util {
namespace converter {
-using google::protobuf::EnumDescriptor;
-using google::protobuf::EnumValueDescriptor;
;
;
;
@@ -130,7 +128,8 @@ StatusOr<int32> DataPiece::ToInt32() const {
}
StatusOr<uint32> DataPiece::ToUint32() const {
- if (type_ == TYPE_STRING) return StringToNumber<uint32>(safe_strtou32);
+ if (type_ == TYPE_STRING)
+ return StringToNumber<uint32>(safe_strtou32);
if (type_ == TYPE_DOUBLE)
return FloatingPointToIntConvertAndCheck<uint32, double>(double_);
@@ -154,7 +153,8 @@ StatusOr<int64> DataPiece::ToInt64() const {
}
StatusOr<uint64> DataPiece::ToUint64() const {
- if (type_ == TYPE_STRING) return StringToNumber<uint64>(safe_strtou64);
+ if (type_ == TYPE_STRING)
+ return StringToNumber<uint64>(safe_strtou64);
if (type_ == TYPE_DOUBLE)
return FloatingPointToIntConvertAndCheck<uint64, double>(double_);
@@ -215,7 +215,7 @@ StatusOr<bool> DataPiece::ToBool() const {
StatusOr<string> DataPiece::ToString() const {
switch (type_) {
case TYPE_STRING:
- return str_.ToString();
+ return string(str_);
case TYPE_BYTES: {
string base64;
Base64Escape(str_, &base64);
@@ -227,7 +227,8 @@ StatusOr<string> DataPiece::ToString() const {
}
}
-string DataPiece::ValueAsStringOrDefault(StringPiece default_string) const {
+string DataPiece::ValueAsStringOrDefault(
+ StringPiece default_string) const {
switch (type_) {
case TYPE_INT32:
return SimpleItoa(i32_);
@@ -253,7 +254,7 @@ string DataPiece::ValueAsStringOrDefault(StringPiece default_string) const {
case TYPE_NULL:
return "null";
default:
- return default_string.ToString();
+ return string(default_string);
}
}
@@ -273,12 +274,13 @@ StatusOr<string> DataPiece::ToBytes() const {
StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
bool use_lower_camel_for_enums,
- bool ignore_unknown_enum_values) const {
+ bool ignore_unknown_enum_values,
+ bool* is_unknown_enum_value) const {
if (type_ == TYPE_NULL) return google::protobuf::NULL_VALUE;
if (type_ == TYPE_STRING) {
// First try the given value as a name.
- string enum_name = str_.ToString();
+ string enum_name = string(str_);
const google::protobuf::EnumValue* value =
FindEnumValueByNameOrNull(enum_type, enum_name);
if (value != nullptr) return value->number();
@@ -307,9 +309,11 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
if (value != nullptr) return value->number();
}
- // If ignore_unknown_enum_values is true an unknown enum value is treated
- // as the default
- if (ignore_unknown_enum_values) return enum_type->enumvalue(0).number();
+ // If ignore_unknown_enum_values is true an unknown enum value is ignored.
+ if (ignore_unknown_enum_values) {
+ *is_unknown_enum_value = true;
+ return enum_type->enumvalue(0).number();
+ }
} else {
// We don't need to check whether the value is actually declared in the
// enum because we preserve unknown enum values as well.
@@ -342,13 +346,14 @@ StatusOr<To> DataPiece::GenericConvert() const {
}
template <typename To>
-StatusOr<To> DataPiece::StringToNumber(bool (*func)(StringPiece, To*)) const {
+StatusOr<To> DataPiece::StringToNumber(bool (*func)(StringPiece,
+ To*)) const {
if (str_.size() > 0 && (str_[0] == ' ' || str_[str_.size() - 1] == ' ')) {
return InvalidArgument(StrCat("\"", str_, "\""));
}
To result;
if (func(str_, &result)) return result;
- return InvalidArgument(StrCat("\"", str_.ToString(), "\""));
+ return InvalidArgument(StrCat("\"", string(str_), "\""));
}
bool DataPiece::DecodeBase64(StringPiece src, string* dest) const {
diff --git a/src/google/protobuf/util/internal/datapiece.h b/src/google/protobuf/util/internal/datapiece.h
index 95b133da..556c0ec4 100644
--- a/src/google/protobuf/util/internal/datapiece.h
+++ b/src/google/protobuf/util/internal/datapiece.h
@@ -37,16 +37,19 @@
#include <google/protobuf/stubs/stringpiece.h>
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class Enum;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
+class ProtoWriter;
// Container for a single piece of data together with its data type.
//
@@ -57,7 +60,7 @@ namespace converter {
// Just like StringPiece, the DataPiece class does not own the storage for
// the actual string or Cord, so it is the user's responsiblity to guarantee
// that the underlying storage is still valid when the DataPiece is accessed.
-class LIBPROTOBUF_EXPORT DataPiece {
+class PROTOBUF_EXPORT DataPiece {
public:
// Identifies data type of the value.
// These are the types supported by DataPiece.
@@ -120,7 +123,7 @@ class LIBPROTOBUF_EXPORT DataPiece {
bool use_strict_base64_decoding() { return use_strict_base64_decoding_; }
StringPiece str() const {
- GOOGLE_LOG_IF(DFATAL, type_ != TYPE_STRING) << "Not a string type.";
+ GOOGLE_LOG_IF(DFATAL, type_ != TYPE_STRING) << "Not a std::string type.";
return str_;
}
@@ -147,13 +150,13 @@ class LIBPROTOBUF_EXPORT DataPiece {
util::StatusOr<bool> ToBool() const;
// Parses, casts or converts the value stored in the DataPiece into a string.
- util::StatusOr<string> ToString() const;
+ util::StatusOr<std::string> ToString() const;
// Tries to convert the value contained in this datapiece to string. If the
// conversion fails, it returns the default_string.
- string ValueAsStringOrDefault(StringPiece default_string) const;
+ std::string ValueAsStringOrDefault(StringPiece default_string) const;
- util::StatusOr<string> ToBytes() const;
+ util::StatusOr<std::string> ToBytes() const;
// Converts a value into protocol buffer enum number. If the value is a
// string, first attempts conversion by name, trying names as follows:
@@ -164,10 +167,13 @@ class LIBPROTOBUF_EXPORT DataPiece {
// If the value is not a string, attempts to convert to a 32-bit integer.
// If none of these succeeds, returns a conversion error status.
util::StatusOr<int> ToEnum(const google::protobuf::Enum* enum_type,
- bool use_lower_camel_for_enums,
- bool ignore_unknown_enum_values) const;
+ bool use_lower_camel_for_enums) const {
+ return ToEnum(enum_type, use_lower_camel_for_enums, false, nullptr);
+ }
private:
+ friend class ProtoWriter;
+
// Disallow implicit constructor.
DataPiece();
@@ -175,6 +181,13 @@ class LIBPROTOBUF_EXPORT DataPiece {
DataPiece(Type type, int32 val)
: type_(type), i32_(val), use_strict_base64_decoding_(false) {}
+ // Same as the ToEnum() method above but with additional flag to ignore
+ // unknown enum values.
+ util::StatusOr<int> ToEnum(const google::protobuf::Enum* enum_type,
+ bool use_lower_camel_for_enums,
+ bool ignore_unknown_enum_values,
+ bool* is_unknown_enum_value) const;
+
// For numeric conversion between
// int32, int64, uint32, uint64, double, float and bool
template <typename To>
@@ -183,10 +196,11 @@ class LIBPROTOBUF_EXPORT DataPiece {
// For conversion from string to
// int32, int64, uint32, uint64, double, float and bool
template <typename To>
- util::StatusOr<To> StringToNumber(bool (*func)(StringPiece, To*)) const;
+ util::StatusOr<To> StringToNumber(bool (*func)(StringPiece,
+ To*)) const;
// Decodes a base64 string. Returns true on success.
- bool DecodeBase64(StringPiece src, string* dest) const;
+ bool DecodeBase64(StringPiece src, std::string* dest) const;
// Helper function to initialize this DataPiece with 'other'.
void InternalCopy(const DataPiece& other);
@@ -215,6 +229,8 @@ class LIBPROTOBUF_EXPORT DataPiece {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_DATAPIECE_H__
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc
index b41feb7a..c1d31012 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc
@@ -30,7 +30,7 @@
#include <google/protobuf/util/internal/default_value_objectwriter.h>
-#include <google/protobuf/stubs/hash.h>
+#include <unordered_map>
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/internal/utility.h>
@@ -48,8 +48,8 @@ namespace {
// passed converter function on the DataPiece created from "value" argument.
// If value is empty or if conversion fails, the default_value is returned.
template <typename T>
-T ConvertTo(StringPiece value, StatusOr<T> (DataPiece::*converter_fn)() const,
- T default_value) {
+T ConvertTo(StringPiece value,
+ StatusOr<T> (DataPiece::*converter_fn)() const, T default_value) {
if (value.empty()) return default_value;
StatusOr<T> result = (DataPiece(value, true).*converter_fn)();
return result.ok() ? result.ValueOrDie() : default_value;
@@ -79,8 +79,8 @@ DefaultValueObjectWriter::~DefaultValueObjectWriter() {
}
}
-DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(StringPiece name,
- bool value) {
+DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBool(
+ StringPiece name, bool value) {
if (current_ == nullptr) {
ow_->RenderBool(name, value);
} else {
@@ -156,7 +156,7 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderString(
} else {
// Since StringPiece is essentially a pointer, takes a copy of "value" to
// avoid ownership issues.
- string_values_.push_back(new string(value.ToString()));
+ string_values_.push_back(new string(value));
RenderDataPiece(name, DataPiece(*string_values_.back(), true));
}
return this;
@@ -193,42 +193,18 @@ void DefaultValueObjectWriter::RegisterFieldScrubCallBack(
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, bool use_ints_for_enums,
- FieldScrubCallBack* field_scrub_callback) {
+ bool suppress_empty_list, bool preserve_proto_field_names,
+ bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback) {
return new Node(name, type, kind, data, is_placeholder, path,
- suppress_empty_list, preserve_proto_field_names, use_ints_for_enums,
- field_scrub_callback);
+ suppress_empty_list, preserve_proto_field_names,
+ use_ints_for_enums, 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, 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_(false),
- use_ints_for_enums_(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, bool use_ints_for_enums,
- FieldScrubCallBack* field_scrub_callback)
+ bool suppress_empty_list, bool preserve_proto_field_names,
+ bool use_ints_for_enums, FieldScrubCallBack* field_scrub_callback)
: name_(name),
type_(type),
kind_(kind),
@@ -337,7 +313,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
return;
}
std::vector<Node*> new_children;
- hash_map<string, int> orig_children_map;
+ std::unordered_map<string, int> orig_children_map;
// Creates a map of child nodes to speed up lookup.
for (int i = 0; i < children_.size(); ++i) {
@@ -359,7 +335,7 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
continue;
}
- hash_map<string, int>::iterator found =
+ std::unordered_map<string, int>::iterator found =
orig_children_map.find(field.name());
// If the child field has already been set, we just add it to the new list
// of children.
@@ -408,13 +384,14 @@ void DefaultValueObjectWriter::Node::PopulateChildren(
// If the child field is of primitive type, sets its data to the default
// value of its type.
- std::unique_ptr<Node> child(new Node(
- preserve_proto_field_names_ ? field.name() : field.json_name(),
- field_type, kind,
- kind == PRIMITIVE ? CreateDefaultDataPieceForField(field, typeinfo, use_ints_for_enums_)
- : DataPiece::NullData(),
- true, path, suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
- field_scrub_callback_));
+ std::unique_ptr<Node> child(
+ new Node(preserve_proto_field_names_ ? field.name() : field.json_name(),
+ field_type, kind,
+ kind == PRIMITIVE ? CreateDefaultDataPieceForField(
+ field, typeinfo, use_ints_for_enums_)
+ : DataPiece::NullData(),
+ true, path, suppress_empty_list_, preserve_proto_field_names_,
+ use_ints_for_enums_, field_scrub_callback_));
new_children.push_back(child.release());
}
// Adds all leftover nodes in children_ to the beginning of new_child.
@@ -438,7 +415,8 @@ void DefaultValueObjectWriter::MaybePopulateChildrenOfAny(Node* node) {
}
DataPiece DefaultValueObjectWriter::FindEnumDefault(
- const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums) {
+ const google::protobuf::Field& field, const TypeInfo* typeinfo,
+ bool use_ints_for_enums) {
if (!field.default_value().empty())
return DataPiece(field.default_value(), true);
@@ -451,12 +429,15 @@ DataPiece DefaultValueObjectWriter::FindEnumDefault(
}
// We treat the first value as the default if none is specified.
return enum_type->enumvalue_size() > 0
- ? (use_ints_for_enums ? DataPiece(enum_type->enumvalue(0).number()) : DataPiece(enum_type->enumvalue(0).name(), true))
+ ? (use_ints_for_enums
+ ? DataPiece(enum_type->enumvalue(0).number())
+ : DataPiece(enum_type->enumvalue(0).name(), true))
: DataPiece::NullData();
}
DataPiece DefaultValueObjectWriter::CreateDefaultDataPieceForField(
- const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums) {
+ const google::protobuf::Field& field, const TypeInfo* typeinfo,
+ bool use_ints_for_enums) {
switch (field.kind()) {
case google::protobuf::Field_Kind_TYPE_DOUBLE: {
return DataPiece(ConvertTo<double>(
@@ -509,10 +490,10 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
StringPiece name) {
if (current_ == nullptr) {
std::vector<string> path;
- root_.reset(CreateNewNode(string(name), &type_, OBJECT,
- DataPiece::NullData(), false, path,
- suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
- field_scrub_callback_.get()));
+ root_.reset(CreateNewNode(
+ string(name), &type_, OBJECT, DataPiece::NullData(), false, path,
+ suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
+ field_scrub_callback_.get()));
root_->PopulateChildren(typeinfo_);
current_ = root_.get();
return this;
@@ -529,8 +510,8 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartObject(
: nullptr),
OBJECT, DataPiece::NullData(), false,
child == nullptr ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
- field_scrub_callback_.get()));
+ suppress_empty_list_, preserve_proto_field_names_,
+ use_ints_for_enums_, field_scrub_callback_.get()));
child = node.get();
current_->AddChild(node.release());
}
@@ -573,8 +554,8 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::StartList(
std::unique_ptr<Node> node(
CreateNewNode(string(name), nullptr, LIST, DataPiece::NullData(), false,
child == nullptr ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
- field_scrub_callback_.get()));
+ suppress_empty_list_, preserve_proto_field_names_,
+ use_ints_for_enums_, field_scrub_callback_.get()));
child = node.get();
current_->AddChild(node.release());
}
@@ -635,8 +616,8 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
std::unique_ptr<Node> node(
CreateNewNode(string(name), nullptr, PRIMITIVE, data, false,
child == nullptr ? current_->path() : child->path(),
- suppress_empty_list_, preserve_proto_field_names_, use_ints_for_enums_,
- field_scrub_callback_.get()));
+ suppress_empty_list_, preserve_proto_field_names_,
+ use_ints_for_enums_, field_scrub_callback_.get()));
current_->AddChild(node.release());
} else {
child->set_data(data);
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.h b/src/google/protobuf/util/internal/default_value_objectwriter.h
index 6e71f9c8..7a8863ca 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.h
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.h
@@ -44,6 +44,8 @@
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -55,7 +57,7 @@ namespace converter {
// ObjectWriter when EndObject() is called on the root object. It also writes
// out all non-repeated primitive fields that haven't been explicitly rendered
// with their default values (0 for numbers, "" for strings, etc).
-class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
+class PROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
public:
// A Callback function to check whether a field needs to be scrubbed.
//
@@ -69,7 +71,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
//
// The Field* should point to the google::protobuf::Field of "c".
typedef ResultCallback2<bool /*return*/,
- const std::vector<string>& /*path of the field*/,
+ const std::vector<std::string>& /*path of the field*/,
const google::protobuf::Field* /*field*/>
FieldScrubCallBack;
@@ -83,35 +85,39 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
virtual ~DefaultValueObjectWriter();
// ObjectWriter methods.
- virtual DefaultValueObjectWriter* StartObject(StringPiece name);
+ DefaultValueObjectWriter* StartObject(StringPiece name) override;
- virtual DefaultValueObjectWriter* EndObject();
+ DefaultValueObjectWriter* EndObject() override;
- virtual DefaultValueObjectWriter* StartList(StringPiece name);
+ DefaultValueObjectWriter* StartList(StringPiece name) override;
- virtual DefaultValueObjectWriter* EndList();
+ DefaultValueObjectWriter* EndList() override;
- virtual DefaultValueObjectWriter* RenderBool(StringPiece name, bool value);
+ DefaultValueObjectWriter* RenderBool(StringPiece name,
+ bool value) override;
- virtual DefaultValueObjectWriter* RenderInt32(StringPiece name, int32 value);
+ DefaultValueObjectWriter* RenderInt32(StringPiece name,
+ int32 value) override;
- virtual DefaultValueObjectWriter* RenderUint32(StringPiece name,
- uint32 value);
+ DefaultValueObjectWriter* RenderUint32(StringPiece name,
+ uint32 value) override;
- virtual DefaultValueObjectWriter* RenderInt64(StringPiece name, int64 value);
+ DefaultValueObjectWriter* RenderInt64(StringPiece name,
+ int64 value) override;
- virtual DefaultValueObjectWriter* RenderUint64(StringPiece name,
- uint64 value);
+ DefaultValueObjectWriter* RenderUint64(StringPiece name,
+ uint64 value) override;
- virtual DefaultValueObjectWriter* RenderDouble(StringPiece name,
- double value);
+ DefaultValueObjectWriter* RenderDouble(StringPiece name,
+ double value) override;
- virtual DefaultValueObjectWriter* RenderFloat(StringPiece name, float value);
+ DefaultValueObjectWriter* RenderFloat(StringPiece name,
+ float value) override;
- virtual DefaultValueObjectWriter* RenderString(StringPiece name,
- StringPiece value);
- virtual DefaultValueObjectWriter* RenderBytes(StringPiece name,
- StringPiece value);
+ DefaultValueObjectWriter* RenderString(StringPiece name,
+ StringPiece value) override;
+ DefaultValueObjectWriter* RenderBytes(StringPiece name,
+ StringPiece value) override;
virtual DefaultValueObjectWriter* RenderNull(StringPiece name);
@@ -130,9 +136,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// If set to true, enums are rendered as ints from output when default values
// are written.
- void set_print_enums_as_ints(bool value) {
- use_ints_for_enums_ = value;
- }
+ void set_print_enums_as_ints(bool value) { use_ints_for_enums_ = value; }
protected:
enum NodeKind {
@@ -144,15 +148,11 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// "Node" represents a node in the tree that holds the input of
// DefaultValueObjectWriter.
- class LIBPROTOBUF_EXPORT Node {
+ class PROTOBUF_EXPORT Node {
public:
- 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,
- FieldScrubCallBack* field_scrub_callback);
- Node(const string& name, const google::protobuf::Type* type, NodeKind kind,
+ Node(const std::string& name, const google::protobuf::Type* type, NodeKind kind,
const DataPiece& data, bool is_placeholder,
- const std::vector<string>& path, bool suppress_empty_list,
+ const std::vector<std::string>& path, bool suppress_empty_list,
bool preserve_proto_field_names, bool use_ints_for_enums,
FieldScrubCallBack* field_scrub_callback);
virtual ~Node() {
@@ -178,9 +178,9 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
virtual void WriteTo(ObjectWriter* ow);
// Accessors
- const string& name() const { return name_; }
+ const std::string& name() const { return name_; }
- const std::vector<string>& path() const { return path_; }
+ const std::vector<std::string>& path() const { return path_; }
const google::protobuf::Type* type() const { return type_; }
@@ -210,7 +210,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
void WriteChildren(ObjectWriter* ow);
// The name of this node.
- string name_;
+ std::string name_;
// google::protobuf::Type of this node. Owned by TypeInfo.
const google::protobuf::Type* type_;
// The kind of this node.
@@ -228,7 +228,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
bool is_placeholder_;
// Path of the field of this node
- std::vector<string> path_;
+ std::vector<std::string> path_;
// Whether to suppress empty list output.
bool suppress_empty_list_;
@@ -248,18 +248,10 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
};
// 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,
+ virtual Node* CreateNewNode(const std::string& name,
const google::protobuf::Type* type, NodeKind kind,
const DataPiece& data, bool is_placeholder,
- const std::vector<string>& path,
+ const std::vector<std::string>& path,
bool suppress_empty_list,
bool preserve_proto_field_names,
bool use_ints_for_enums,
@@ -267,7 +259,14 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// Creates a DataPiece containing the default value of the type of the field.
static DataPiece CreateDefaultDataPieceForField(
- const google::protobuf::Field& field, const TypeInfo* typeinfo, bool use_ints_for_enums);
+ const google::protobuf::Field& field, const TypeInfo* typeinfo) {
+ return CreateDefaultDataPieceForField(field, typeinfo, false);
+ }
+
+ // Same as the above but with a flag to use ints instead of enum names.
+ static DataPiece CreateDefaultDataPieceForField(
+ const google::protobuf::Field& field, const TypeInfo* typeinfo,
+ bool use_ints_for_enums);
protected:
// Returns a pointer to current Node in tree.
@@ -300,7 +299,7 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
// google::protobuf::Type of the root message type.
const google::protobuf::Type& type_;
// Holds copies of strings passed to RenderString.
- std::vector<string*> string_values_;
+ std::vector<std::string*> string_values_;
// The current Node. Owned by its parents.
Node* current_;
@@ -330,6 +329,8 @@ class LIBPROTOBUF_EXPORT DefaultValueObjectWriter : public ObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_DEFAULT_VALUE_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/error_listener.h b/src/google/protobuf/util/internal/error_listener.h
index a19bd3f7..c2b7560d 100644
--- a/src/google/protobuf/util/internal/error_listener.h
+++ b/src/google/protobuf/util/internal/error_listener.h
@@ -42,23 +42,27 @@
#include <google/protobuf/util/internal/location_tracker.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
namespace converter {
// Interface for error listener.
-class LIBPROTOBUF_EXPORT ErrorListener {
+class PROTOBUF_EXPORT ErrorListener {
public:
virtual ~ErrorListener() {}
// Reports an invalid name at the given location.
virtual void InvalidName(const LocationTrackerInterface& loc,
- StringPiece invalid_name, StringPiece message) = 0;
+ StringPiece invalid_name,
+ StringPiece message) = 0;
// Reports an invalid value for a field.
virtual void InvalidValue(const LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value) = 0;
+ StringPiece type_name,
+ StringPiece value) = 0;
// Reports a missing required field.
virtual void MissingField(const LocationTrackerInterface& loc,
@@ -73,19 +77,21 @@ class LIBPROTOBUF_EXPORT ErrorListener {
};
// An error listener that ignores all errors.
-class LIBPROTOBUF_EXPORT NoopErrorListener : public ErrorListener {
+class PROTOBUF_EXPORT NoopErrorListener : public ErrorListener {
public:
NoopErrorListener() {}
- virtual ~NoopErrorListener() {}
+ ~NoopErrorListener() override {}
- virtual void InvalidName(const LocationTrackerInterface& loc,
- StringPiece invalid_name, StringPiece message) {}
+ void InvalidName(const LocationTrackerInterface& loc,
+ StringPiece invalid_name,
+ StringPiece message) override {}
- virtual void InvalidValue(const LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value) {}
+ void InvalidValue(const LocationTrackerInterface& loc,
+ StringPiece type_name,
+ StringPiece value) override {}
- virtual void MissingField(const LocationTrackerInterface& loc,
- StringPiece missing_name) {}
+ void MissingField(const LocationTrackerInterface& loc,
+ StringPiece missing_name) override {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NoopErrorListener);
@@ -95,6 +101,8 @@ class LIBPROTOBUF_EXPORT NoopErrorListener : public ErrorListener {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_ERROR_LISTENER_H__
diff --git a/src/google/protobuf/util/internal/expecting_objectwriter.h b/src/google/protobuf/util/internal/expecting_objectwriter.h
index ae98ddd8..108a15b9 100644
--- a/src/google/protobuf/util/internal/expecting_objectwriter.h
+++ b/src/google/protobuf/util/internal/expecting_objectwriter.h
@@ -54,6 +54,7 @@
#include <google/protobuf/util/internal/object_writer.h>
#include <gmock/gmock.h>
+
namespace google {
namespace protobuf {
namespace util {
@@ -81,7 +82,8 @@ class MockObjectWriter : public ObjectWriter {
MOCK_METHOD2(RenderUint64, ObjectWriter*(StringPiece, uint64));
MOCK_METHOD2(RenderDouble, ObjectWriter*(StringPiece, double));
MOCK_METHOD2(RenderFloat, ObjectWriter*(StringPiece, float));
- MOCK_METHOD2(RenderString, ObjectWriter*(StringPiece, StringPiece));
+ MOCK_METHOD2(RenderString,
+ ObjectWriter*(StringPiece, StringPiece));
MOCK_METHOD2(RenderBytes, ObjectWriter*(StringPiece, StringPiece));
MOCK_METHOD1(RenderNull, ObjectWriter*(StringPiece));
};
@@ -91,9 +93,8 @@ class ExpectingObjectWriter : public ObjectWriter {
explicit ExpectingObjectWriter(MockObjectWriter* mock) : mock_(mock) {}
virtual ObjectWriter* StartObject(StringPiece name) {
- (name.empty()
- ? EXPECT_CALL(*mock_, StartObject(IsEmpty()))
- : EXPECT_CALL(*mock_, StartObject(StrEq(name.ToString()))))
+ (name.empty() ? EXPECT_CALL(*mock_, StartObject(IsEmpty()))
+ : EXPECT_CALL(*mock_, StartObject(StrEq(std::string(name)))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -107,9 +108,8 @@ class ExpectingObjectWriter : public ObjectWriter {
}
virtual ObjectWriter* StartList(StringPiece name) {
- (name.empty()
- ? EXPECT_CALL(*mock_, StartList(IsEmpty()))
- : EXPECT_CALL(*mock_, StartList(StrEq(name.ToString()))))
+ (name.empty() ? EXPECT_CALL(*mock_, StartList(IsEmpty()))
+ : EXPECT_CALL(*mock_, StartList(StrEq(std::string(name)))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -125,8 +125,8 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderBool(StringPiece name, bool value) {
(name.empty()
? EXPECT_CALL(*mock_, RenderBool(IsEmpty(), TypedEq<bool>(value)))
- : EXPECT_CALL(*mock_, RenderBool(StrEq(name.ToString()),
- TypedEq<bool>(value))))
+ : EXPECT_CALL(*mock_,
+ RenderBool(StrEq(std::string(name)), TypedEq<bool>(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -135,8 +135,8 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderInt32(StringPiece name, int32 value) {
(name.empty()
? EXPECT_CALL(*mock_, RenderInt32(IsEmpty(), TypedEq<int32>(value)))
- : EXPECT_CALL(*mock_, RenderInt32(StrEq(name.ToString()),
- TypedEq<int32>(value))))
+ : EXPECT_CALL(*mock_,
+ RenderInt32(StrEq(std::string(name)), TypedEq<int32>(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -145,7 +145,7 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderUint32(StringPiece name, uint32 value) {
(name.empty()
? EXPECT_CALL(*mock_, RenderUint32(IsEmpty(), TypedEq<uint32>(value)))
- : EXPECT_CALL(*mock_, RenderUint32(StrEq(name.ToString()),
+ : EXPECT_CALL(*mock_, RenderUint32(StrEq(std::string(name)),
TypedEq<uint32>(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
@@ -155,8 +155,8 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderInt64(StringPiece name, int64 value) {
(name.empty()
? EXPECT_CALL(*mock_, RenderInt64(IsEmpty(), TypedEq<int64>(value)))
- : EXPECT_CALL(*mock_, RenderInt64(StrEq(name.ToString()),
- TypedEq<int64>(value))))
+ : EXPECT_CALL(*mock_,
+ RenderInt64(StrEq(std::string(name)), TypedEq<int64>(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -165,7 +165,7 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderUint64(StringPiece name, uint64 value) {
(name.empty()
? EXPECT_CALL(*mock_, RenderUint64(IsEmpty(), TypedEq<uint64>(value)))
- : EXPECT_CALL(*mock_, RenderUint64(StrEq(name.ToString()),
+ : EXPECT_CALL(*mock_, RenderUint64(StrEq(std::string(name)),
TypedEq<uint64>(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
@@ -174,9 +174,9 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderDouble(StringPiece name, double value) {
(name.empty()
- ? EXPECT_CALL(*mock_, RenderDouble(IsEmpty(),
- NanSensitiveDoubleEq(value)))
- : EXPECT_CALL(*mock_, RenderDouble(StrEq(name.ToString()),
+ ? EXPECT_CALL(*mock_,
+ RenderDouble(IsEmpty(), NanSensitiveDoubleEq(value)))
+ : EXPECT_CALL(*mock_, RenderDouble(StrEq(std::string(name)),
NanSensitiveDoubleEq(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
@@ -185,21 +185,24 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderFloat(StringPiece name, float value) {
(name.empty()
- ? EXPECT_CALL(*mock_, RenderFloat(IsEmpty(),
- NanSensitiveFloatEq(value)))
- : EXPECT_CALL(*mock_, RenderFloat(StrEq(name.ToString()),
+ ? EXPECT_CALL(*mock_,
+ RenderFloat(IsEmpty(), NanSensitiveFloatEq(value)))
+ : EXPECT_CALL(*mock_, RenderFloat(StrEq(std::string(name)),
NanSensitiveFloatEq(value))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
}
- virtual ObjectWriter* RenderString(StringPiece name, StringPiece value) {
+ virtual ObjectWriter* RenderString(StringPiece name,
+ StringPiece value) {
(name.empty()
- ? EXPECT_CALL(*mock_, RenderString(IsEmpty(),
- TypedEq<StringPiece>(value.ToString())))
- : EXPECT_CALL(*mock_, RenderString(StrEq(name.ToString()),
- TypedEq<StringPiece>(value.ToString()))))
+ ? EXPECT_CALL(*mock_,
+ RenderString(IsEmpty(),
+ TypedEq<StringPiece>(std::string(value))))
+ : EXPECT_CALL(*mock_,
+ RenderString(StrEq(std::string(name)),
+ TypedEq<StringPiece>(std::string(value)))))
.WillOnce(Return(mock_))
.RetiresOnSaturation();
return this;
@@ -218,7 +221,7 @@ class ExpectingObjectWriter : public ObjectWriter {
virtual ObjectWriter* RenderNull(StringPiece name) {
(name.empty() ? EXPECT_CALL(*mock_, RenderNull(IsEmpty()))
- : EXPECT_CALL(*mock_, RenderNull(StrEq(name.ToString())))
+ : EXPECT_CALL(*mock_, RenderNull(StrEq(std::string(name))))
.WillOnce(Return(mock_))
.RetiresOnSaturation());
return this;
@@ -233,6 +236,6 @@ class ExpectingObjectWriter : public ObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_EXPECTING_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/field_mask_utility.cc b/src/google/protobuf/util/internal/field_mask_utility.cc
index 778a4510..b0190127 100644
--- a/src/google/protobuf/util/internal/field_mask_utility.cc
+++ b/src/google/protobuf/util/internal/field_mask_utility.cc
@@ -34,6 +34,8 @@
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/status_macros.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -46,12 +48,13 @@ inline util::Status CallPathSink(PathSinkCallback path_sink,
}
// Appends a FieldMask path segment to a prefix.
-string AppendPathSegmentToPrefix(StringPiece prefix, StringPiece segment) {
+string AppendPathSegmentToPrefix(StringPiece prefix,
+ StringPiece segment) {
if (prefix.empty()) {
- return segment.ToString();
+ return string(segment);
}
if (segment.empty()) {
- return prefix.ToString();
+ return string(prefix);
}
// If the segment is a map key, appends it to the prefix without the ".".
if (StringStartsWith(segment, "[\"")) {
@@ -135,8 +138,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
if (i >= length - 1 || paths[i + 1] != ']') {
return util::Status(
util::error::INVALID_ARGUMENT,
- StrCat("Invalid FieldMask '", paths,
- "'. Map keys should be represented as [\"some_key\"]."));
+ StrCat(
+ "Invalid FieldMask '", paths,
+ "'. Map keys should be represented as [\"some_key\"]."));
}
// The end of the map key ("\"]") has been found.
in_map_key = false;
@@ -147,8 +151,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
paths[i + 1] != ')' && paths[i + 1] != '(') {
return util::Status(
util::error::INVALID_ARGUMENT,
- StrCat("Invalid FieldMask '", paths,
- "'. Map keys should be at the end of a path segment."));
+ StrCat(
+ "Invalid FieldMask '", paths,
+ "'. Map keys should be at the end of a path segment."));
}
is_escaping = false;
continue;
@@ -159,8 +164,9 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
if (i >= length - 1 || paths[i + 1] != '\"') {
return util::Status(
util::error::INVALID_ARGUMENT,
- StrCat("Invalid FieldMask '", paths,
- "'. Map keys should be represented as [\"some_key\"]."));
+ StrCat(
+ "Invalid FieldMask '", paths,
+ "'. Map keys should be represented as [\"some_key\"]."));
}
// "[\"" starts a map key.
in_map_key = true;
@@ -196,21 +202,23 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
return util::Status(
util::error::INVALID_ARGUMENT,
StrCat("Invalid FieldMask '", paths,
- "'. Cannot find matching '(' for all ')'."));
+ "'. Cannot find matching '(' for all ')'."));
}
prefix.pop();
}
previous_position = i + 1;
}
if (in_map_key) {
- return util::Status(util::error::INVALID_ARGUMENT,
- StrCat("Invalid FieldMask '", paths,
- "'. Cannot find matching ']' for all '['."));
+ return util::Status(
+ util::error::INVALID_ARGUMENT,
+ StrCat("Invalid FieldMask '", paths,
+ "'. Cannot find matching ']' for all '['."));
}
if (!prefix.empty()) {
- return util::Status(util::error::INVALID_ARGUMENT,
- StrCat("Invalid FieldMask '", paths,
- "'. Cannot find matching ')' for all '('."));
+ return util::Status(
+ util::error::INVALID_ARGUMENT,
+ StrCat("Invalid FieldMask '", paths,
+ "'. Cannot find matching ')' for all '('."));
}
return util::Status();
}
diff --git a/src/google/protobuf/util/internal/field_mask_utility.h b/src/google/protobuf/util/internal/field_mask_utility.h
index 59f36f75..97755804 100644
--- a/src/google/protobuf/util/internal/field_mask_utility.h
+++ b/src/google/protobuf/util/internal/field_mask_utility.h
@@ -45,14 +45,14 @@ namespace protobuf {
namespace util {
namespace converter {
-typedef string (*ConverterCallback)(StringPiece);
+typedef std::string (*ConverterCallback)(StringPiece);
typedef ResultCallback1<util::Status, StringPiece>* PathSinkCallback;
// Applies a 'converter' to each segment of a FieldMask path and returns the
// result. Quoted strings in the 'path' are copied to the output as-is without
// converting their content. Escaping is supported within quoted strings.
// For example, "ab\"_c" will be returned as "ab\"_c" without any changes.
-string ConvertFieldMaskPath(const StringPiece path,
+std::string ConvertFieldMaskPath(const StringPiece path,
ConverterCallback converter);
// Decodes a compact list of FieldMasks. For example, "a.b,a.c.d,a.c.e" will be
@@ -67,6 +67,6 @@ util::Status DecodeCompactFieldMaskPaths(StringPiece paths,
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_FIELD_MASK_UTILITY_H__
diff --git a/src/google/protobuf/util/internal/json_escaping.cc b/src/google/protobuf/util/internal/json_escaping.cc
index 06b9a7f2..d1673597 100644
--- a/src/google/protobuf/util/internal/json_escaping.cc
+++ b/src/google/protobuf/util/internal/json_escaping.cc
@@ -134,8 +134,8 @@ inline uint16 ToHighSurrogate(uint32 cp) {
// Returns false if we encounter an invalid UTF-8 string. Returns true
// otherwise, including the case when we reach the end of the input (str)
// before a complete unicode code point is read.
-bool ReadCodePoint(StringPiece str, int index,
- uint32 *cp, int* num_left, int *num_read) {
+bool ReadCodePoint(StringPiece str, int index, uint32* cp, int* num_left,
+ int* num_read) {
if (*num_left == 0) {
// Last read was complete. Start reading a new unicode code point.
*cp = static_cast<uint8>(str[index++]);
diff --git a/src/google/protobuf/util/internal/json_escaping.h b/src/google/protobuf/util/internal/json_escaping.h
index 5495c57f..07042f6f 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 // GOOGLE_PROTOBUF_UTIL_INTERNAL__JSON_ESCAPING_H__
diff --git a/src/google/protobuf/util/internal/json_objectwriter.cc b/src/google/protobuf/util/internal/json_objectwriter.cc
index a431177a..c2d3292e 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter.cc
@@ -49,7 +49,7 @@ using strings::ArrayByteSource;
;
JsonObjectWriter::~JsonObjectWriter() {
- if (!element_->is_root()) {
+ if (element_ && !element_->is_root()) {
GOOGLE_LOG(WARNING) << "JsonObjectWriter was not fully closed.";
}
}
@@ -64,7 +64,7 @@ JsonObjectWriter* JsonObjectWriter::StartObject(StringPiece name) {
JsonObjectWriter* JsonObjectWriter::EndObject() {
Pop();
WriteChar('}');
- if (element()->is_root()) NewLine();
+ if (element() && element()->is_root()) NewLine();
return this;
}
@@ -82,11 +82,13 @@ JsonObjectWriter* JsonObjectWriter::EndList() {
return this;
}
-JsonObjectWriter* JsonObjectWriter::RenderBool(StringPiece name, bool value) {
+JsonObjectWriter* JsonObjectWriter::RenderBool(StringPiece name,
+ bool value) {
return RenderSimple(name, value ? "true" : "false");
}
-JsonObjectWriter* JsonObjectWriter::RenderInt32(StringPiece name, int32 value) {
+JsonObjectWriter* JsonObjectWriter::RenderInt32(StringPiece name,
+ int32 value) {
return RenderSimple(name, SimpleItoa(value));
}
@@ -95,7 +97,8 @@ JsonObjectWriter* JsonObjectWriter::RenderUint32(StringPiece name,
return RenderSimple(name, SimpleItoa(value));
}
-JsonObjectWriter* JsonObjectWriter::RenderInt64(StringPiece name, int64 value) {
+JsonObjectWriter* JsonObjectWriter::RenderInt64(StringPiece name,
+ int64 value) {
WritePrefix(name);
WriteChar('"');
stream_->WriteString(SimpleItoa(value));
@@ -122,7 +125,8 @@ JsonObjectWriter* JsonObjectWriter::RenderDouble(StringPiece name,
return RenderString(name, DoubleAsString(value));
}
-JsonObjectWriter* JsonObjectWriter::RenderFloat(StringPiece name, float value) {
+JsonObjectWriter* JsonObjectWriter::RenderFloat(StringPiece name,
+ float value) {
if (MathLimits<float>::IsFinite(value)) {
return RenderSimple(name, SimpleFtoa(value));
}
diff --git a/src/google/protobuf/util/internal/json_objectwriter.h b/src/google/protobuf/util/internal/json_objectwriter.h
index 81644dab..ebfc7fba 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.h
+++ b/src/google/protobuf/util/internal/json_objectwriter.h
@@ -38,6 +38,8 @@
#include <google/protobuf/util/internal/structured_objectwriter.h>
#include <google/protobuf/stubs/bytestream.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -82,14 +84,13 @@ namespace converter {
// uint64 would lose precision if rendered as numbers.
//
// JsonObjectWriter is thread-unsafe.
-class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
+class PROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
public:
- JsonObjectWriter(StringPiece indent_string,
- google::protobuf::io::CodedOutputStream* out)
+ JsonObjectWriter(StringPiece indent_string, io::CodedOutputStream* out)
: element_(new Element(/*parent=*/nullptr, /*is_json_object=*/false)),
stream_(out),
sink_(out),
- indent_string_(indent_string.ToString()),
+ indent_string_(indent_string),
use_websafe_base64_for_bytes_(false) {}
virtual ~JsonObjectWriter();
@@ -105,7 +106,8 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
virtual JsonObjectWriter* RenderUint64(StringPiece name, uint64 value);
virtual JsonObjectWriter* RenderDouble(StringPiece name, double value);
virtual JsonObjectWriter* RenderFloat(StringPiece name, float value);
- virtual JsonObjectWriter* RenderString(StringPiece name, StringPiece value);
+ virtual JsonObjectWriter* RenderString(StringPiece name,
+ StringPiece value);
virtual JsonObjectWriter* RenderBytes(StringPiece name, StringPiece value);
virtual JsonObjectWriter* RenderNull(StringPiece name);
virtual JsonObjectWriter* RenderNullAsEmpty(StringPiece name);
@@ -115,7 +117,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
}
protected:
- class LIBPROTOBUF_EXPORT Element : public BaseElement {
+ class PROTOBUF_EXPORT Element : public BaseElement {
public:
Element(Element* parent, bool is_json_object)
: BaseElement(parent),
@@ -143,22 +145,21 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(Element);
};
- virtual Element* element() { return element_.get(); }
+ Element* element() override { return element_.get(); }
private:
- class LIBPROTOBUF_EXPORT ByteSinkWrapper : public strings::ByteSink {
+ class PROTOBUF_EXPORT ByteSinkWrapper : public strings::ByteSink {
public:
- explicit ByteSinkWrapper(google::protobuf::io::CodedOutputStream* stream)
- : stream_(stream) {}
- virtual ~ByteSinkWrapper() {}
+ explicit ByteSinkWrapper(io::CodedOutputStream* stream) : stream_(stream) {}
+ ~ByteSinkWrapper() override {}
// ByteSink methods.
- virtual void Append(const char* bytes, size_t n) {
+ void Append(const char* bytes, size_t n) override {
stream_->WriteRaw(bytes, n);
}
private:
- google::protobuf::io::CodedOutputStream* stream_;
+ io::CodedOutputStream* stream_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSinkWrapper);
};
@@ -166,7 +167,7 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
// Renders a simple value as a string. By default all non-string Render
// methods convert their argument to a string and call this method. This
// method can then be used to render the simple value without escaping it.
- JsonObjectWriter* RenderSimple(StringPiece name, const string& value) {
+ JsonObjectWriter* RenderSimple(StringPiece name, const std::string& value) {
WritePrefix(name);
stream_->WriteString(value);
return this;
@@ -209,9 +210,9 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
void WriteChar(const char c) { stream_->WriteRaw(&c, sizeof(c)); }
std::unique_ptr<Element> element_;
- google::protobuf::io::CodedOutputStream* stream_;
+ io::CodedOutputStream* stream_;
ByteSinkWrapper sink_;
- const string indent_string_;
+ const std::string indent_string_;
// Whether to use regular or websafe base64 encoding for byte fields. Defaults
// to regular base64 encoding.
@@ -223,6 +224,8 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/json_objectwriter_test.cc b/src/google/protobuf/util/internal/json_objectwriter_test.cc
index 0dc710c7..63636525 100644
--- a/src/google/protobuf/util/internal/json_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter_test.cc
@@ -39,8 +39,8 @@ namespace protobuf {
namespace util {
namespace converter {
-using google::protobuf::io::CodedOutputStream;
-using google::protobuf::io::StringOutputStream;
+using io::CodedOutputStream;
+using io::StringOutputStream;
class JsonObjectWriterTest : public ::testing::Test {
protected:
diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc
index 1c63b31d..e272bbd5 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser.cc
@@ -39,9 +39,10 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/util/internal/object_writer.h>
#include <google/protobuf/util/internal/json_escaping.h>
-#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/mathlimits.h>
@@ -63,6 +64,8 @@ namespace converter {
// Number of digits in an escaped UTF-16 code unit ('\\' 'u' X X X X)
static const int kUnicodeEscapedLength = 6;
+static const int kDefaultMaxRecursionDepth = 100;
+
// Length of the true, false, and null literals.
static const int true_len = strlen("true");
static const int false_len = strlen("false");
@@ -109,7 +112,9 @@ JsonStreamParser::JsonStreamParser(ObjectWriter* ow)
chunk_storage_(),
coerce_to_utf8_(false),
allow_empty_null_(false),
- loose_float_number_conversion_(false) {
+ loose_float_number_conversion_(false),
+ recursion_depth_(0),
+ max_recursion_depth_(kDefaultMaxRecursionDepth) {
// Initialize the stack with a single value to be parsed.
stack_.push(VALUE);
}
@@ -201,7 +206,7 @@ util::Status JsonStreamParser::ParseChunk(StringPiece chunk) {
}
// If we expect future data i.e. stack is non-empty, and we have some
// unparsed data left, we save it for later parse.
- leftover_ = p_.ToString();
+ leftover_ = string(p_);
}
return util::Status();
}
@@ -539,7 +544,7 @@ util::Status JsonStreamParser::ParseNumberHelper(NumberResult* result) {
}
// Create a string containing just the number, so we can use safe_strtoX
- string number = p_.substr(0, index).ToString();
+ string number = string(p_.substr(0, index));
// Floating point number, parse as a double.
if (floating) {
@@ -593,6 +598,10 @@ util::Status JsonStreamParser::HandleBeginObject() {
GOOGLE_DCHECK_EQ('{', *p_.data());
Advance();
ow_->StartObject(key_);
+ auto status = IncrementRecursionDepth(key_);
+ if (!status.ok()) {
+ return status;
+ }
key_ = StringPiece();
stack_.push(ENTRY);
return util::Status();
@@ -607,6 +616,7 @@ util::Status JsonStreamParser::ParseObjectMid(TokenType type) {
if (type == END_OBJECT) {
Advance();
ow_->EndObject();
+ --recursion_depth_;
return util::Status();
}
// Found a comma, advance past it and get ready for an entry.
@@ -628,6 +638,7 @@ util::Status JsonStreamParser::ParseEntry(TokenType type) {
if (type == END_OBJECT) {
ow_->EndObject();
Advance();
+ --recursion_depth_;
return util::Status();
}
@@ -784,6 +795,17 @@ util::Status JsonStreamParser::ReportUnknown(StringPiece message) {
return ReportFailure(message);
}
+util::Status JsonStreamParser::IncrementRecursionDepth(
+ StringPiece key) const {
+ if (++recursion_depth_ > max_recursion_depth_) {
+ return Status(
+ util::error::INVALID_ARGUMENT,
+ StrCat("Message too deep. Max recursion depth reached for key '",
+ key, "'"));
+ }
+ return util::Status();
+}
+
void JsonStreamParser::SkipWhitespace() {
while (!p_.empty() && ascii_isspace(*p_.data())) {
Advance();
diff --git a/src/google/protobuf/util/internal/json_stream_parser.h b/src/google/protobuf/util/internal/json_stream_parser.h
index 31933b67..3526ec57 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.h
+++ b/src/google/protobuf/util/internal/json_stream_parser.h
@@ -38,11 +38,13 @@
#include <google/protobuf/stubs/stringpiece.h>
#include <google/protobuf/stubs/status.h>
-namespace google {
+#include <google/protobuf/port_def.inc>
+
namespace util {
class Status;
} // namespace util
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
@@ -69,7 +71,7 @@ class ObjectWriter;
//
// This parser is thread-compatible as long as only one thread is calling a
// Parse() method at a time.
-class LIBPROTOBUF_EXPORT JsonStreamParser {
+class PROTOBUF_EXPORT JsonStreamParser {
public:
// Creates a JsonStreamParser that will write to the given ObjectWriter.
explicit JsonStreamParser(ObjectWriter* ow);
@@ -83,7 +85,18 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
util::Status FinishParse();
+ // Sets the max recursion depth of JSON message to be deserialized. JSON
+ // messages over this depth will fail to be deserialized.
+ // Default value is 100.
+ void set_max_recursion_depth(int max_depth) {
+ max_recursion_depth_ = max_depth;
+ }
+
private:
+ friend class JsonStreamParserTest;
+ // Return the current recursion depth.
+ const int recursion_depth() { return recursion_depth_; }
+
enum TokenType {
BEGIN_STRING, // " or '
BEGIN_NUMBER, // - or digit
@@ -155,7 +168,7 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
util::Status ParseNumberHelper(NumberResult* result);
// Parse a number as double into a NumberResult.
- util::Status ParseDoubleHelper(const string& number, NumberResult* result);
+ util::Status ParseDoubleHelper(const std::string& number, NumberResult* result);
// Handles a { during parsing of a value.
util::Status HandleBeginObject();
@@ -195,6 +208,11 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// status to return in this case.
util::Status ReportUnknown(StringPiece message);
+ // Helper function to check recursion depth and increment it. It will return
+ // Status::OK if the current depth is allowed. Otherwise an error is returned.
+ // key is used for error reporting.
+ util::Status IncrementRecursionDepth(StringPiece key) const;
+
// Advance p_ past all whitespace or until the end of the string.
void SkipWhitespace();
@@ -216,7 +234,7 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// Contains any leftover text from a previous chunk that we weren't able to
// fully parse, for example the start of a key or number.
- string leftover_;
+ std::string leftover_;
// The current chunk of JSON being parsed. Primarily used for providing
// context during error reporting.
@@ -230,7 +248,7 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// Storage for key_ if we need to keep ownership, for example between chunks
// or if the key was unescaped from a JSON string.
- string key_storage_;
+ std::string key_storage_;
// True during the FinishParse() call, so we know that any errors are fatal.
// For example an unterminated string will normally result in cancelling and
@@ -242,14 +260,14 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// Storage for the string we parsed. This may be empty if the string was able
// to be parsed directly from the input.
- string parsed_storage_;
+ std::string parsed_storage_;
// The character that opened the string, either ' or ".
// A value of 0 indicates that string parsing is not in process.
char string_open_;
// Storage for the chunk that are being parsed in ParseChunk().
- string chunk_storage_;
+ std::string chunk_storage_;
// Whether to allow non UTF-8 encoded input and replace invalid code points.
bool coerce_to_utf8_;
@@ -261,12 +279,20 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// Whether allows out-of-range floating point numbers or reject them.
bool loose_float_number_conversion_;
+ // Tracks current recursion depth.
+ mutable int recursion_depth_;
+
+ // Maximum allowed recursion depth.
+ int max_recursion_depth_;
+
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(JsonStreamParser);
};
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_JSON_STREAM_PARSER_H__
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 a11e9be0..764c9f71 100644
--- a/src/google/protobuf/util/internal/json_stream_parser_test.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser_test.cc
@@ -37,6 +37,7 @@
#include <google/protobuf/util/internal/object_writer.h>
#include <google/protobuf/stubs/strutil.h>
#include <gtest/gtest.h>
+
#include <google/protobuf/stubs/status.h>
@@ -88,8 +89,8 @@ class JsonStreamParserTest : public ::testing::Test {
JsonStreamParserTest() : mock_(), ow_(&mock_) {}
virtual ~JsonStreamParserTest() {}
- util::Status RunTest(StringPiece json, int split, bool coerce_utf8 = false,
- bool allow_empty_null = false,
+ util::Status RunTest(StringPiece json, int split,
+ bool coerce_utf8 = false, bool allow_empty_null = false,
bool loose_float_number_conversion = false) {
JsonStreamParser parser(&mock_);
@@ -117,6 +118,9 @@ class JsonStreamParserTest : public ::testing::Test {
result = parser.FinishParse();
}
}
+ if (result.ok()){
+ EXPECT_EQ(parser.recursion_depth(), 0);
+ }
return result;
}
@@ -131,8 +135,9 @@ class JsonStreamParserTest : public ::testing::Test {
EXPECT_OK(result);
}
- void DoErrorTest(StringPiece json, int split, StringPiece error_prefix,
- bool coerce_utf8 = false, bool allow_empty_null = false) {
+ void DoErrorTest(StringPiece json, int split,
+ StringPiece error_prefix, bool coerce_utf8 = false,
+ bool allow_empty_null = false) {
util::Status result =
RunTest(json, split, coerce_utf8, allow_empty_null);
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.error_code());
@@ -838,6 +843,49 @@ TEST_F(JsonStreamParserTest, UnknownCharactersInObject) {
}
}
+TEST_F(JsonStreamParserTest, DeepNestJsonNotExceedLimit) {
+ int count = 99;
+ string str;
+ for (int i = 0; i < count; ++i) {
+ StrAppend(&str, "{'a':");
+ }
+ StrAppend(&str, "{'nest64':'v1', 'nest64': false, 'nest64': ['v2']}");
+ for (int i = 0; i < count; ++i) {
+ StrAppend(&str, "}");
+ }
+ ow_.StartObject("");
+ for (int i = 0; i < count; ++i) {
+ ow_.StartObject("a");
+ }
+ ow_.RenderString("nest64", "v1")
+ ->RenderBool("nest64", false)
+ ->StartList("nest64")
+ ->RenderString("", "v2")
+ ->EndList();
+ for (int i = 0; i < count; ++i) {
+ ow_.EndObject();
+ }
+ ow_.EndObject();
+ DoTest(str, 0);
+}
+
+TEST_F(JsonStreamParserTest, DeepNestJsonExceedLimit) {
+ int count = 98;
+ string str;
+ for (int i = 0; i < count; ++i) {
+ StrAppend(&str, "{'a':");
+ }
+ // Supports trailing commas.
+ StrAppend(&str,
+ "{'nest11' : [{'nest12' : null,},],"
+ "'nest21' : {'nest22' : {'nest23' : false}}}");
+ for (int i = 0; i < count; ++i) {
+ StrAppend(&str, "}");
+ }
+ DoErrorTest(str, 0,
+ "Message too deep. Max recursion depth reached for key 'nest22'");
+}
+
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/location_tracker.h b/src/google/protobuf/util/internal/location_tracker.h
index 0864b057..c29a75a7 100644
--- a/src/google/protobuf/util/internal/location_tracker.h
+++ b/src/google/protobuf/util/internal/location_tracker.h
@@ -35,6 +35,8 @@
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -42,12 +44,12 @@ namespace converter {
// LocationTrackerInterface is an interface for classes that track
// the location information for the purpose of error reporting.
-class LIBPROTOBUF_EXPORT LocationTrackerInterface {
+class PROTOBUF_EXPORT LocationTrackerInterface {
public:
virtual ~LocationTrackerInterface() {}
// Returns the object location as human readable string.
- virtual string ToString() const = 0;
+ virtual std::string ToString() const = 0;
protected:
LocationTrackerInterface() {}
@@ -60,6 +62,8 @@ class LIBPROTOBUF_EXPORT LocationTrackerInterface {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_LOCATION_TRACKER_H__
diff --git a/src/google/protobuf/util/internal/mock_error_listener.h b/src/google/protobuf/util/internal/mock_error_listener.h
index 591c35db..1f1321f2 100644
--- a/src/google/protobuf/util/internal/mock_error_listener.h
+++ b/src/google/protobuf/util/internal/mock_error_listener.h
@@ -31,11 +31,11 @@
#ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__
-#include <google/protobuf/stubs/stringpiece.h>
#include <google/protobuf/util/internal/error_listener.h>
#include <google/protobuf/util/internal/location_tracker.h>
#include <gmock/gmock.h>
+
namespace google {
namespace protobuf {
namespace util {
@@ -46,11 +46,12 @@ class MockErrorListener : public ErrorListener {
MockErrorListener() {}
virtual ~MockErrorListener() {}
- MOCK_METHOD3(InvalidName, void(const LocationTrackerInterface& loc,
- StringPiece unknown_name,
- StringPiece message));
- MOCK_METHOD3(InvalidValue, void(const LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value));
+ MOCK_METHOD3(InvalidName,
+ void(const LocationTrackerInterface& loc,
+ StringPiece unknown_name, StringPiece message));
+ MOCK_METHOD3(InvalidValue,
+ void(const LocationTrackerInterface& loc,
+ StringPiece type_name, StringPiece value));
MOCK_METHOD2(MissingField, void(const LocationTrackerInterface& loc,
StringPiece missing_name));
};
@@ -58,6 +59,6 @@ class MockErrorListener : public ErrorListener {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__
diff --git a/src/google/protobuf/util/internal/object_location_tracker.h b/src/google/protobuf/util/internal/object_location_tracker.h
index 8586cecc..571279d5 100644
--- a/src/google/protobuf/util/internal/object_location_tracker.h
+++ b/src/google/protobuf/util/internal/object_location_tracker.h
@@ -47,10 +47,10 @@ class ObjectLocationTracker : public LocationTrackerInterface {
// Creates an empty location tracker.
ObjectLocationTracker() {}
- virtual ~ObjectLocationTracker() {}
+ ~ObjectLocationTracker() override {}
// Returns empty because nothing is tracked.
- virtual string ToString() const { return ""; }
+ std::string ToString() const override { return ""; }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjectLocationTracker);
@@ -59,6 +59,6 @@ class ObjectLocationTracker : public LocationTrackerInterface {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_OBJECT_LOCATION_TRACKER_H__
diff --git a/src/google/protobuf/util/internal/object_source.h b/src/google/protobuf/util/internal/object_source.h
index 2c31cfb0..c8ee36fb 100644
--- a/src/google/protobuf/util/internal/object_source.h
+++ b/src/google/protobuf/util/internal/object_source.h
@@ -35,6 +35,8 @@
#include <google/protobuf/stubs/stringpiece.h>
#include <google/protobuf/stubs/status.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -48,7 +50,7 @@ class ObjectWriter;
// example, a character stream, or protobuf.
//
// Derived classes could be thread-unsafe.
-class LIBPROTOBUF_EXPORT ObjectSource {
+class PROTOBUF_EXPORT ObjectSource {
public:
virtual ~ObjectSource() {}
@@ -74,6 +76,8 @@ class LIBPROTOBUF_EXPORT ObjectSource {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_OBJECT_SOURCE_H__
diff --git a/src/google/protobuf/util/internal/object_writer.cc b/src/google/protobuf/util/internal/object_writer.cc
index 57cc08a1..bb1b3e57 100644
--- a/src/google/protobuf/util/internal/object_writer.cc
+++ b/src/google/protobuf/util/internal/object_writer.cc
@@ -38,8 +38,8 @@ namespace util {
namespace converter {
// static
-void ObjectWriter::RenderDataPieceTo(const DataPiece& data, StringPiece name,
- ObjectWriter* ow) {
+void ObjectWriter::RenderDataPieceTo(const DataPiece& data,
+ StringPiece name, ObjectWriter* ow) {
switch (data.type()) {
case DataPiece::TYPE_INT32: {
ow->RenderInt32(name, data.ToInt32().ValueOrDie());
diff --git a/src/google/protobuf/util/internal/object_writer.h b/src/google/protobuf/util/internal/object_writer.h
index 5781aa1e..a4b509da 100644
--- a/src/google/protobuf/util/internal/object_writer.h
+++ b/src/google/protobuf/util/internal/object_writer.h
@@ -34,6 +34,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -55,7 +57,7 @@ class DataPiece;
//
// TODO(xinb): seems like a prime candidate to apply the RAII paradigm
// and get rid the need to call EndXXX().
-class LIBPROTOBUF_EXPORT ObjectWriter {
+class PROTOBUF_EXPORT ObjectWriter {
public:
virtual ~ObjectWriter() {}
@@ -93,7 +95,8 @@ class LIBPROTOBUF_EXPORT ObjectWriter {
virtual ObjectWriter* RenderFloat(StringPiece name, float value) = 0;
// Renders a StringPiece value. This is for rendering strings.
- virtual ObjectWriter* RenderString(StringPiece name, StringPiece value) = 0;
+ virtual ObjectWriter* RenderString(StringPiece name,
+ StringPiece value) = 0;
// Renders a bytes value.
virtual ObjectWriter* RenderBytes(StringPiece name, StringPiece value) = 0;
@@ -134,6 +137,8 @@ class LIBPROTOBUF_EXPORT ObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_OBJECT_WRITER_H__
diff --git a/src/google/protobuf/util/internal/proto_writer.cc b/src/google/protobuf/util/internal/proto_writer.cc
index b7a52db6..56ee774a 100644
--- a/src/google/protobuf/util/internal/proto_writer.cc
+++ b/src/google/protobuf/util/internal/proto_writer.cc
@@ -45,16 +45,18 @@
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
namespace converter {
-using google::protobuf::internal::WireFormatLite;
-using google::protobuf::io::CodedOutputStream;
-using util::error::INVALID_ARGUMENT;
+using io::CodedOutputStream;
+using ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite;
using util::Status;
using util::StatusOr;
+using util::error::INVALID_ARGUMENT;
ProtoWriter::ProtoWriter(TypeResolver* type_resolver,
@@ -65,6 +67,7 @@ ProtoWriter::ProtoWriter(TypeResolver* type_resolver,
own_typeinfo_(true),
done_(false),
ignore_unknown_fields_(false),
+ ignore_unknown_enum_values_(false),
use_lower_camel_for_enums_(false),
element_(nullptr),
size_insert_(),
@@ -84,6 +87,7 @@ ProtoWriter::ProtoWriter(const TypeInfo* typeinfo,
own_typeinfo_(false),
done_(false),
ignore_unknown_fields_(false),
+ ignore_unknown_enum_values_(false),
use_lower_camel_for_enums_(false),
element_(nullptr),
size_insert_(),
@@ -263,19 +267,6 @@ inline Status WriteString(int field_number, const DataPiece& data,
return s.status();
}
-// Writes an ENUM field, including tag, to the stream.
-inline Status WriteEnum(int field_number, const DataPiece& data,
- const google::protobuf::Enum* enum_type,
- CodedOutputStream* stream,
- bool use_lower_camel_for_enums,
- bool ignore_unknown_values) {
- StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums, ignore_unknown_values);
- if (e.ok()) {
- WireFormatLite::WriteEnum(field_number, e.ValueOrDie(), stream);
- }
- return e.status();
-}
-
// Given a google::protobuf::Type, returns the set of all required fields.
std::set<const google::protobuf::Field*> GetRequiredFields(
const google::protobuf::Type& type) {
@@ -426,11 +417,13 @@ void ProtoWriter::ProtoElement::TakeOneofIndex(int32 index) {
oneof_indices_[index] = true;
}
-void ProtoWriter::InvalidName(StringPiece unknown_name, StringPiece message) {
+void ProtoWriter::InvalidName(StringPiece unknown_name,
+ StringPiece message) {
listener_->InvalidName(location(), ToSnakeCase(unknown_name), message);
}
-void ProtoWriter::InvalidValue(StringPiece type_name, StringPiece value) {
+void ProtoWriter::InvalidValue(StringPiece type_name,
+ StringPiece value) {
listener_->InvalidValue(location(), type_name, value);
}
@@ -462,8 +455,8 @@ ProtoWriter* ProtoWriter::StartObject(StringPiece name) {
const google::protobuf::Type* type = LookupType(field);
if (type == nullptr) {
++invalid_depth_;
- InvalidName(name,
- StrCat("Missing descriptor for field: ", field->type_url()));
+ InvalidName(name, StrCat("Missing descriptor for field: ",
+ field->type_url()));
return this;
}
@@ -501,8 +494,8 @@ ProtoWriter* ProtoWriter::StartList(StringPiece name) {
const google::protobuf::Type* type = LookupType(field);
if (type == nullptr) {
++invalid_depth_;
- InvalidName(name,
- StrCat("Missing descriptor for field: ", field->type_url()));
+ InvalidName(name, StrCat("Missing descriptor for field: ",
+ field->type_url()));
return this;
}
@@ -530,8 +523,8 @@ ProtoWriter* ProtoWriter::RenderDataPiece(StringPiece name,
const google::protobuf::Type* type = LookupType(field);
if (type == nullptr) {
- InvalidName(name,
- StrCat("Missing descriptor for field: ", field->type_url()));
+ InvalidName(name, StrCat("Missing descriptor for field: ",
+ field->type_url()));
return this;
}
@@ -546,9 +539,9 @@ bool ProtoWriter::ValidOneof(const google::protobuf::Field& field,
if (element_->IsOneofIndexTaken(field.oneof_index())) {
InvalidValue(
"oneof",
- StrCat("oneof field '",
- element_->type().oneofs(field.oneof_index() - 1),
- "' is already set. Cannot set '", unnormalized_name, "'"));
+ StrCat(
+ "oneof field '", element_->type().oneofs(field.oneof_index() - 1),
+ "' is already set. Cannot set '", unnormalized_name, "'"));
return false;
}
element_->TakeOneofIndex(field.oneof_index());
@@ -574,6 +567,20 @@ ProtoWriter* ProtoWriter::StartListField(const google::protobuf::Field& field,
return this;
}
+Status ProtoWriter::WriteEnum(int field_number, const DataPiece& data,
+ const google::protobuf::Enum* enum_type,
+ CodedOutputStream* stream,
+ bool use_lower_camel_for_enums,
+ bool ignore_unknown_values) {
+ bool is_unknown_enum_value = false;
+ StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums,
+ ignore_unknown_values, &is_unknown_enum_value);
+ if (e.ok() && !is_unknown_enum_value) {
+ WireFormatLite::WriteEnum(field_number, e.ValueOrDie(), stream);
+ }
+ return e.status();
+}
+
ProtoWriter* ProtoWriter::RenderPrimitiveField(
const google::protobuf::Field& field, const google::protobuf::Type& type,
const DataPiece& data) {
@@ -667,7 +674,7 @@ ProtoWriter* ProtoWriter::RenderPrimitiveField(
status = WriteEnum(field.number(), data,
typeinfo_->GetEnumByTypeUrl(field.type_url()),
stream_.get(), use_lower_camel_for_enums_,
- ignore_unknown_fields_);
+ ignore_unknown_enum_values_);
break;
}
default: // TYPE_GROUP or TYPE_MESSAGE
@@ -751,7 +758,7 @@ void ProtoWriter::WriteRootMessage() {
stream_.reset(nullptr);
const void* data;
int length;
- google::protobuf::io::ArrayInputStream input_stream(buffer_.data(), buffer_.size());
+ io::ArrayInputStream input_stream(buffer_.data(), buffer_.size());
while (input_stream.Next(&data, &length)) {
if (length == 0) continue;
int num_bytes = length;
diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h
index 28496963..1a8df982 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -46,6 +46,9 @@
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/bytestream.h>
#include <google/protobuf/stubs/hash.h>
+#include <google/protobuf/stubs/status.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -53,14 +56,16 @@ namespace io {
class CodedOutputStream;
} // namespace io
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
class Type;
class Field;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
@@ -73,12 +78,12 @@ class ObjectLocationTracker;
// special types by inheriting from it or by wrapping it.
//
// It also supports streaming.
-class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
+class PROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
public:
// Constructor. Does not take ownership of any parameter passed in.
ProtoWriter(TypeResolver* type_resolver, const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener);
- virtual ~ProtoWriter();
+ ~ProtoWriter() override;
// ObjectWriter methods.
ProtoWriter* StartObject(StringPiece name) override;
@@ -106,11 +111,12 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoWriter* RenderFloat(StringPiece name, float value) override {
return RenderDataPiece(name, DataPiece(value));
}
- ProtoWriter* RenderString(StringPiece name, StringPiece value) override {
+ ProtoWriter* RenderString(StringPiece name,
+ StringPiece value) override {
return RenderDataPiece(name,
DataPiece(value, use_strict_base64_decoding()));
}
- virtual ProtoWriter* RenderBytes(StringPiece name, StringPiece value) {
+ ProtoWriter* RenderBytes(StringPiece name, StringPiece value) override {
return RenderDataPiece(
name, DataPiece(value, false, use_strict_base64_decoding()));
}
@@ -133,7 +139,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
bool done() override { return done_; }
// Returns the proto stream object.
- google::protobuf::io::CodedOutputStream* stream() { return stream_.get(); }
+ io::CodedOutputStream* stream() { return stream_.get(); }
// Getters and mutators of invalid_depth_.
void IncrementInvalidDepth() { ++invalid_depth_; }
@@ -148,12 +154,17 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ignore_unknown_fields_ = ignore_unknown_fields;
}
+ void set_ignore_unknown_enum_values(bool ignore_unknown_enum_values) {
+ ignore_unknown_enum_values_ = ignore_unknown_enum_values;
+ }
+
void set_use_lower_camel_for_enums(bool use_lower_camel_for_enums) {
use_lower_camel_for_enums_ = use_lower_camel_for_enums;
}
protected:
- class LIBPROTOBUF_EXPORT ProtoElement : public BaseElement, public LocationTrackerInterface {
+ class PROTOBUF_EXPORT ProtoElement : public BaseElement,
+ public LocationTrackerInterface {
public:
// Constructor for the root element. No parent nor field.
ProtoElement(const TypeInfo* typeinfo, const google::protobuf::Type& type,
@@ -163,7 +174,7 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ProtoElement(ProtoElement* parent, const google::protobuf::Field* field,
const google::protobuf::Type& type, bool is_list);
- virtual ~ProtoElement() {}
+ ~ProtoElement() override {}
// Called just before the destructor for clean up:
// - reports any missing required fields
@@ -183,9 +194,9 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
void RegisterField(const google::protobuf::Field* field);
// To report location on error messages.
- virtual string ToString() const;
+ std::string ToString() const override;
- virtual ProtoElement* parent() const {
+ ProtoElement* parent() const override {
return static_cast<ProtoElement*>(BaseElement::parent());
}
@@ -251,7 +262,8 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// Common code for BeginObject() and BeginList() that does invalid_depth_
// bookkeeping associated with name lookup.
- const google::protobuf::Field* BeginNamed(StringPiece name, bool is_list);
+ const google::protobuf::Field* BeginNamed(StringPiece name,
+ bool is_list);
// Lookup the field in the current element. Looks in the base descriptor
// and in any extension. This will report an error if the field cannot be
@@ -298,6 +310,13 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
const DataPiece& value);
private:
+ // Writes an ENUM field, including tag, to the stream.
+ static util::Status WriteEnum(int field_number, const DataPiece& data,
+ const google::protobuf::Enum* enum_type,
+ io::CodedOutputStream* stream,
+ bool use_lower_camel_for_enums,
+ bool ignore_unknown_values);
+
// Variables for describing the structure of the input tree:
// master_type_: descriptor for the whole protobuf message.
// typeinfo_ : the TypeInfo object to lookup types.
@@ -309,9 +328,12 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// Indicates whether we finished writing root message completely.
bool done_;
- // If true, don't report unknown field names and enum values to the listener.
+ // If true, don't report unknown field names to the listener.
bool ignore_unknown_fields_;
+ // If true, don't report unknown enum values to the listener.
+ bool ignore_unknown_enum_values_;
+
// If true, check if enum name in camel case or without underscore matches the
// field name.
bool use_lower_camel_for_enums_;
@@ -330,9 +352,9 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// adapter_ : internal adapter between CodedOutputStream and buffer_.
// stream_ : wrapper for writing tags and other encodings in wire format.
strings::ByteSink* output_;
- string buffer_;
- google::protobuf::io::StringOutputStream adapter_;
- std::unique_ptr<google::protobuf::io::CodedOutputStream> stream_;
+ std::string buffer_;
+ io::StringOutputStream adapter_;
+ std::unique_ptr<io::CodedOutputStream> stream_;
// Variables for error tracking and reporting:
// listener_ : a place to report any errors found.
@@ -348,6 +370,8 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTO_WRITER_H__
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc
index 56e6db12..97a8bb48 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource.cc
@@ -30,9 +30,9 @@
#include <google/protobuf/util/internal/protostream_objectsource.h>
+#include <unordered_map>
#include <utility>
-#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringprintf.h>
@@ -40,16 +40,22 @@
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
+#include <google/protobuf/stubs/once.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/util/internal/field_mask_utility.h>
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
+#include <google/protobuf/stubs/casts.h>
+
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/status_macros.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -60,12 +66,8 @@ using util::error::Code;
using util::error::INTERNAL;
}
namespace converter {
-
-using google::protobuf::Descriptor;
-using google::protobuf::EnumValueDescriptor;
-using google::protobuf::FieldDescriptor;
-using google::protobuf::internal::WireFormat;
-using google::protobuf::internal::WireFormatLite;
+using ::PROTOBUF_NAMESPACE_ID::internal::WireFormat;
+using ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite;
using util::Status;
using util::StatusOr;
@@ -113,7 +115,7 @@ StatusOr<string> MapKeyDefaultValueAsString(
ProtoStreamObjectSource::ProtoStreamObjectSource(
- google::protobuf::io::CodedInputStream* stream, TypeResolver* type_resolver,
+ io::CodedInputStream* stream, TypeResolver* type_resolver,
const google::protobuf::Type& type)
: stream_(stream),
typeinfo_(TypeInfo::NewTypeInfo(type_resolver)),
@@ -131,7 +133,7 @@ ProtoStreamObjectSource::ProtoStreamObjectSource(
}
ProtoStreamObjectSource::ProtoStreamObjectSource(
- google::protobuf::io::CodedInputStream* stream, const TypeInfo* typeinfo,
+ io::CodedInputStream* stream, const TypeInfo* typeinfo,
const google::protobuf::Type& type)
: stream_(stream),
typeinfo_(typeinfo),
@@ -194,7 +196,7 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
string field_name;
// last_tag set to dummy value that is different from tag.
uint32 tag = stream_->ReadTag(), last_tag = tag + 1;
- google::protobuf::UnknownFieldSet unknown_fields;
+ UnknownFieldSet unknown_fields;
if (include_start_and_end) {
ow->StartObject(name);
@@ -246,8 +248,8 @@ Status ProtoStreamObjectSource::WriteMessage(const google::protobuf::Type& type,
}
StatusOr<uint32> ProtoStreamObjectSource::RenderList(
- const google::protobuf::Field* field, StringPiece name, uint32 list_tag,
- ObjectWriter* ow) const {
+ const google::protobuf::Field* field, StringPiece name,
+ uint32 list_tag, ObjectWriter* ow) const {
uint32 tag_to_return = 0;
ow->StartList(name);
if (IsPackable(*field) &&
@@ -268,8 +270,8 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderList(
}
StatusOr<uint32> ProtoStreamObjectSource::RenderMap(
- const google::protobuf::Field* field, StringPiece name, uint32 list_tag,
- ObjectWriter* ow) const {
+ const google::protobuf::Field* field, StringPiece name,
+ uint32 list_tag, ObjectWriter* ow) const {
const google::protobuf::Type* field_type =
typeinfo_->GetTypeByTypeUrl(field->type_url());
uint32 tag_to_return = 0;
@@ -332,9 +334,9 @@ Status ProtoStreamObjectSource::RenderTimestamp(
int64 seconds = p.first;
int32 nanos = p.second;
if (seconds > kTimestampMaxSeconds || seconds < kTimestampMinSeconds) {
- return Status(
- util::error::INTERNAL,
- StrCat("Timestamp seconds exceeds limit for field: ", field_name));
+ return Status(util::error::INTERNAL,
+ StrCat("Timestamp seconds exceeds limit for field: ",
+ field_name));
}
if (nanos < 0 || nanos >= kNanosPerSecond) {
@@ -370,10 +372,11 @@ Status ProtoStreamObjectSource::RenderDuration(
string sign = "";
if (seconds < 0) {
if (nanos > 0) {
- return Status(util::error::INTERNAL,
- StrCat("Duration nanos is non-negative, but seconds is "
- "negative for field: ",
- field_name));
+ return Status(
+ util::error::INTERNAL,
+ StrCat("Duration nanos is non-negative, but seconds is "
+ "negative for field: ",
+ field_name));
}
sign = "-";
seconds = -seconds;
@@ -383,7 +386,7 @@ Status ProtoStreamObjectSource::RenderDuration(
nanos = -nanos;
}
string formatted_duration = StringPrintf(
- "%s%lld%ss", sign.c_str(), seconds,
+ "%s%lld%ss", sign.c_str(), static_cast<long long>(seconds), // NOLINT
FormatNanos(nanos, os->add_trailing_zeros_for_timestamp_and_duration_)
.c_str());
ow->RenderString(field_name, formatted_duration);
@@ -400,7 +403,7 @@ Status ProtoStreamObjectSource::RenderDouble(const ProtoStreamObjectSource* os,
os->stream_->ReadLittleEndian64(&buffer64);
os->stream_->ReadTag();
}
- ow->RenderDouble(field_name, bit_cast<double>(buffer64));
+ ow->RenderDouble(field_name, ::google::protobuf::bit_cast<double>(buffer64));
return util::Status();
}
@@ -414,7 +417,7 @@ Status ProtoStreamObjectSource::RenderFloat(const ProtoStreamObjectSource* os,
os->stream_->ReadLittleEndian32(&buffer32);
os->stream_->ReadTag();
}
- ow->RenderFloat(field_name, bit_cast<float>(buffer32));
+ ow->RenderFloat(field_name, ::google::protobuf::bit_cast<float>(buffer32));
return util::Status();
}
@@ -428,7 +431,7 @@ Status ProtoStreamObjectSource::RenderInt64(const ProtoStreamObjectSource* os,
os->stream_->ReadVarint64(&buffer64);
os->stream_->ReadTag();
}
- ow->RenderInt64(field_name, bit_cast<int64>(buffer64));
+ ow->RenderInt64(field_name, ::google::protobuf::bit_cast<int64>(buffer64));
return util::Status();
}
@@ -442,7 +445,7 @@ Status ProtoStreamObjectSource::RenderUInt64(const ProtoStreamObjectSource* os,
os->stream_->ReadVarint64(&buffer64);
os->stream_->ReadTag();
}
- ow->RenderUint64(field_name, bit_cast<uint64>(buffer64));
+ ow->RenderUint64(field_name, ::google::protobuf::bit_cast<uint64>(buffer64));
return util::Status();
}
@@ -456,7 +459,7 @@ Status ProtoStreamObjectSource::RenderInt32(const ProtoStreamObjectSource* os,
os->stream_->ReadVarint32(&buffer32);
os->stream_->ReadTag();
}
- ow->RenderInt32(field_name, bit_cast<int32>(buffer32));
+ ow->RenderInt32(field_name, ::google::protobuf::bit_cast<int32>(buffer32));
return util::Status();
}
@@ -470,7 +473,7 @@ Status ProtoStreamObjectSource::RenderUInt32(const ProtoStreamObjectSource* os,
os->stream_->ReadVarint32(&buffer32);
os->stream_->ReadTag();
}
- ow->RenderUint32(field_name, bit_cast<uint32>(buffer32));
+ ow->RenderUint32(field_name, ::google::protobuf::bit_cast<uint32>(buffer32));
return util::Status();
}
@@ -642,12 +645,19 @@ Status ProtoStreamObjectSource::RenderAny(const ProtoStreamObjectSource* os,
// nested_type cannot be null at this time.
const google::protobuf::Type* nested_type = resolved_type.ValueOrDie();
- google::protobuf::io::ArrayInputStream zero_copy_stream(value.data(), value.size());
- google::protobuf::io::CodedInputStream in_stream(&zero_copy_stream);
+ io::ArrayInputStream zero_copy_stream(value.data(), value.size());
+ io::CodedInputStream in_stream(&zero_copy_stream);
// We know the type so we can render it. Recursively parse the nested stream
// using a nested ProtoStreamObjectSource using our nested type information.
ProtoStreamObjectSource nested_os(&in_stream, os->typeinfo_, *nested_type);
+ // TODO(htuch): This is somewhat fragile, since new options may be omitted.
+ // We should probably do this via the constructor or some object grouping
+ // options.
+ nested_os.set_use_lower_camel_for_enums(os->use_lower_camel_for_enums_);
+ nested_os.set_use_ints_for_enums(os->use_ints_for_enums_);
+ nested_os.set_preserve_proto_field_names(os->preserve_proto_field_names_);
+
// We manually call start and end object here so we can inject the @type.
ow->StartObject(field_name);
ow->RenderString("@type", type_url);
@@ -689,12 +699,13 @@ Status ProtoStreamObjectSource::RenderFieldMask(
}
-hash_map<string, ProtoStreamObjectSource::TypeRenderer>*
+std::unordered_map<string, ProtoStreamObjectSource::TypeRenderer>*
ProtoStreamObjectSource::renderers_ = NULL;
-GOOGLE_PROTOBUF_DECLARE_ONCE(source_renderers_init_);
+PROTOBUF_NAMESPACE_ID::internal::once_flag source_renderers_init_;
void ProtoStreamObjectSource::InitRendererMap() {
- renderers_ = new hash_map<string, ProtoStreamObjectSource::TypeRenderer>();
+ renderers_ =
+ new std::unordered_map<string, ProtoStreamObjectSource::TypeRenderer>();
(*renderers_)["google.protobuf.Timestamp"] =
&ProtoStreamObjectSource::RenderTimestamp;
(*renderers_)["google.protobuf.Duration"] =
@@ -737,7 +748,8 @@ void ProtoStreamObjectSource::DeleteRendererMap() {
// static
ProtoStreamObjectSource::TypeRenderer*
ProtoStreamObjectSource::FindTypeRenderer(const string& type_url) {
- ::google::protobuf::GoogleOnceInit(&source_renderers_init_, &InitRendererMap);
+ PROTOBUF_NAMESPACE_ID::internal::call_once(source_renderers_init_,
+ InitRendererMap);
return FindOrNull(*renderers_, type_url);
}
@@ -755,9 +767,10 @@ Status ProtoStreamObjectSource::RenderField(
const google::protobuf::Type* type =
typeinfo_->GetTypeByTypeUrl(field->type_url());
if (type == nullptr) {
- return Status(util::error::INTERNAL,
- StrCat("Invalid configuration. Could not find the type: ",
- field->type_url()));
+ return Status(
+ util::error::INTERNAL,
+ StrCat("Invalid configuration. Could not find the type: ",
+ field->type_url()));
}
// Short-circuit any special type rendering to save call-stack space.
@@ -799,22 +812,22 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
}
case google::protobuf::Field_Kind_TYPE_INT32: {
stream_->ReadVarint32(&buffer32);
- ow->RenderInt32(field_name, bit_cast<int32>(buffer32));
+ ow->RenderInt32(field_name, ::google::protobuf::bit_cast<int32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_INT64: {
stream_->ReadVarint64(&buffer64);
- ow->RenderInt64(field_name, bit_cast<int64>(buffer64));
+ ow->RenderInt64(field_name, ::google::protobuf::bit_cast<int64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_UINT32: {
stream_->ReadVarint32(&buffer32);
- ow->RenderUint32(field_name, bit_cast<uint32>(buffer32));
+ ow->RenderUint32(field_name, ::google::protobuf::bit_cast<uint32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_UINT64: {
stream_->ReadVarint64(&buffer64);
- ow->RenderUint64(field_name, bit_cast<uint64>(buffer64));
+ ow->RenderUint64(field_name, ::google::protobuf::bit_cast<uint64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_SINT32: {
@@ -829,32 +842,32 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
}
case google::protobuf::Field_Kind_TYPE_SFIXED32: {
stream_->ReadLittleEndian32(&buffer32);
- ow->RenderInt32(field_name, bit_cast<int32>(buffer32));
+ ow->RenderInt32(field_name, ::google::protobuf::bit_cast<int32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_SFIXED64: {
stream_->ReadLittleEndian64(&buffer64);
- ow->RenderInt64(field_name, bit_cast<int64>(buffer64));
+ ow->RenderInt64(field_name, ::google::protobuf::bit_cast<int64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_FIXED32: {
stream_->ReadLittleEndian32(&buffer32);
- ow->RenderUint32(field_name, bit_cast<uint32>(buffer32));
+ ow->RenderUint32(field_name, ::google::protobuf::bit_cast<uint32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_FIXED64: {
stream_->ReadLittleEndian64(&buffer64);
- ow->RenderUint64(field_name, bit_cast<uint64>(buffer64));
+ ow->RenderUint64(field_name, ::google::protobuf::bit_cast<uint64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_FLOAT: {
stream_->ReadLittleEndian32(&buffer32);
- ow->RenderFloat(field_name, bit_cast<float>(buffer32));
+ ow->RenderFloat(field_name, ::google::protobuf::bit_cast<float>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_DOUBLE: {
stream_->ReadLittleEndian64(&buffer64);
- ow->RenderDouble(field_name, bit_cast<double>(buffer64));
+ ow->RenderDouble(field_name, ::google::protobuf::bit_cast<double>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_ENUM: {
@@ -925,25 +938,25 @@ const string ProtoStreamObjectSource::ReadFieldValueAsString(
case google::protobuf::Field_Kind_TYPE_INT32: {
uint32 buffer32;
stream_->ReadVarint32(&buffer32);
- result = SimpleItoa(bit_cast<int32>(buffer32));
+ result = SimpleItoa(::google::protobuf::bit_cast<int32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_INT64: {
uint64 buffer64;
stream_->ReadVarint64(&buffer64);
- result = SimpleItoa(bit_cast<int64>(buffer64));
+ result = SimpleItoa(::google::protobuf::bit_cast<int64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_UINT32: {
uint32 buffer32;
stream_->ReadVarint32(&buffer32);
- result = SimpleItoa(bit_cast<uint32>(buffer32));
+ result = SimpleItoa(::google::protobuf::bit_cast<uint32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_UINT64: {
uint64 buffer64;
stream_->ReadVarint64(&buffer64);
- result = SimpleItoa(bit_cast<uint64>(buffer64));
+ result = SimpleItoa(::google::protobuf::bit_cast<uint64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_SINT32: {
@@ -961,37 +974,37 @@ const string ProtoStreamObjectSource::ReadFieldValueAsString(
case google::protobuf::Field_Kind_TYPE_SFIXED32: {
uint32 buffer32;
stream_->ReadLittleEndian32(&buffer32);
- result = SimpleItoa(bit_cast<int32>(buffer32));
+ result = SimpleItoa(::google::protobuf::bit_cast<int32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_SFIXED64: {
uint64 buffer64;
stream_->ReadLittleEndian64(&buffer64);
- result = SimpleItoa(bit_cast<int64>(buffer64));
+ result = SimpleItoa(::google::protobuf::bit_cast<int64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_FIXED32: {
uint32 buffer32;
stream_->ReadLittleEndian32(&buffer32);
- result = SimpleItoa(bit_cast<uint32>(buffer32));
+ result = SimpleItoa(::google::protobuf::bit_cast<uint32>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_FIXED64: {
uint64 buffer64;
stream_->ReadLittleEndian64(&buffer64);
- result = SimpleItoa(bit_cast<uint64>(buffer64));
+ result = SimpleItoa(::google::protobuf::bit_cast<uint64>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_FLOAT: {
uint32 buffer32;
stream_->ReadLittleEndian32(&buffer32);
- result = SimpleFtoa(bit_cast<float>(buffer32));
+ result = SimpleFtoa(::google::protobuf::bit_cast<float>(buffer32));
break;
}
case google::protobuf::Field_Kind_TYPE_DOUBLE: {
uint64 buffer64;
stream_->ReadLittleEndian64(&buffer64);
- result = SimpleDtoa(bit_cast<double>(buffer64));
+ result = SimpleDtoa(::google::protobuf::bit_cast<double>(buffer64));
break;
}
case google::protobuf::Field_Kind_TYPE_ENUM: {
@@ -1037,7 +1050,7 @@ bool ProtoStreamObjectSource::IsMap(
const google::protobuf::Type* field_type =
typeinfo_->GetTypeByTypeUrl(field.type_url());
return field.kind() == google::protobuf::Field_Kind_TYPE_MESSAGE &&
- google::protobuf::util::converter::IsMap(field, *field_type);
+ util::converter::IsMap(field, *field_type);
}
std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos(
@@ -1059,11 +1072,11 @@ std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos(
if (field->number() == 1) {
// read seconds
stream_->ReadVarint64(&seconds);
- signed_seconds = bit_cast<int64>(seconds);
+ signed_seconds = ::google::protobuf::bit_cast<int64>(seconds);
} else if (field->number() == 2) {
// read nanos
stream_->ReadVarint32(&nanos);
- signed_nanos = bit_cast<int32>(nanos);
+ signed_nanos = ::google::protobuf::bit_cast<int32>(nanos);
}
}
return std::pair<int64, int32>(signed_seconds, signed_nanos);
@@ -1075,7 +1088,7 @@ Status ProtoStreamObjectSource::IncrementRecursionDepth(
return Status(
util::error::INVALID_ARGUMENT,
StrCat("Message too deep. Max recursion depth reached for type '",
- type_name, "', field '", field_name, "'"));
+ type_name, "', field '", field_name, "'"));
}
return util::Status();
}
@@ -1097,8 +1110,8 @@ const google::protobuf::Field* FindFieldByNumber(
bool IsPackable(const google::protobuf::Field& field) {
return field.cardinality() ==
google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
- google::protobuf::FieldDescriptor::IsTypePackable(
- static_cast<google::protobuf::FieldDescriptor::Type>(field.kind()));
+ FieldDescriptor::IsTypePackable(
+ static_cast<FieldDescriptor::Type>(field.kind()));
}
// TODO(skarvaje): Speed this up by not doing a linear scan.
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.h b/src/google/protobuf/util/internal/protostream_objectsource.h
index b56efdf4..c2549878 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.h
+++ b/src/google/protobuf/util/internal/protostream_objectsource.h
@@ -32,8 +32,8 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
#include <functional>
-#include <google/protobuf/stubs/hash.h>
#include <string>
+#include <unordered_map>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/type.pb.h>
@@ -42,17 +42,20 @@
#include <google/protobuf/util/internal/type_info.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/stringpiece.h>
+#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/stubs/status.h>
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class Field;
class Type;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
@@ -72,15 +75,16 @@ class TypeInfo;
// <your message google::protobuf::Type>);
//
// Status status = os.WriteTo(<some ObjectWriter>);
-class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
+class PROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
public:
- ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream,
+ ProtoStreamObjectSource(io::CodedInputStream* stream,
TypeResolver* type_resolver,
const google::protobuf::Type& type);
- virtual ~ProtoStreamObjectSource();
+ ~ProtoStreamObjectSource() override;
- virtual util::Status NamedWriteTo(StringPiece name, ObjectWriter* ow) const;
+ util::Status NamedWriteTo(StringPiece name,
+ ObjectWriter* ow) const override;
// Sets whether or not to use lowerCamelCase casing for enum values. If set to
// false, enum values are output without any case conversions.
@@ -134,7 +138,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// The include_start_and_end parameter allows this method to be called when
// already inside of an object, and skip calling StartObject and EndObject.
virtual util::Status WriteMessage(const google::protobuf::Type& descriptor,
- StringPiece name, const uint32 end_tag,
+ StringPiece name,
+ const uint32 end_tag,
bool include_start_and_end,
ObjectWriter* ow) const;
@@ -142,8 +147,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// reading all sequential repeating elements. The caller should use this tag
// before reading more tags from the stream.
virtual util::StatusOr<uint32> RenderList(
- const google::protobuf::Field* field, StringPiece name, uint32 list_tag,
- ObjectWriter* ow) const;
+ const google::protobuf::Field* field, StringPiece name,
+ uint32 list_tag, ObjectWriter* ow) const;
// Looks up a field and verify its consistency with wire type in tag.
const google::protobuf::Field* FindAndVerifyField(
@@ -151,17 +156,18 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Renders a field value to the ObjectWriter.
util::Status RenderField(const google::protobuf::Field* field,
- StringPiece field_name, ObjectWriter* ow) const;
+ StringPiece field_name,
+ ObjectWriter* ow) const;
// Reads field value according to Field spec in 'field' and returns the read
// value as string. This only works for primitive datatypes (no message
// types).
- const string ReadFieldValueAsString(
+ const std::string ReadFieldValueAsString(
const google::protobuf::Field& field) const;
private:
- ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream,
+ ProtoStreamObjectSource(io::CodedInputStream* stream,
const TypeInfo* typeinfo,
const google::protobuf::Type& type);
// Function that renders a well known type with a modified behavior.
@@ -188,12 +194,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Renders a google.protobuf.Timestamp value to ObjectWriter
static util::Status RenderTimestamp(const ProtoStreamObjectSource* os,
const google::protobuf::Type& type,
- StringPiece name, ObjectWriter* ow);
+ StringPiece name,
+ ObjectWriter* ow);
// Renders a google.protobuf.Duration value to ObjectWriter
static util::Status RenderDuration(const ProtoStreamObjectSource* os,
const google::protobuf::Type& type,
- StringPiece name, ObjectWriter* ow);
+ StringPiece name,
+ ObjectWriter* ow);
// Following RenderTYPE functions render well known types in
// google/protobuf/wrappers.proto corresponding to TYPE.
@@ -233,7 +241,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Helper to render google.protobuf.Struct's Value fields to ObjectWriter.
static util::Status RenderStructValue(const ProtoStreamObjectSource* os,
const google::protobuf::Type& type,
- StringPiece name, ObjectWriter* ow);
+ StringPiece name,
+ ObjectWriter* ow);
// Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter.
static util::Status RenderStructListValue(
@@ -248,12 +257,13 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Render the "FieldMask" type.
static util::Status RenderFieldMask(const ProtoStreamObjectSource* os,
const google::protobuf::Type& type,
- StringPiece name, ObjectWriter* ow);
+ StringPiece name,
+ ObjectWriter* ow);
- static hash_map<string, TypeRenderer>* renderers_;
+ static std::unordered_map<std::string, TypeRenderer>* renderers_;
static void InitRendererMap();
static void DeleteRendererMap();
- static TypeRenderer* FindTypeRenderer(const string& type_url);
+ static TypeRenderer* FindTypeRenderer(const std::string& type_url);
// Same as above but renders all non-message field types. Callers don't call
// this function directly. They just use RenderField.
@@ -277,7 +287,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
StringPiece field_name) const;
// Input stream to read from. Ownership rests with the caller.
- google::protobuf::io::CodedInputStream* stream_;
+ io::CodedInputStream* stream_;
// Type information for all the types used in the descriptor. Used to find
// google::protobuf::Type of nested messages/enums.
@@ -321,6 +331,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index df790728..5e2f86f4 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
@@ -33,7 +33,6 @@
#include <memory>
#include <sstream>
-#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/any.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
@@ -50,6 +49,7 @@
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/stubs/strutil.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/casts.h>
namespace google {
@@ -57,13 +57,6 @@ namespace protobuf {
namespace util {
namespace converter {
-using google::protobuf::Descriptor;
-using google::protobuf::DescriptorPool;
-using google::protobuf::FileDescriptorProto;
-using google::protobuf::Message;
-using google::protobuf::io::ArrayInputStream;
-using google::protobuf::io::CodedInputStream;
-using util::Status;
using google::protobuf::testing::AnyM;
using google::protobuf::testing::AnyOut;
using google::protobuf::testing::Author;
@@ -82,7 +75,10 @@ using google::protobuf::testing::Primitive;
using google::protobuf::testing::Proto3Message;
using google::protobuf::testing::StructType;
using google::protobuf::testing::TimestampDuration;
+using io::ArrayInputStream;
+using io::CodedInputStream;
using ::testing::_;
+using util::Status;
namespace {
@@ -100,6 +96,7 @@ class ProtostreamObjectSourceTest
ow_(&mock_),
use_lower_camel_for_enums_(false),
use_ints_for_enums_(false),
+ use_preserve_proto_field_names_(false),
add_trailing_zeros_(false),
render_unknown_enum_values_(true) {
helper_.ResetTypeInfo(Book::descriptor(), Proto3Message::descriptor());
@@ -123,6 +120,8 @@ class ProtostreamObjectSourceTest
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);
+ if (use_preserve_proto_field_names_)
+ os->set_preserve_proto_field_names(true);
os->set_max_recursion_depth(64);
return os->WriteTo(&mock_);
}
@@ -130,13 +129,13 @@ class ProtostreamObjectSourceTest
void PrepareExpectingObjectWriterForRepeatedPrimitive() {
ow_.StartObject("")
->StartList("repFix32")
- ->RenderUint32("", bit_cast<uint32>(3201))
- ->RenderUint32("", bit_cast<uint32>(0))
- ->RenderUint32("", bit_cast<uint32>(3202))
+ ->RenderUint32("", ::google::protobuf::bit_cast<uint32>(3201))
+ ->RenderUint32("", ::google::protobuf::bit_cast<uint32>(0))
+ ->RenderUint32("", ::google::protobuf::bit_cast<uint32>(3202))
->EndList()
->StartList("repU32")
- ->RenderUint32("", bit_cast<uint32>(3203))
- ->RenderUint32("", bit_cast<uint32>(0))
+ ->RenderUint32("", ::google::protobuf::bit_cast<uint32>(3203))
+ ->RenderUint32("", ::google::protobuf::bit_cast<uint32>(0))
->EndList()
->StartList("repI32")
->RenderInt32("", 0)
@@ -153,13 +152,13 @@ class ProtostreamObjectSourceTest
->RenderInt32("", 3208)
->EndList()
->StartList("repFix64")
- ->RenderUint64("", bit_cast<uint64>(6401LL))
- ->RenderUint64("", bit_cast<uint64>(0LL))
+ ->RenderUint64("", ::google::protobuf::bit_cast<uint64>(6401LL))
+ ->RenderUint64("", ::google::protobuf::bit_cast<uint64>(0LL))
->EndList()
->StartList("repU64")
- ->RenderUint64("", bit_cast<uint64>(0LL))
- ->RenderUint64("", bit_cast<uint64>(6402LL))
- ->RenderUint64("", bit_cast<uint64>(6403LL))
+ ->RenderUint64("", ::google::protobuf::bit_cast<uint64>(0LL))
+ ->RenderUint64("", ::google::protobuf::bit_cast<uint64>(6402LL))
+ ->RenderUint64("", ::google::protobuf::bit_cast<uint64>(6403LL))
->EndList()
->StartList("repI64")
->RenderInt64("", 6404L)
@@ -272,6 +271,8 @@ class ProtostreamObjectSourceTest
void UseIntsForEnums() { use_ints_for_enums_ = true; }
+ void UsePreserveProtoFieldNames() { use_preserve_proto_field_names_ = true; }
+
void AddTrailingZeros() { add_trailing_zeros_ = true; }
void SetRenderUnknownEnumValues(bool value) {
@@ -284,6 +285,7 @@ class ProtostreamObjectSourceTest
ExpectingObjectWriter ow_;
bool use_lower_camel_for_enums_;
bool use_ints_for_enums_;
+ bool use_preserve_proto_field_names_;
bool add_trailing_zeros_;
bool render_unknown_enum_values_;
};
@@ -318,13 +320,13 @@ TEST_P(ProtostreamObjectSourceTest, Primitives) {
primitive.set_bool_(true);
ow_.StartObject("")
- ->RenderUint32("fix32", bit_cast<uint32>(3201))
- ->RenderUint32("u32", bit_cast<uint32>(3202))
+ ->RenderUint32("fix32", ::google::protobuf::bit_cast<uint32>(3201))
+ ->RenderUint32("u32", ::google::protobuf::bit_cast<uint32>(3202))
->RenderInt32("i32", 3203)
->RenderInt32("sf32", 3204)
->RenderInt32("s32", 3205)
- ->RenderUint64("fix64", bit_cast<uint64>(6401LL))
- ->RenderUint64("u64", bit_cast<uint64>(6402LL))
+ ->RenderUint64("fix64", ::google::protobuf::bit_cast<uint64>(6401LL))
+ ->RenderUint64("u64", ::google::protobuf::bit_cast<uint64>(6402LL))
->RenderInt64("i64", 6403L)
->RenderInt64("sf64", 6404L)
->RenderInt64("s64", 6405L)
@@ -536,6 +538,16 @@ TEST_P(ProtostreamObjectSourceTest, UseIntsForEnumsTest) {
DoTest(book, Book::descriptor());
}
+TEST_P(ProtostreamObjectSourceTest, UsePreserveProtoFieldNames) {
+ Book book;
+ book.set_snake_field("foo");
+
+ UsePreserveProtoFieldNames();
+
+ ow_.StartObject("")->RenderString("snake_field", "foo")->EndObject();
+ DoTest(book, Book::descriptor());
+}
+
TEST_P(ProtostreamObjectSourceTest,
UnknownEnumAreDroppedWhenRenderUnknownEnumValuesIsUnset) {
Proto3Message message;
@@ -731,8 +743,8 @@ TEST_P(ProtostreamObjectSourceMapsTest, MissingKeysTest) {
class ProtostreamObjectSourceAnysTest : public ProtostreamObjectSourceTest {
protected:
ProtostreamObjectSourceAnysTest() {
- helper_.ResetTypeInfo(AnyOut::descriptor(),
- google::protobuf::Any::descriptor());
+ helper_.ResetTypeInfo({AnyOut::descriptor(), Book::descriptor(),
+ google::protobuf::Any::descriptor()});
}
};
@@ -769,6 +781,69 @@ TEST_P(ProtostreamObjectSourceAnysTest, BasicAny) {
DoTest(out, AnyOut::descriptor());
}
+TEST_P(ProtostreamObjectSourceAnysTest, LowerCamelEnumOutputSnakeCase) {
+ AnyOut out;
+ ::google::protobuf::Any* any = out.mutable_any();
+
+ Book book;
+ book.set_type(Book::arts_and_photography);
+ any->PackFrom(book);
+
+ UseLowerCamelForEnums();
+
+ ow_.StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type",
+ "type.googleapis.com/google.protobuf.testing.Book")
+ ->RenderString("type", "artsAndPhotography")
+ ->EndObject()
+ ->EndObject();
+
+ DoTest(out, AnyOut::descriptor());
+}
+
+TEST_P(ProtostreamObjectSourceAnysTest, UseIntsForEnumsTest) {
+ AnyOut out;
+ ::google::protobuf::Any* any = out.mutable_any();
+
+ Book book;
+ book.set_type(Book::ACTION_AND_ADVENTURE);
+ any->PackFrom(book);
+
+ UseIntsForEnums();
+
+ ow_.StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type",
+ "type.googleapis.com/google.protobuf.testing.Book")
+ ->RenderInt32("type", 3)
+ ->EndObject()
+ ->EndObject();
+
+ DoTest(out, AnyOut::descriptor());
+}
+
+TEST_P(ProtostreamObjectSourceAnysTest, UsePreserveProtoFieldNames) {
+ AnyOut out;
+ ::google::protobuf::Any* any = out.mutable_any();
+
+ Book book;
+ book.set_snake_field("foo");
+ any->PackFrom(book);
+
+ UsePreserveProtoFieldNames();
+
+ ow_.StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type",
+ "type.googleapis.com/google.protobuf.testing.Book")
+ ->RenderString("snake_field", "foo")
+ ->EndObject()
+ ->EndObject();
+
+ DoTest(out, AnyOut::descriptor());
+}
+
TEST_P(ProtostreamObjectSourceAnysTest, RecursiveAny) {
AnyOut out;
::google::protobuf::Any* any = out.mutable_any();
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc
index 2edfd075..9c52116e 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -32,28 +32,33 @@
#include <functional>
#include <stack>
+#include <unordered_map>
+#include <unordered_set>
-#include <google/protobuf/stubs/once.h>
#include <google/protobuf/stubs/time.h>
+#include <google/protobuf/stubs/once.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/util/internal/field_mask_utility.h>
#include <google/protobuf/util/internal/object_location_tracker.h>
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
namespace converter {
-using google::protobuf::internal::WireFormatLite;
-using util::error::INVALID_ARGUMENT;
+using ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite;
using util::Status;
using util::StatusOr;
+using util::error::INVALID_ARGUMENT;
ProtoStreamObjectWriter::ProtoStreamObjectWriter(
@@ -65,11 +70,24 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter(
current_(nullptr),
options_(options) {
set_ignore_unknown_fields(options_.ignore_unknown_fields);
+ set_ignore_unknown_enum_values(options_.ignore_unknown_enum_values);
set_use_lower_camel_for_enums(options_.use_lower_camel_for_enums);
}
ProtoStreamObjectWriter::ProtoStreamObjectWriter(
const TypeInfo* typeinfo, const google::protobuf::Type& type,
+ strings::ByteSink* output, ErrorListener* listener,
+ const ProtoStreamObjectWriter::Options& options)
+ : ProtoWriter(typeinfo, type, output, listener),
+ master_type_(type),
+ current_(nullptr),
+ options_(options) {
+ set_ignore_unknown_fields(options_.ignore_unknown_fields);
+ set_use_lower_camel_for_enums(options.use_lower_camel_for_enums);
+}
+
+ProtoStreamObjectWriter::ProtoStreamObjectWriter(
+ const TypeInfo* typeinfo, const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener)
: ProtoWriter(typeinfo, type, output, listener),
master_type_(type),
@@ -120,7 +138,7 @@ Status GetNanosFromStringPiece(StringPiece s_nanos,
// "0." + s_nanos.ToString() seconds. An int32 is used for the
// conversion to 'nanos', rather than a double, so that there is no
// loss of precision.
- if (!s_nanos.empty() && !safe_strto32(s_nanos.ToString(), &i_nanos)) {
+ if (!s_nanos.empty() && !safe_strto32(s_nanos, &i_nanos)) {
return Status(INVALID_ARGUMENT, parse_failure_message);
}
if (i_nanos > kNanosPerSecond || i_nanos < 0) {
@@ -305,7 +323,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
// Figure out the type url. This is a copy-paste from WriteString but we also
// need the value, so we can't just call through to that.
if (value.type() == DataPiece::TYPE_STRING) {
- type_url_ = value.str().ToString();
+ type_url_ = string(value.str());
} else {
StatusOr<string> s = value.ToString();
if (!s.ok()) {
@@ -337,7 +355,7 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
// Create our object writer and initialize it with the first StartObject
// call.
ow_.reset(new ProtoStreamObjectWriter(parent_->typeinfo(), *type, &output_,
- parent_->listener()));
+ parent_->listener(), parent_->options_));
// Don't call StartObject() for well-known types yet. Depending on the
// type of actual data, we may not need to call StartObject(). For
@@ -368,8 +386,9 @@ void ProtoStreamObjectWriter::AnyWriter::WriteAny() {
} else {
// There are uninterpreted data, but we never got a "@type" field.
if (!invalid_) {
- parent_->InvalidValue("Any", StrCat("Missing @type for any field in ",
- parent_->master_type_.name()));
+ parent_->InvalidValue("Any",
+ StrCat("Missing @type for any field in ",
+ parent_->master_type_.name()));
invalid_ = true;
}
return;
@@ -431,7 +450,7 @@ ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter* enclosing,
any_.reset(new AnyWriter(ow_));
}
if (item_type == MAP) {
- map_keys_.reset(new hash_set<string>);
+ map_keys_.reset(new std::unordered_set<string>);
}
}
@@ -448,13 +467,13 @@ ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter::Item* parent,
any_.reset(new AnyWriter(ow_));
}
if (item_type == MAP) {
- map_keys_.reset(new hash_set<string>);
+ map_keys_.reset(new std::unordered_set<string>);
}
}
bool ProtoStreamObjectWriter::Item::InsertMapKeyIfNotPresent(
StringPiece map_key) {
- return InsertIfNotPresent(map_keys_.get(), map_key.ToString());
+ return InsertIfNotPresent(map_keys_.get(), string(map_key));
}
ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
@@ -477,7 +496,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
// stream, we write those values.
if (master_type_.name() == kStructType) {
// Struct has a map<string, Value> field called "fields".
- // https://github.com/google/protobuf/blob/master/src/google/protobuf/struct.proto
+ // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
// "fields": [
Push("fields", Item::MAP, true, true);
return this;
@@ -488,7 +507,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
// object within that type is a struct type. So start a struct.
//
// The struct field in Value type is named "struct_value"
- // https://github.com/google/protobuf/blob/master/src/google/protobuf/struct.proto
+ // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
// Also start the map field "fields" within the struct.
// "struct_value": {
// "fields": [
@@ -534,7 +553,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartObject(
Push("", Item::MESSAGE, false, false);
ProtoWriter::RenderDataPiece("key",
DataPiece(name, use_strict_base64_decoding()));
- Push("value", Item::MESSAGE, true, false);
+ Push("value", IsAny(*Lookup("value")) ? Item::ANY : Item::MESSAGE, true,
+ false);
// Make sure we are valid so far after starting map fields.
if (invalid_depth() > 0) return this;
@@ -618,7 +638,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::EndObject() {
return this;
}
-ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
+ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(
+ StringPiece name) {
if (invalid_depth() > 0) {
IncrementInvalidDepth();
return this;
@@ -641,7 +662,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
// we have to start the "list_value" within google.protobuf.Value.
//
// See
- // https://github.com/google/protobuf/blob/master/src/google/protobuf/struct.proto
+ // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto
//
// Render
// "<name>": {
@@ -727,7 +748,7 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
// Report an error.
InvalidValue("Map", StrCat("Cannot have repeated items ('", name,
- "') within a map."));
+ "') within a map."));
return this;
}
@@ -818,8 +839,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::StartList(StringPiece name) {
}
if (IsMap(*field)) {
- InvalidValue("Map",
- StrCat("Cannot bind a list to map for field '", name, "'."));
+ InvalidValue("Map", StrCat("Cannot bind a list to map for field '",
+ name, "'."));
IncrementInvalidDepth();
return this;
}
@@ -924,7 +945,7 @@ Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for timestamp, value is ",
- data.ValueAsStringOrDefault("")));
+ data.ValueAsStringOrDefault("")));
}
StringPiece value(data.str());
@@ -955,13 +976,13 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for field mask, value is ",
- data.ValueAsStringOrDefault("")));
+ data.ValueAsStringOrDefault("")));
}
// TODO(tsun): figure out how to do proto descriptor based snake case
// conversions as much as possible. Because ToSnakeCase sometimes returns the
// wrong value.
- std::unique_ptr<ResultCallback1<util::Status, StringPiece> > callback(
+ std::unique_ptr<ResultCallback1<util::Status, StringPiece>> callback(
::google::protobuf::NewPermanentCallback(&RenderOneFieldPath, ow));
return DecodeCompactFieldMaskPaths(data.str(), callback.get());
}
@@ -972,7 +993,7 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for duration, value is ",
- data.ValueAsStringOrDefault("")));
+ data.ValueAsStringOrDefault("")));
}
StringPiece value(data.str());
@@ -1042,8 +1063,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
ProtoWriter::StartObject(name);
status = (*type_renderer)(this, data);
if (!status.ok()) {
- InvalidValue(master_type_.name(),
- StrCat("Field '", name, "', ", status.error_message()));
+ InvalidValue(master_type_.name(), StrCat("Field '", name, "', ",
+ status.error_message()));
}
ProtoWriter::EndObject();
return this;
@@ -1058,18 +1079,27 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
if (current_->IsMap()) {
if (!ValidMapKey(name)) return this;
- // Render an item in repeated map list.
- // { "key": "<name>", "value":
- Push("", Item::MESSAGE, false, false);
- ProtoWriter::RenderDataPiece("key",
- DataPiece(name, use_strict_base64_decoding()));
field = Lookup("value");
if (field == nullptr) {
- Pop();
GOOGLE_LOG(DFATAL) << "Map does not have a value field.";
return this;
}
+ if (options_.ignore_null_value_map_entry) {
+ // If we are rendering explicit null values and the backend proto field is
+ // not of the google.protobuf.NullType type, interpret null as absence.
+ if (data.type() == DataPiece::TYPE_NULL &&
+ field->type_url() != kStructNullValueTypeUrl) {
+ return this;
+ }
+ }
+
+ // Render an item in repeated map list.
+ // { "key": "<name>", "value":
+ Push("", Item::MESSAGE, false, false);
+ ProtoWriter::RenderDataPiece("key",
+ DataPiece(name, use_strict_base64_decoding()));
+
const TypeRenderer* type_renderer = FindTypeRenderer(field->type_url());
if (type_renderer != nullptr) {
// Map's value type is a special type. Render it like a message:
@@ -1079,8 +1109,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
Push("value", Item::MESSAGE, true, false);
status = (*type_renderer)(this, data);
if (!status.ok()) {
- InvalidValue(field->type_url(),
- StrCat("Field '", name, "', ", status.error_message()));
+ InvalidValue(field->type_url(), StrCat("Field '", name, "', ",
+ status.error_message()));
}
Pop();
return this;
@@ -1113,8 +1143,8 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
Push(name, Item::MESSAGE, false, false);
status = (*type_renderer)(this, data);
if (!status.ok()) {
- InvalidValue(field->type_url(),
- StrCat("Field '", name, "', ", status.error_message()));
+ InvalidValue(field->type_url(), StrCat("Field '", name, "', ",
+ status.error_message()));
}
Pop();
}
@@ -1134,12 +1164,13 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
// Map of functions that are responsible for rendering well known type
// represented by the key.
-hash_map<string, ProtoStreamObjectWriter::TypeRenderer>*
+std::unordered_map<string, ProtoStreamObjectWriter::TypeRenderer>*
ProtoStreamObjectWriter::renderers_ = NULL;
-GOOGLE_PROTOBUF_DECLARE_ONCE(writer_renderers_init_);
+PROTOBUF_NAMESPACE_ID::internal::once_flag writer_renderers_init_;
void ProtoStreamObjectWriter::InitRendererMap() {
- renderers_ = new hash_map<string, ProtoStreamObjectWriter::TypeRenderer>();
+ renderers_ =
+ new std::unordered_map<string, ProtoStreamObjectWriter::TypeRenderer>();
(*renderers_)["type.googleapis.com/google.protobuf.Timestamp"] =
&ProtoStreamObjectWriter::RenderTimestamp;
(*renderers_)["type.googleapis.com/google.protobuf.Duration"] =
@@ -1194,7 +1225,8 @@ void ProtoStreamObjectWriter::DeleteRendererMap() {
ProtoStreamObjectWriter::TypeRenderer*
ProtoStreamObjectWriter::FindTypeRenderer(const string& type_url) {
- ::google::protobuf::GoogleOnceInit(&writer_renderers_init_, &InitRendererMap);
+ PROTOBUF_NAMESPACE_ID::internal::call_once(writer_renderers_init_,
+ InitRendererMap);
return FindOrNull(*renderers_, type_url);
}
@@ -1204,14 +1236,16 @@ bool ProtoStreamObjectWriter::ValidMapKey(StringPiece unnormalized_name) {
if (!current_->InsertMapKeyIfNotPresent(unnormalized_name)) {
listener()->InvalidName(
location(), unnormalized_name,
- StrCat("Repeated map key: '", unnormalized_name, "' is already set."));
+ StrCat("Repeated map key: '", unnormalized_name,
+ "' is already set."));
return false;
}
return true;
}
-void ProtoStreamObjectWriter::Push(StringPiece name, Item::ItemType item_type,
+void ProtoStreamObjectWriter::Push(StringPiece name,
+ Item::ItemType item_type,
bool is_placeholder, bool is_list) {
is_list ? ProtoWriter::StartList(name) : ProtoWriter::StartObject(name);
@@ -1247,7 +1281,7 @@ bool ProtoStreamObjectWriter::IsMap(const google::protobuf::Field& field) {
const google::protobuf::Type* field_type =
typeinfo()->GetTypeByTypeUrl(field.type_url());
- return google::protobuf::util::converter::IsMap(field, *field_type);
+ return converter::IsMap(field, *field_type);
}
bool ProtoStreamObjectWriter::IsAny(const google::protobuf::Field& field) {
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h
index c33a4639..fe8170d1 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -32,8 +32,9 @@
#define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTWRITER_H__
#include <deque>
-#include <google/protobuf/stubs/hash.h>
#include <string>
+#include <unordered_map>
+#include <unordered_set>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
@@ -46,6 +47,9 @@
#include <google/protobuf/util/internal/structured_objectwriter.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/bytestream.h>
+#include <google/protobuf/stubs/hash.h>
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -53,14 +57,16 @@ namespace io {
class CodedOutputStream;
} // namespace io
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
class Type;
class Field;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
@@ -72,7 +78,7 @@ class ObjectLocationTracker;
// the ProtoWriter class to write raw proto bytes.
//
// It also supports streaming.
-class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
+class PROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
public:
// Options that control ProtoStreamObjectWriter class's behavior.
struct Options {
@@ -87,17 +93,27 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
bool struct_integers_as_strings;
// Not treat unknown fields as an error. If there is an unknown fields,
- // just ignore it and continue to process the rest.
+ // just ignore it and continue to process the rest. Note that this doesn't
+ // apply to unknown enum values.
bool ignore_unknown_fields;
+ // Ignore unknown enum values.
+ bool ignore_unknown_enum_values;
+
// If true, check if enum name in camel case or without underscore matches
// the field name.
bool use_lower_camel_for_enums;
+ // If true, skips rendering the map entry if map value is null unless the
+ // value type is google.protobuf.NullType.
+ bool ignore_null_value_map_entry;
+
Options()
: struct_integers_as_strings(false),
ignore_unknown_fields(false),
- use_lower_camel_for_enums(false) {}
+ ignore_unknown_enum_values(false),
+ use_lower_camel_for_enums(false),
+ ignore_null_value_map_entry(false) {}
// Default instance of Options with all options set to defaults.
static const Options& Defaults() {
@@ -112,18 +128,18 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
strings::ByteSink* output, ErrorListener* listener,
const ProtoStreamObjectWriter::Options& options =
ProtoStreamObjectWriter::Options::Defaults());
- virtual ~ProtoStreamObjectWriter();
+ ~ProtoStreamObjectWriter() override;
// ObjectWriter methods.
- virtual ProtoStreamObjectWriter* StartObject(StringPiece name);
- virtual ProtoStreamObjectWriter* EndObject();
- virtual ProtoStreamObjectWriter* StartList(StringPiece name);
- virtual ProtoStreamObjectWriter* EndList();
+ ProtoStreamObjectWriter* StartObject(StringPiece name) override;
+ ProtoStreamObjectWriter* EndObject() override;
+ ProtoStreamObjectWriter* StartList(StringPiece name) override;
+ ProtoStreamObjectWriter* EndList() override;
// Renders a DataPiece 'value' into a field whose wire type is determined
// from the given field 'name'.
- virtual ProtoStreamObjectWriter* RenderDataPiece(StringPiece name,
- const DataPiece& value);
+ ProtoStreamObjectWriter* RenderDataPiece(StringPiece name,
+ const DataPiece& data) override;
protected:
// Function that renders a well known type with modified behavior.
@@ -131,7 +147,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
const DataPiece&);
// Handles writing Anys out using nested object writers and the like.
- class LIBPROTOBUF_EXPORT AnyWriter {
+ class PROTOBUF_EXPORT AnyWriter {
public:
explicit AnyWriter(ProtoStreamObjectWriter* parent);
~AnyWriter();
@@ -156,7 +172,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
private:
// Before the "@type" field is encountered, we store all incoming data
// into this Event struct and replay them after we get the "@type" field.
- class LIBPROTOBUF_EXPORT Event {
+ class PROTOBUF_EXPORT Event {
public:
enum Type {
START_OBJECT = 0,
@@ -171,13 +187,11 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// Constructor for START_OBJECT and START_LIST events.
explicit Event(Type type, StringPiece name)
- : type_(type),
- name_(name.ToString()),
- value_(DataPiece::NullData()) {}
+ : type_(type), name_(name), value_(DataPiece::NullData()) {}
// Constructor for RENDER_DATA_PIECE events.
explicit Event(StringPiece name, const DataPiece& value)
- : type_(RENDER_DATA_PIECE), name_(name.ToString()), value_(value) {
+ : type_(RENDER_DATA_PIECE), name_(name), value_(value) {
DeepCopy();
}
@@ -200,9 +214,9 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
void DeepCopy();
Type type_;
- string name_;
+ std::string name_;
DataPiece value_;
- string value_storage_;
+ std::string value_storage_;
};
// Handles starting up the any once we have a type.
@@ -219,14 +233,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
std::unique_ptr<ProtoStreamObjectWriter> ow_;
// The type_url_ that this Any represents.
- string type_url_;
+ std::string type_url_;
// Whether this any is invalid. This allows us to only report an invalid
// Any message a single time rather than every time we get a nested field.
bool invalid_;
// The output data and wrapping ByteSink.
- string data_;
+ std::string data_;
strings::StringByteSink output_;
// The depth within the Any, so we can track when we're done.
@@ -247,7 +261,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// Represents an item in a stack of items used to keep state between
// ObjectWrier events.
- class LIBPROTOBUF_EXPORT Item : public BaseElement {
+ class PROTOBUF_EXPORT Item : public BaseElement {
public:
// Indicates the type of item.
enum ItemType {
@@ -263,7 +277,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// Constructor for a field of a message.
Item(Item* parent, ItemType item_type, bool is_placeholder, bool is_list);
- virtual ~Item() {}
+ ~Item() override {}
// These functions return true if the element type is corresponding to the
// type in function name.
@@ -272,7 +286,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
AnyWriter* any() const { return any_.get(); }
- virtual Item* parent() const {
+ Item* parent() const override {
return static_cast<Item*>(BaseElement::parent());
}
@@ -299,7 +313,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// Set of map keys already seen for the type_. Used to validate incoming
// messages so no map key appears more than once.
- std::unique_ptr<hash_set<string> > map_keys_;
+ std::unique_ptr<std::unordered_set<std::string> > map_keys_;
// Conveys whether this Item is a placeholder or not. Placeholder items are
// pushed to stack to account for special types.
@@ -316,6 +330,11 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
const google::protobuf::Type& type,
strings::ByteSink* output, ErrorListener* listener);
+ ProtoStreamObjectWriter(const TypeInfo* typeinfo,
+ const google::protobuf::Type& type,
+ strings::ByteSink* output, ErrorListener* listener,
+ const ProtoStreamObjectWriter::Options& options);
+
// Returns true if the field is a map.
inline bool IsMap(const google::protobuf::Field& field);
@@ -355,7 +374,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
static void InitRendererMap();
static void DeleteRendererMap();
- static TypeRenderer* FindTypeRenderer(const string& type_url);
+ static TypeRenderer* FindTypeRenderer(const std::string& type_url);
// Returns true if the map key for type_ is not duplicated key.
// If map key is duplicated key, this function returns false.
@@ -371,8 +390,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// is_placeholder conveys whether the item is a placeholder item or not.
// Placeholder items are pushed when adding auxillary types' StartObject or
// StartList calls.
- void Push(StringPiece name, Item::ItemType item_type, bool is_placeholder,
- bool is_list);
+ void Push(StringPiece name, Item::ItemType item_type,
+ bool is_placeholder, bool is_list);
// Pops items from the stack. All placeholder items are popped until a
// non-placeholder item is found.
@@ -385,7 +404,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
private:
// Helper functions to create the map and find functions responsible for
// rendering well known types, keyed by type URL.
- static hash_map<string, TypeRenderer>* renderers_;
+ static std::unordered_map<std::string, TypeRenderer>* renderers_;
// Variables for describing the structure of the input tree:
// master_type_: descriptor for the whole protobuf message.
@@ -403,6 +422,8 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
index 7f0df567..66a8f003 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
@@ -58,6 +58,7 @@
#include <gtest/gtest.h>
+
namespace google {
namespace protobuf {
namespace util {
@@ -79,11 +80,6 @@ using google::protobuf::testing::TestJsonName2;
using google::protobuf::testing::TimestampDuration;
using google::protobuf::testing::ValueWrapper;
using google::protobuf::testing::oneofs::OneOfsRequest;
-using google::protobuf::Descriptor;
-using google::protobuf::DescriptorPool;
-using google::protobuf::DynamicMessageFactory;
-using google::protobuf::FileDescriptorProto;
-using google::protobuf::Message;
using strings::GrowingArrayByteSink;
using ::testing::_;
using ::testing::Args;
@@ -274,7 +270,7 @@ TEST_P(ProtoStreamObjectWriterTest, CustomJsonName) {
}
// Test that two messages can have different fields mapped to the same JSON
-// name. See: https://github.com/google/protobuf/issues/1415
+// name. See: https://github.com/protocolbuffers/protobuf/issues/1415
TEST_P(ProtoStreamObjectWriterTest, ConflictingJsonName) {
ResetTypeInfo(TestJsonName1::descriptor());
TestJsonName1 message1;
@@ -517,8 +513,8 @@ TEST_P(ProtoStreamObjectWriterTest, NaNInputTest) {
EXPECT_CALL(listener_, InvalidValue(_, StringPiece("TYPE_SFIXED64"),
StringPiece("\"NaN\"")))
.With(Args<0>(HasObjectLocation("sf64")));
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("TYPE_BOOL"), StringPiece("\"NaN\"")))
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("TYPE_BOOL"),
+ StringPiece("\"NaN\"")))
.With(Args<0>(HasObjectLocation("bool")));
ow_->StartObject("")
@@ -591,9 +587,9 @@ TEST_P(ProtoStreamObjectWriterTest, NonRepeatedExplicitPrimitiveList) {
EXPECT_CALL(
listener_,
- InvalidName(
- _, StringPiece("name"),
- StringPiece("Proto field is not repeating, cannot start list.")))
+ InvalidName(_, StringPiece("name"),
+ StringPiece(
+ "Proto field is not repeating, cannot start list.")))
.With(Args<0>(HasObjectLocation("author")));
ow_->StartObject("")
->StartObject("author")
@@ -687,9 +683,9 @@ TEST_P(ProtoStreamObjectWriterTest, NonRepeatedExplicitMessageList) {
EXPECT_CALL(
listener_,
- InvalidName(
- _, StringPiece("publisher"),
- StringPiece("Proto field is not repeating, cannot start list.")))
+ InvalidName(_, StringPiece("publisher"),
+ StringPiece(
+ "Proto field is not repeating, cannot start list.")))
.With(Args<0>(HasObjectLocation("")));
ow_->StartObject("")
->StartObject("author")
@@ -925,6 +921,22 @@ TEST_P(ProtoStreamObjectWriterTest, IgnoreUnknownListAtPublisher) {
CheckOutput(expected);
}
+TEST_P(ProtoStreamObjectWriterTest,
+ IgnoreUnknownFieldsDontIgnoreUnknownEnumValues) {
+ ResetTypeInfo(Proto3Message::descriptor());
+
+ Proto3Message expected;
+ EXPECT_CALL(
+ listener_,
+ InvalidValue(_, StringPiece("TYPE_ENUM"),
+ StringPiece("\"someunknownvalueyouwillneverknow\"")))
+ .With(Args<0>(HasObjectLocation("enum_value")));
+ ow_->StartObject("")
+ ->RenderString("enumValue", "someunknownvalueyouwillneverknow")
+ ->EndObject();
+ CheckOutput(expected);
+}
+
TEST_P(ProtoStreamObjectWriterTest, AcceptUnknownEnumValue) {
ResetTypeInfo(Proto3Message::descriptor());
@@ -1030,9 +1042,10 @@ TEST_P(ProtoStreamObjectWriterTest, RootNamedObject) {
Book expected;
expected.set_title("Annie");
- EXPECT_CALL(listener_,
- InvalidName(_, StringPiece("oops"),
- StringPiece("Root element should not be named.")))
+ EXPECT_CALL(
+ listener_,
+ InvalidName(_, StringPiece("oops"),
+ StringPiece("Root element should not be named.")))
.With(Args<0>(HasObjectLocation("")));
ow_->StartObject("oops")->RenderString("title", "Annie")->EndObject();
CheckOutput(expected, 7);
@@ -1041,9 +1054,10 @@ TEST_P(ProtoStreamObjectWriterTest, RootNamedObject) {
TEST_P(ProtoStreamObjectWriterTest, RootNamedList) {
Book empty;
- EXPECT_CALL(listener_,
- InvalidName(_, StringPiece("oops"),
- StringPiece("Root element should not be named.")))
+ EXPECT_CALL(
+ listener_,
+ InvalidName(_, StringPiece("oops"),
+ StringPiece("Root element should not be named.")))
.With(Args<0>(HasObjectLocation("")));
ow_->StartList("oops")->RenderString("", "item")->EndList();
CheckOutput(empty, 0);
@@ -1179,10 +1193,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2016-03-07T15:14:23+")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2016-03-07T15:14:23+")));
ow_->StartObject("")->RenderString("ts", "2016-03-07T15:14:23+")->EndObject();
CheckOutput(timestamp);
@@ -1194,10 +1208,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2016-03-07T15:14:23+08-10")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2016-03-07T15:14:23+08-10")));
ow_->StartObject("")
->RenderString("ts", "2016-03-07T15:14:23+08-10")
@@ -1211,10 +1225,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2016-03-07T15:14:23+24:10")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2016-03-07T15:14:23+24:10")));
ow_->StartObject("")
->RenderString("ts", "2016-03-07T15:14:23+24:10")
@@ -1228,10 +1242,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2016-03-07T15:14:23+04:60")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2016-03-07T15:14:23+04:60")));
ow_->StartObject("")
->RenderString("ts", "2016-03-07T15:14:23+04:60")
@@ -1244,9 +1258,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError1) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: ")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: ")));
ow_->StartObject("")->RenderString("ts", "")->EndObject();
CheckOutput(timestamp);
@@ -1257,9 +1271,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError2) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: Z")));
ow_->StartObject("")->RenderString("ts", "Z")->EndObject();
CheckOutput(timestamp);
@@ -1270,10 +1284,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError3) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "1970-01-01T00:00:00.ABZ")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "1970-01-01T00:00:00.ABZ")));
ow_->StartObject("")
->RenderString("ts", "1970-01-01T00:00:00.ABZ")
@@ -1286,10 +1300,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError4) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "-8031-10-18T00:00:00.000Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "-8031-10-18T00:00:00.000Z")));
ow_->StartObject("")
->RenderString("ts", "-8031-10-18T00:00:00.000Z")
@@ -1302,10 +1316,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError5) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2015-11-23T03:37:35.033155 Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2015-11-23T03:37:35.033155 Z")));
ow_->StartObject("")
// Whitespace in the Timestamp nanos is not allowed.
@@ -1319,10 +1333,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError6) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2015-11-23T03:37:35.033155 1234Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2015-11-23T03:37:35.033155 1234Z")));
ow_->StartObject("")
// Whitespace in the Timestamp nanos is not allowed.
@@ -1336,10 +1350,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError7) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "2015-11-23T03:37:35.033abc155Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "2015-11-23T03:37:35.033abc155Z")));
ow_->StartObject("")
// Non-numeric characters in the Timestamp nanos is not allowed.
@@ -1353,10 +1367,10 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidTimestampError8) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
- StringPiece("Field 'ts', Invalid time format: "
- "0-12-31T23:59:59.000Z")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
+ StringPiece("Field 'ts', Invalid time format: "
+ "0-12-31T23:59:59.000Z")));
ow_->StartObject("")
->RenderString("ts", "0-12-31T23:59:59.000Z")
@@ -1381,8 +1395,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidDurationError1) {
listener_,
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.Duration"),
- StringPiece("Field 'dur', Illegal duration format; duration must "
- "end with 's'")));
+ StringPiece(
+ "Field 'dur', Illegal duration format; duration must "
+ "end with 's'")));
ow_->StartObject("")->RenderString("dur", "")->EndObject();
CheckOutput(duration);
@@ -1395,8 +1410,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidDurationError2) {
listener_,
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.Duration"),
- StringPiece("Field 'dur', Invalid duration format, failed to parse "
- "seconds")));
+ StringPiece(
+ "Field 'dur', Invalid duration format, failed to parse "
+ "seconds")));
ow_->StartObject("")->RenderString("dur", "s")->EndObject();
CheckOutput(duration);
@@ -1410,7 +1426,7 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidDurationError3) {
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.Duration"),
StringPiece("Field 'dur', Invalid duration format, failed to "
- "parse nano seconds")));
+ "parse nano seconds")));
ow_->StartObject("")->RenderString("dur", "123.DEFs")->EndObject();
CheckOutput(duration);
@@ -1421,9 +1437,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidDurationError4) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Duration"),
- StringPiece("Field 'dur', Duration value exceeds limits")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Duration"),
+ StringPiece("Field 'dur', Duration value exceeds limits")));
ow_->StartObject("")->RenderString("dur", "315576000002s")->EndObject();
CheckOutput(duration);
@@ -1434,9 +1450,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest, InvalidDurationError5) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.Duration"),
- StringPiece("Field 'dur', Duration value exceeds limits")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Duration"),
+ StringPiece("Field 'dur', Duration value exceeds limits")));
ow_->StartObject("")->RenderString("dur", "0.1000000001s")->EndObject();
CheckOutput(duration);
@@ -1533,8 +1549,9 @@ TEST_P(ProtoStreamObjectWriterStructTest, StructInvalidInputFailure) {
StructType struct_type;
EXPECT_CALL(
listener_,
- InvalidValue(_, StringPiece("type.googleapis.com/google.protobuf.Struct"),
- StringPiece("true")))
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.Struct"),
+ StringPiece("true")))
.With(Args<0>(HasObjectLocation("object")));
ow_->StartObject("")->RenderBool("object", true)->EndObject();
@@ -1564,10 +1581,10 @@ TEST_P(ProtoStreamObjectWriterStructTest, StructValuePreservesNull) {
}
TEST_P(ProtoStreamObjectWriterStructTest, SimpleRepeatedStructMapKeyTest) {
- EXPECT_CALL(
- listener_,
- InvalidName(_, StringPiece("gBike"),
- StringPiece("Repeated map key: 'gBike' is already set.")));
+ EXPECT_CALL(listener_,
+ InvalidName(_, StringPiece("gBike"),
+ StringPiece(
+ "Repeated map key: 'gBike' is already set.")));
ow_->StartObject("")
->StartObject("object")
->RenderString("gBike", "v1")
@@ -1641,8 +1658,12 @@ TEST_P(ProtoStreamObjectWriterStructTest, ValuePreservesNull) {
class ProtoStreamObjectWriterMapTest : public BaseProtoStreamObjectWriterTest {
protected:
- ProtoStreamObjectWriterMapTest()
- : BaseProtoStreamObjectWriterTest(MapIn::descriptor()) {}
+ ProtoStreamObjectWriterMapTest() {
+ std::vector<const Descriptor*> descriptors;
+ descriptors.push_back(MapIn::descriptor());
+ descriptors.push_back(google::protobuf::DoubleValue::descriptor());
+ ResetTypeInfo(descriptors);
+ }
};
INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest,
@@ -1654,9 +1675,9 @@ TEST_P(ProtoStreamObjectWriterMapTest, MapShouldNotAcceptList) {
MapIn mm;
EXPECT_CALL(
listener_,
- InvalidValue(
- _, StringPiece("Map"),
- StringPiece("Cannot bind a list to map for field 'map_input'.")));
+ InvalidValue(_, StringPiece("Map"),
+ StringPiece(
+ "Cannot bind a list to map for field 'map_input'.")));
ow_->StartObject("")
->StartList("map_input")
->RenderString("a", "b")
@@ -1665,6 +1686,36 @@ TEST_P(ProtoStreamObjectWriterMapTest, MapShouldNotAcceptList) {
CheckOutput(mm);
}
+TEST_P(ProtoStreamObjectWriterMapTest, MapAcceptsNullValue) {
+ // Null should not be a valid map value.
+ // See http://go/proto3-json-spec#heading=h.r2ddatp7y4vi
+ // This test is added for backward compatibility.
+ MapIn mm;
+ (*mm.mutable_map_input())["a"] = "b";
+ (*mm.mutable_map_input())["x"] = "";
+ ow_->StartObject("")
+ ->StartObject("map_input")
+ ->RenderString("a", "b")
+ ->RenderNull("x")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(mm);
+}
+
+TEST_P(ProtoStreamObjectWriterMapTest, MapShouldIgnoreNullValueEntry) {
+ options_.ignore_null_value_map_entry = true;
+ ResetTypeInfo(MapIn::descriptor());
+ MapIn mm;
+ (*mm.mutable_map_input())["a"] = "b";
+ ow_->StartObject("")
+ ->StartObject("map_input")
+ ->RenderString("a", "b")
+ ->RenderNull("x")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(mm);
+}
+
TEST_P(ProtoStreamObjectWriterMapTest, RepeatedMapKeyTest) {
EXPECT_CALL(
listener_,
@@ -1679,6 +1730,22 @@ TEST_P(ProtoStreamObjectWriterMapTest, RepeatedMapKeyTest) {
->EndObject();
}
+TEST_P(ProtoStreamObjectWriterMapTest, AnyInMap) {
+ MapIn mm;
+ google::protobuf::DoubleValue d;
+ d.set_value(40.2);
+ (*mm.mutable_map_any())["foo"].PackFrom(d);
+ ow_->StartObject("")
+ ->StartObject("map_any")
+ ->StartObject("foo")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.DoubleValue")
+ ->RenderDouble("value", 40.2)
+ ->EndObject()
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(mm);
+}
+
class ProtoStreamObjectWriterAnyTest : public BaseProtoStreamObjectWriterTest {
protected:
ProtoStreamObjectWriterAnyTest() {
@@ -1883,10 +1950,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, EmptyAnyFromEmptyObject) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails1) {
AnyOut any;
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing @type for any field in "
- "google.protobuf.testing.AnyOut")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("Any"),
+ StringPiece(
+ "Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1900,10 +1967,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails1) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails2) {
AnyOut any;
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing @type for any field in "
- "google.protobuf.testing.AnyOut")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("Any"),
+ StringPiece(
+ "Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1917,10 +1984,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails2) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails3) {
AnyOut any;
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing @type for any field in "
- "google.protobuf.testing.AnyOut")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("Any"),
+ StringPiece(
+ "Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1933,12 +2000,13 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails3) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithInvalidTypeUrlFails) {
AnyOut any;
- EXPECT_CALL(listener_,
- InvalidValue(
- _, StringPiece("Any"),
- StringPiece("Invalid type URL, type URLs must be of the form "
- "'type.googleapis.com/<typename>', got: "
- "type.other.com/some.Type")));
+ EXPECT_CALL(
+ listener_,
+ InvalidValue(
+ _, StringPiece("Any"),
+ StringPiece("Invalid type URL, type URLs must be of the form "
+ "'type.googleapis.com/<typename>', got: "
+ "type.other.com/some.Type")));
ow_->StartObject("")
->StartObject("any")
@@ -1952,10 +2020,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithInvalidTypeUrlFails) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithUnknownTypeFails) {
AnyOut any;
- EXPECT_CALL(
- listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Invalid type URL, unknown type: some.Type")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece(
+ "Invalid type URL, unknown type: some.Type")));
ow_->StartObject("")
->StartObject("any")
->RenderString("@type", "type.googleapis.com/some.Type")
@@ -1970,7 +2038,8 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyIncorrectInputTypeFails) {
EXPECT_CALL(
listener_,
- InvalidValue(_, StringPiece("type.googleapis.com/google.protobuf.Any"),
+ InvalidValue(_,
+ StringPiece("type.googleapis.com/google.protobuf.Any"),
StringPiece("1")));
ow_->StartObject("")->RenderInt32("any", 1)->EndObject();
CheckOutput(any);
@@ -2178,8 +2247,9 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWellKnownTypesNoValueFieldForArray) {
// }
// }
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWellKnownTypesExpectObjectForStruct) {
- EXPECT_CALL(listener_, InvalidValue(_, StringPiece("Any"),
- StringPiece("Expect a JSON object.")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece("Expect a JSON object.")));
AnyOut any;
google::protobuf::Any* any_type = any.mutable_any();
any_type->set_type_url("type.googleapis.com/google.protobuf.Struct");
@@ -2202,8 +2272,9 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWellKnownTypesExpectObjectForStruct) {
// }
// }
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWellKnownTypesExpectObjectForAny) {
- EXPECT_CALL(listener_, InvalidValue(_, StringPiece("Any"),
- StringPiece("Expect a JSON object.")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece("Expect a JSON object.")));
AnyOut any;
google::protobuf::Any* any_type = any.mutable_any();
any_type->set_type_url("type.googleapis.com/google.protobuf.Any");
@@ -2464,7 +2535,7 @@ TEST_P(ProtoStreamObjectWriterFieldMaskTest, MoreCloseThanOpenParentheses) {
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
StringPiece("Field 'single_mask', Invalid FieldMask 'a(b,c))'. "
- "Cannot find matching '(' for all ')'.")));
+ "Cannot find matching '(' for all ')'.")));
ow_->StartObject("");
ow_->RenderString("id", "1");
@@ -2509,9 +2580,10 @@ TEST_P(ProtoStreamObjectWriterFieldMaskTest,
listener_,
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
- StringPiece("Field 'single_mask', Invalid FieldMask "
- "'path.to.map[\"key1\"]a,path.to.map[\"key2\"]'. "
- "Map keys should be at the end of a path segment.")));
+ StringPiece(
+ "Field 'single_mask', Invalid FieldMask "
+ "'path.to.map[\"key1\"]a,path.to.map[\"key2\"]'. "
+ "Map keys should be at the end of a path segment.")));
ow_->StartObject("");
ow_->RenderString("single_mask",
@@ -2522,11 +2594,11 @@ TEST_P(ProtoStreamObjectWriterFieldMaskTest,
TEST_P(ProtoStreamObjectWriterFieldMaskTest, MapKeyMustEnd) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
- StringPiece("Field 'single_mask', Invalid FieldMask "
- "'path.to.map[\"key1\"'. Map keys should be "
- "represented as [\"some_key\"].")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
+ StringPiece("Field 'single_mask', Invalid FieldMask "
+ "'path.to.map[\"key1\"'. Map keys should be "
+ "represented as [\"some_key\"].")));
ow_->StartObject("");
ow_->RenderString("single_mask", "path.to.map[\"key1\"");
@@ -2536,11 +2608,11 @@ TEST_P(ProtoStreamObjectWriterFieldMaskTest, MapKeyMustEnd) {
TEST_P(ProtoStreamObjectWriterFieldMaskTest, MapKeyMustBeEscapedCorrectly) {
EXPECT_CALL(
listener_,
- InvalidValue(_,
- StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
- StringPiece("Field 'single_mask', Invalid FieldMask "
- "'path.to.map[\"ke\"y1\"]'. Map keys should be "
- "represented as [\"some_key\"].")));
+ InvalidValue(
+ _, StringPiece("type.googleapis.com/google.protobuf.FieldMask"),
+ StringPiece("Field 'single_mask', Invalid FieldMask "
+ "'path.to.map[\"ke\"y1\"]'. Map keys should be "
+ "represented as [\"some_key\"].")));
ow_->StartObject("");
ow_->RenderString("single_mask", "path.to.map[\"ke\"y1\"]");
@@ -2631,10 +2703,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForMessageTypesPrimitiveFirstTest) {
// Test for setting primitive oneof field first and then message field.
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'messageData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'messageData'")));
// JSON: { "strData": "blah", "messageData": { "dataValue": 123 } }
ow_->StartObject("");
@@ -2648,10 +2720,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForMessageTypesMessageFirstTest) {
// Test for setting message oneof field first and then primitive field.
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'strData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'strData'")));
// JSON: { "messageData": { "dataValue": 123 }, "strData": "blah" }
ow_->StartObject("");
@@ -2664,10 +2736,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForStructTypesPrimitiveFirstTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'structData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'structData'")));
// JSON: { "strData": "blah", "structData": { "a": "b" } }
ow_->StartObject("");
@@ -2680,10 +2752,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForStructTypesStructFirstTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'strData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'strData'")));
// JSON: { "structData": { "a": "b" }, "strData": "blah" }
ow_->StartObject("");
@@ -2696,10 +2768,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForStructValueTypesTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'valueData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'valueData'")));
// JSON: { "messageData": { "dataValue": 123 }, "valueData": { "a": "b" } }
ow_->StartObject("");
@@ -2714,10 +2786,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForWellKnownTypesPrimitiveFirstTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'tsData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'tsData'")));
// JSON: { "intData": 123, "tsData": "1970-01-02T01:00:00.000Z" }
ow_->StartObject("");
@@ -2728,10 +2800,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForWellKnownTypesWktFirstTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'intData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'intData'")));
// JSON: { "tsData": "1970-01-02T01:00:00.000Z", "intData": 123 }
ow_->StartObject("");
@@ -2742,10 +2814,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForWellKnownTypesAndMessageTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'messageData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'messageData'")));
// JSON: { "tsData": "1970-01-02T01:00:00.000Z",
// "messageData": { "dataValue": 123 } }
@@ -2759,10 +2831,10 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
TEST_P(ProtoStreamObjectWriterOneOfsTest,
MultipleOneofsFailForOneofWithinAnyTest) {
- EXPECT_CALL(listener_,
- InvalidValue(_, StringPiece("oneof"),
- StringPiece("oneof field 'data' is already set. "
- "Cannot set 'intData'")));
+ EXPECT_CALL(listener_, InvalidValue(_, StringPiece("oneof"),
+ StringPiece(
+ "oneof field 'data' is already set. "
+ "Cannot set 'intData'")));
// JSON:
// { "anyData":
diff --git a/src/google/protobuf/util/internal/structured_objectwriter.h b/src/google/protobuf/util/internal/structured_objectwriter.h
index 8e63222b..bccea718 100644
--- a/src/google/protobuf/util/internal/structured_objectwriter.h
+++ b/src/google/protobuf/util/internal/structured_objectwriter.h
@@ -37,6 +37,8 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/util/internal/object_writer.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -53,7 +55,7 @@ namespace converter {
// StructuredObjectWriter and its use.
//
// Derived classes could be thread-unsafe.
-class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
+class PROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
public:
virtual ~StructuredObjectWriter() {}
@@ -63,7 +65,7 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
// StructuredObjectWriter behaves as a visitor. BaseElement represents a node
// in the input tree. Implementation of StructuredObjectWriter should also
// extend BaseElement to keep track of the location in the input tree.
- class LIBPROTOBUF_EXPORT BaseElement {
+ class PROTOBUF_EXPORT BaseElement {
public:
// Takes ownership of the parent Element.
explicit BaseElement(BaseElement* parent)
@@ -110,6 +112,8 @@ class LIBPROTOBUF_EXPORT StructuredObjectWriter : public ObjectWriter {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_STRUCTURED_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/testdata/anys.proto b/src/google/protobuf/util/internal/testdata/anys.proto
index a9ebca3d..77c1043b 100644
--- a/src/google/protobuf/util/internal/testdata/anys.proto
+++ b/src/google/protobuf/util/internal/testdata/anys.proto
@@ -57,6 +57,7 @@ message AnyTestCases {
AnyWrapper any_with_message_containing_struct = 13;
AnyWrapper any_with_message_containing_repeated_message = 14;
AnyWrapper recursive_any_with_type_field_at_end = 15;
+ AnyWrapper repeated_any = 16;
google.protobuf.Any top_level_any = 50;
google.protobuf.Any top_level_any_with_type_field_at_end = 51;
@@ -87,6 +88,7 @@ message Data {
map<string, string> map_data = 7;
google.protobuf.Struct struct_data = 8;
repeated Data repeated_data = 9;
+ repeated google.protobuf.Any repeated_any = 10;
}
service AnyTestService {
diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto
index 5630cc78..812474bb 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -69,6 +69,9 @@ message Book {
}
optional Type type = 11;
+ // Useful for testing JSON snake/camel-case conversions.
+ optional string snake_field = 12;
+
extensions 200 to 499;
}
@@ -193,7 +196,7 @@ message Cyclic {
}
// Test that two messages can have different fields mapped to the same JSON
-// name. See: https://github.com/google/protobuf/issues/1415
+// name. See: https://github.com/protocolbuffers/protobuf/issues/1415
message TestJsonName1 {
optional int32 one_value = 1 [json_name = "value"];
}
diff --git a/src/google/protobuf/util/internal/testdata/maps.proto b/src/google/protobuf/util/internal/testdata/maps.proto
index 0f381b32..765254ea 100644
--- a/src/google/protobuf/util/internal/testdata/maps.proto
+++ b/src/google/protobuf/util/internal/testdata/maps.proto
@@ -32,6 +32,8 @@ syntax = "proto3";
package google.protobuf.testing;
+import "google/protobuf/any.proto";
+
// Top-level test cases proto used by MarshallingTest. See description
// at the top of the class MarshallingTest for details on how to write
// test cases.
@@ -103,6 +105,7 @@ message MapIn {
string other = 1;
repeated string things = 2;
map<string, string> map_input = 3;
+ map<string, google.protobuf.Any> map_any = 4;
}
message MapOut {
diff --git a/src/google/protobuf/util/internal/type_info.cc b/src/google/protobuf/util/internal/type_info.cc
index 3847b179..60cc3fc0 100644
--- a/src/google/protobuf/util/internal/type_info.cc
+++ b/src/google/protobuf/util/internal/type_info.cc
@@ -58,8 +58,8 @@ class TypeInfoForTypeResolver : public TypeInfo {
DeleteCachedTypes(&cached_enums_);
}
- virtual util::StatusOr<const google::protobuf::Type*> ResolveTypeUrl(
- StringPiece type_url) const {
+ util::StatusOr<const google::protobuf::Type*> ResolveTypeUrl(
+ StringPiece type_url) const override {
std::map<StringPiece, StatusOrType>::iterator it =
cached_types_.find(type_url);
if (it != cached_types_.end()) {
@@ -68,7 +68,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
// Stores the string value so it can be referenced using StringPiece in the
// cached_types_ map.
const string& string_type_url =
- *string_storage_.insert(type_url.ToString()).first;
+ *string_storage_.insert(string(type_url)).first;
std::unique_ptr<google::protobuf::Type> type(new google::protobuf::Type());
util::Status status =
type_resolver_->ResolveMessageType(string_type_url, type.get());
@@ -78,14 +78,14 @@ class TypeInfoForTypeResolver : public TypeInfo {
return result;
}
- virtual const google::protobuf::Type* GetTypeByTypeUrl(
- StringPiece type_url) const {
+ const google::protobuf::Type* GetTypeByTypeUrl(
+ StringPiece type_url) const override {
StatusOrType result = ResolveTypeUrl(type_url);
return result.ok() ? result.ValueOrDie() : NULL;
}
- virtual const google::protobuf::Enum* GetEnumByTypeUrl(
- StringPiece type_url) const {
+ const google::protobuf::Enum* GetEnumByTypeUrl(
+ StringPiece type_url) const override {
std::map<StringPiece, StatusOrEnum>::iterator it =
cached_enums_.find(type_url);
if (it != cached_enums_.end()) {
@@ -94,7 +94,7 @@ class TypeInfoForTypeResolver : public TypeInfo {
// Stores the string value so it can be referenced using StringPiece in the
// cached_enums_ map.
const string& string_type_url =
- *string_storage_.insert(type_url.ToString()).first;
+ *string_storage_.insert(string(type_url)).first;
std::unique_ptr<google::protobuf::Enum> enum_type(
new google::protobuf::Enum());
util::Status status =
@@ -105,16 +105,17 @@ class TypeInfoForTypeResolver : public TypeInfo {
return result.ok() ? result.ValueOrDie() : NULL;
}
- virtual const google::protobuf::Field* FindField(
- const google::protobuf::Type* type, StringPiece camel_case_name) const {
+ const google::protobuf::Field* FindField(
+ const google::protobuf::Type* type,
+ StringPiece camel_case_name) const override {
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());
+ StringPiece name = FindWithDefault(
+ camel_case_name_table, camel_case_name, StringPiece());
if (name.empty()) {
// Didn't find a mapping. Use whatever provided.
name = camel_case_name;
@@ -129,7 +130,8 @@ class TypeInfoForTypeResolver : public TypeInfo {
template <typename T>
static void DeleteCachedTypes(std::map<StringPiece, T>* cached_types) {
- for (typename std::map<StringPiece, T>::iterator it = cached_types->begin();
+ for (typename std::map<StringPiece, T>::iterator it =
+ cached_types->begin();
it != cached_types->end(); ++it) {
if (it->second.ok()) {
delete it->second.ValueOrDie();
@@ -144,8 +146,8 @@ class TypeInfoForTypeResolver : public TypeInfo {
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
diff --git a/src/google/protobuf/util/internal/type_info.h b/src/google/protobuf/util/internal/type_info.h
index d8133176..b933b77a 100644
--- a/src/google/protobuf/util/internal/type_info.h
+++ b/src/google/protobuf/util/internal/type_info.h
@@ -38,13 +38,15 @@
#include <google/protobuf/stubs/status.h>
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
namespace converter {
// Internal helper class for type resolving. Note that this class is not
// thread-safe and should only be accessed in one thread.
-class LIBPROTOBUF_EXPORT TypeInfo {
+class PROTOBUF_EXPORT TypeInfo {
public:
TypeInfo() {}
virtual ~TypeInfo() {}
@@ -87,6 +89,8 @@ class LIBPROTOBUF_EXPORT TypeInfo {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_TYPE_INFO_H__
diff --git a/src/google/protobuf/util/internal/type_info_test_helper.cc b/src/google/protobuf/util/internal/type_info_test_helper.cc
index 281a7f58..dfd86fa3 100644
--- a/src/google/protobuf/util/internal/type_info_test_helper.cc
+++ b/src/google/protobuf/util/internal/type_info_test_helper.cc
@@ -33,6 +33,7 @@
#include <memory>
#include <vector>
+
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
diff --git a/src/google/protobuf/util/internal/type_info_test_helper.h b/src/google/protobuf/util/internal/type_info_test_helper.h
index 5a077e04..3cafbceb 100644
--- a/src/google/protobuf/util/internal/type_info_test_helper.h
+++ b/src/google/protobuf/util/internal/type_info_test_helper.h
@@ -72,13 +72,13 @@ class TypeInfoTestHelper {
TypeInfo* GetTypeInfo();
ProtoStreamObjectSource* NewProtoSource(io::CodedInputStream* coded_input,
- const string& type_url);
+ const std::string& type_url);
ProtoStreamObjectWriter* NewProtoWriter(
- const string& type_url, strings::ByteSink* output,
+ const std::string& type_url, strings::ByteSink* output,
ErrorListener* listener, const ProtoStreamObjectWriter::Options& options);
- DefaultValueObjectWriter* NewDefaultValueWriter(const string& type_url,
+ DefaultValueObjectWriter* NewDefaultValueWriter(const std::string& type_url,
ObjectWriter* writer);
private:
@@ -90,6 +90,6 @@ class TypeInfoTestHelper {
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_TYPE_INFO_TEST_HELPER_H__
diff --git a/src/google/protobuf/util/internal/utility.cc b/src/google/protobuf/util/internal/utility.cc
index b8d917ce..7c7e3f1c 100644
--- a/src/google/protobuf/util/internal/utility.cc
+++ b/src/google/protobuf/util/internal/utility.cc
@@ -43,13 +43,15 @@
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/mathlimits.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
namespace converter {
bool GetBoolOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
+ const RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, bool default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
if (opt == nullptr) {
@@ -59,7 +61,7 @@ bool GetBoolOptionOrDefault(
}
int64 GetInt64OptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
+ const RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, int64 default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
if (opt == nullptr) {
@@ -69,7 +71,7 @@ int64 GetInt64OptionOrDefault(
}
double GetDoubleOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
+ const RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, double default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
if (opt == nullptr) {
@@ -79,7 +81,7 @@ double GetDoubleOptionOrDefault(
}
string GetStringOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
+ const RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name, const string& default_value) {
const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
if (opt == nullptr) {
@@ -136,7 +138,7 @@ const string GetFullTypeWithUrl(StringPiece simple_type) {
}
const google::protobuf::Option* FindOptionOrNull(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
+ const RepeatedPtrField<google::protobuf::Option>& options,
const string& option_name) {
for (int i = 0; i < options.size(); ++i) {
const google::protobuf::Option& opt = options.Get(i);
@@ -325,7 +327,7 @@ string ToSnakeCase(StringPiece input) {
}
std::set<string>* well_known_types_ = NULL;
-GOOGLE_PROTOBUF_DECLARE_ONCE(well_known_types_init_);
+PROTOBUF_NAMESPACE_ID::internal::once_flag well_known_types_init_;
const char* well_known_types_name_array_[] = {
"google.protobuf.Timestamp", "google.protobuf.Duration",
"google.protobuf.DoubleValue", "google.protobuf.FloatValue",
@@ -345,7 +347,8 @@ void InitWellKnownTypes() {
}
bool IsWellKnownType(const string& type_name) {
- InitWellKnownTypes();
+ PROTOBUF_NAMESPACE_ID::internal::call_once(well_known_types_init_,
+ InitWellKnownTypes);
return ContainsKey(*well_known_types_, type_name);
}
diff --git a/src/google/protobuf/util/internal/utility.h b/src/google/protobuf/util/internal/utility.h
index d8e06a97..6fe82959 100644
--- a/src/google/protobuf/util/internal/utility.h
+++ b/src/google/protobuf/util/internal/utility.h
@@ -44,6 +44,7 @@
#include <google/protobuf/stubs/status.h>
#include <google/protobuf/stubs/statusor.h>
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
@@ -56,8 +57,9 @@ class Type;
class Enum;
class EnumValue;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace util {
namespace converter {
@@ -68,46 +70,47 @@ static const int64 kTypeUrlSize = 19;
// Finds the tech option identified by option_name. Parses the boolean value and
// returns it.
// When the option with the given name is not found, default_value is returned.
-LIBPROTOBUF_EXPORT bool GetBoolOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
- const string& option_name, bool default_value);
+PROTOBUF_EXPORT bool GetBoolOptionOrDefault(
+ const RepeatedPtrField<google::protobuf::Option>& options,
+ const std::string& option_name, bool default_value);
// Returns int64 option value. If the option isn't found, returns the
// default_value.
-LIBPROTOBUF_EXPORT int64 GetInt64OptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
- const string& option_name, int64 default_value);
+PROTOBUF_EXPORT int64 GetInt64OptionOrDefault(
+ const RepeatedPtrField<google::protobuf::Option>& options,
+ const std::string& option_name, int64 default_value);
// Returns double option value. If the option isn't found, returns the
// default_value.
-LIBPROTOBUF_EXPORT double GetDoubleOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
- const string& option_name, double default_value);
+PROTOBUF_EXPORT double GetDoubleOptionOrDefault(
+ const RepeatedPtrField<google::protobuf::Option>& options,
+ const std::string& option_name, double default_value);
// Returns string option value. If the option isn't found, returns the
// default_value.
-LIBPROTOBUF_EXPORT string GetStringOptionOrDefault(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
- const string& option_name, const string& default_value);
+PROTOBUF_EXPORT std::string GetStringOptionOrDefault(
+ const RepeatedPtrField<google::protobuf::Option>& options,
+ const std::string& option_name, const std::string& default_value);
// Returns a boolean value contained in Any type.
// TODO(skarvaje): Make these utilities dealing with Any types more generic,
// add more error checking and move to a more public/sharable location so others
// can use.
-LIBPROTOBUF_EXPORT bool GetBoolFromAny(const google::protobuf::Any& any);
+PROTOBUF_EXPORT bool GetBoolFromAny(const google::protobuf::Any& any);
// Returns int64 value contained in Any type.
-LIBPROTOBUF_EXPORT int64 GetInt64FromAny(const google::protobuf::Any& any);
+PROTOBUF_EXPORT int64 GetInt64FromAny(const google::protobuf::Any& any);
// Returns double value contained in Any type.
-LIBPROTOBUF_EXPORT double GetDoubleFromAny(const google::protobuf::Any& any);
+PROTOBUF_EXPORT double GetDoubleFromAny(const google::protobuf::Any& any);
// Returns string value contained in Any type.
-LIBPROTOBUF_EXPORT string GetStringFromAny(const google::protobuf::Any& any);
+PROTOBUF_EXPORT std::string GetStringFromAny(const google::protobuf::Any& any);
// Returns the type string without the url prefix. e.g.: If the passed type is
// 'type.googleapis.com/tech.type.Bool', the returned value is 'tech.type.Bool'.
-LIBPROTOBUF_EXPORT const StringPiece GetTypeWithoutUrl(StringPiece type_url);
+PROTOBUF_EXPORT const StringPiece GetTypeWithoutUrl(
+ StringPiece type_url);
// Returns the simple_type with the base type url (kTypeServiceBaseUrl)
// prefixed.
@@ -115,13 +118,13 @@ LIBPROTOBUF_EXPORT const StringPiece GetTypeWithoutUrl(StringPiece type_url);
// E.g:
// GetFullTypeWithUrl("google.protobuf.Timestamp") returns the string
// "type.googleapis.com/google.protobuf.Timestamp".
-LIBPROTOBUF_EXPORT const string GetFullTypeWithUrl(StringPiece simple_type);
+PROTOBUF_EXPORT const std::string GetFullTypeWithUrl(StringPiece simple_type);
// Finds and returns option identified by name and option_name within the
// provided map. Returns nullptr if none found.
const google::protobuf::Option* FindOptionOrNull(
- const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
- const string& option_name);
+ const RepeatedPtrField<google::protobuf::Option>& options,
+ const std::string& option_name);
// Finds and returns the field identified by field_name in the passed tech Type
// object. Returns nullptr if none found.
@@ -155,51 +158,51 @@ const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
const google::protobuf::Enum* enum_type, StringPiece enum_name);
// Converts input to camel-case and returns it.
-LIBPROTOBUF_EXPORT string ToCamelCase(const StringPiece input);
+PROTOBUF_EXPORT std::string ToCamelCase(const StringPiece input);
// Converts enum name string to camel-case and returns it.
-string EnumValueNameToLowerCamelCase(const StringPiece input);
+std::string EnumValueNameToLowerCamelCase(const StringPiece input);
// Converts input to snake_case and returns it.
-LIBPROTOBUF_EXPORT string ToSnakeCase(StringPiece input);
+PROTOBUF_EXPORT std::string ToSnakeCase(StringPiece input);
// Returns true if type_name represents a well-known type.
-LIBPROTOBUF_EXPORT bool IsWellKnownType(const string& type_name);
+PROTOBUF_EXPORT bool IsWellKnownType(const std::string& type_name);
// Returns true if 'bool_string' represents a valid boolean value. Only "true",
// "false", "0" and "1" are allowed.
-LIBPROTOBUF_EXPORT bool IsValidBoolString(const string& bool_string);
+PROTOBUF_EXPORT bool IsValidBoolString(const std::string& bool_string);
// Returns true if "field" is a protobuf map field based on its type.
-LIBPROTOBUF_EXPORT bool IsMap(const google::protobuf::Field& field,
- const google::protobuf::Type& type);
+PROTOBUF_EXPORT bool IsMap(const google::protobuf::Field& field,
+ const google::protobuf::Type& type);
// Returns true if the given type has special MessageSet wire format.
bool IsMessageSetWireFormat(const google::protobuf::Type& type);
// Infinity/NaN-aware conversion to string.
-LIBPROTOBUF_EXPORT string DoubleAsString(double value);
-LIBPROTOBUF_EXPORT string FloatAsString(float value);
+PROTOBUF_EXPORT std::string DoubleAsString(double value);
+PROTOBUF_EXPORT std::string FloatAsString(float value);
// Convert from int32, int64, uint32, uint64, double or float to string.
template <typename T>
-string ValueAsString(T value) {
+std::string ValueAsString(T value) {
return SimpleItoa(value);
}
template <>
-inline string ValueAsString(float value) {
+inline std::string ValueAsString(float value) {
return FloatAsString(value);
}
template <>
-inline string ValueAsString(double value) {
+inline std::string ValueAsString(double value) {
return DoubleAsString(value);
}
// Converts a string to float. Unlike safe_strtof, conversion will fail if the
// value fits into double but not float (e.g., DBL_MAX).
-LIBPROTOBUF_EXPORT bool SafeStrToFloat(StringPiece str, float* value);
+PROTOBUF_EXPORT bool SafeStrToFloat(StringPiece str, float* value);
// Returns whether a StringPiece begins with the provided prefix.
bool StringStartsWith(StringPiece text, StringPiece prefix);
@@ -209,6 +212,8 @@ bool StringEndsWith(StringPiece text, StringPiece suffix);
} // namespace converter
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_UTILITY_H__
diff --git a/src/google/protobuf/compiler/js/well_known_types/any.js b/src/google/protobuf/util/json_format.proto
index d7ca6e3a..40b040e7 100644
--- a/src/google/protobuf/compiler/js/well_known_types/any.js
+++ b/src/google/protobuf/util/json_format.proto
@@ -28,53 +28,82 @@
// (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 code will be inserted into generated code for
- * google/protobuf/any.proto. */
+// 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.
-/**
- * Returns the type name contained in this instance, if any.
- * @return {string|undefined}
- */
-proto.google.protobuf.Any.prototype.getTypeName = function() {
- return this.getTypeUrl().split('/').pop();
-};
+syntax = "proto2";
+package google.protobuf;
-/**
- * Packs the given message instance into this Any.
- * @param {!Uint8Array} serialized The serialized data to pack.
- * @param {string} name The type name of this message object.
- * @param {string=} opt_typeUrlPrefix the type URL prefix.
- */
-proto.google.protobuf.Any.prototype.pack = function(serialized, name,
- opt_typeUrlPrefix) {
- if (!opt_typeUrlPrefix) {
- opt_typeUrlPrefix = 'type.googleapis.com/';
+message TestFlagsAndStrings {
+ required int32 A = 1;
+ repeated group RepeatedGroup = 2 {
+ required string f = 3;
}
+}
- if (opt_typeUrlPrefix.substr(-1) != '/') {
- this.setTypeUrl(opt_typeUrlPrefix + '/' + name);
- } else {
- this.setTypeUrl(opt_typeUrlPrefix + name);
- }
+message TestBase64ByteArrays {
+ required bytes a = 1;
+}
+
+message TestJavaScriptJSON {
+ optional int32 a = 1;
+ optional float final = 2;
+ optional string in = 3;
+ optional string Var = 4;
+}
+
+message TestJavaScriptOrderJSON1 {
+ optional int32 d = 1;
+ optional int32 c = 2;
+ optional bool x = 3;
+ optional int32 b = 4;
+ optional int32 a = 5;
+}
- this.setValue(serialized);
-};
+message TestJavaScriptOrderJSON2 {
+ optional int32 d = 1;
+ optional int32 c = 2;
+ optional bool x = 3;
+ optional int32 b = 4;
+ optional int32 a = 5;
+ repeated TestJavaScriptOrderJSON1 z = 6;
+}
+message TestLargeInt {
+ required int64 a = 1;
+ required uint64 b = 2;
+}
-/**
- * @template T
- * Unpacks this Any into the given message object.
- * @param {function(Uint8Array):T} deserialize Function that will deserialize
- * 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 null.
- */
-proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) {
- if (this.getTypeName() == name) {
- return deserialize(this.getValue_asU8());
- } else {
- return null;
+message TestNumbers {
+ enum MyType {
+ OK = 0;
+ WARNING = 1;
+ ERROR = 2;
}
-};
+ optional MyType a = 1;
+ optional int32 b = 2;
+ optional float c = 3;
+ optional bool d = 4;
+ optional double e = 5;
+ optional uint32 f = 6;
+}
+
+
+message TestCamelCase {
+ optional string normal_field = 1;
+ optional int32 CAPITAL_FIELD = 2;
+ optional int32 CamelCaseField = 3;
+}
+
+message TestBoolMap {
+ map<bool, int32> bool_map = 1;
+}
+
+message TestRecursion {
+ optional int32 value = 1;
+ optional TestRecursion child = 2;
+}
diff --git a/src/google/protobuf/util/json_format_proto3.proto b/src/google/protobuf/util/json_format_proto3.proto
index cbc3f81f..28e593df 100644
--- a/src/google/protobuf/util/json_format_proto3.proto
+++ b/src/google/protobuf/util/json_format_proto3.proto
@@ -182,8 +182,8 @@ message TestExtensions {
.protobuf_unittest.TestAllExtensions extensions = 1;
}
-message TestEnumValue{
+message TestEnumValue {
EnumType enum_value1 = 1;
EnumType enum_value2 = 2;
EnumType enum_value3 = 3;
-} \ No newline at end of file
+}
diff --git a/src/google/protobuf/util/json_util.cc b/src/google/protobuf/util/json_util.cc
index f81a7a30..19e20a47 100644
--- a/src/google/protobuf/util/json_util.cc
+++ b/src/google/protobuf/util/json_util.cc
@@ -33,6 +33,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/stubs/once.h>
#include <google/protobuf/util/internal/default_value_objectwriter.h>
#include <google/protobuf/util/internal/error_listener.h>
#include <google/protobuf/util/internal/json_objectwriter.h>
@@ -42,8 +43,12 @@
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/util/type_resolver_util.h>
#include <google/protobuf/stubs/bytestream.h>
+
+
#include <google/protobuf/stubs/status_macros.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -120,34 +125,50 @@ namespace {
class StatusErrorListener : public converter::ErrorListener {
public:
StatusErrorListener() {}
- virtual ~StatusErrorListener() {}
+ ~StatusErrorListener() override {}
util::Status GetStatus() { return status_; }
virtual void InvalidName(const converter::LocationTrackerInterface& loc,
- StringPiece unknown_name, StringPiece message) {
- status_ = util::Status(util::error::INVALID_ARGUMENT,
- loc.ToString() + ": " + string(message));
+ StringPiece unknown_name,
+ StringPiece message) {
+ string loc_string = GetLocString(loc);
+ if (!loc_string.empty()) {
+ loc_string.append(" ");
+ }
+ status_ =
+ util::Status(util::error::INVALID_ARGUMENT,
+ StrCat(loc_string, unknown_name, ": ", message));
}
virtual void InvalidValue(const converter::LocationTrackerInterface& loc,
- StringPiece type_name, StringPiece value) {
- status_ =
- util::Status(util::error::INVALID_ARGUMENT,
- loc.ToString() + ": invalid value " + string(value) +
- " for type " + string(type_name));
+ StringPiece type_name,
+ StringPiece value) {
+ status_ = util::Status(
+ util::error::INVALID_ARGUMENT,
+ StrCat(GetLocString(loc), ": invalid value ", string(value),
+ " for type ", string(type_name)));
}
virtual void MissingField(const converter::LocationTrackerInterface& loc,
StringPiece missing_name) {
- status_ = util::Status(
- util::error::INVALID_ARGUMENT,
- loc.ToString() + ": missing field " + string(missing_name));
+ status_ = util::Status(util::error::INVALID_ARGUMENT,
+ StrCat(GetLocString(loc), ": missing field ",
+ string(missing_name)));
}
private:
util::Status status_;
+ string GetLocString(const converter::LocationTrackerInterface& loc) {
+ string loc_string = loc.ToString();
+ StripWhitespace(&loc_string);
+ if (!loc_string.empty()) {
+ loc_string = StrCat("(", loc_string, ")");
+ }
+ return loc_string;
+ }
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StatusErrorListener);
};
} // namespace
@@ -163,6 +184,8 @@ util::Status JsonToBinaryStream(TypeResolver* resolver,
StatusErrorListener listener;
converter::ProtoStreamObjectWriter::Options proto_writer_options;
proto_writer_options.ignore_unknown_fields = options.ignore_unknown_fields;
+ proto_writer_options.ignore_unknown_enum_values =
+ options.ignore_unknown_fields;
converter::ProtoStreamObjectWriter proto_writer(resolver, type, &sink,
&listener,
proto_writer_options);
@@ -172,8 +195,8 @@ util::Status JsonToBinaryStream(TypeResolver* resolver,
int length;
while (json_input->Next(&buffer, &length)) {
if (length == 0) continue;
- RETURN_IF_ERROR(
- parser.Parse(StringPiece(static_cast<const char*>(buffer), length)));
+ RETURN_IF_ERROR(parser.Parse(
+ StringPiece(static_cast<const char*>(buffer), length)));
}
RETURN_IF_ERROR(parser.FinishParse());
@@ -182,7 +205,7 @@ util::Status JsonToBinaryStream(TypeResolver* resolver,
util::Status JsonToBinaryString(TypeResolver* resolver,
const string& type_url,
- const string& json_input,
+ StringPiece json_input,
string* binary_output,
const JsonParseOptions& options) {
io::ArrayInputStream input_stream(json_input.data(), json_input.size());
@@ -194,7 +217,7 @@ util::Status JsonToBinaryString(TypeResolver* resolver,
namespace {
const char* kTypeUrlPrefix = "type.googleapis.com";
TypeResolver* generated_type_resolver_ = NULL;
-GOOGLE_PROTOBUF_DECLARE_ONCE(generated_type_resolver_init_);
+PROTOBUF_NAMESPACE_ID::internal::once_flag generated_type_resolver_init_;
string GetTypeUrl(const Message& message) {
return string(kTypeUrlPrefix) + "/" + message.GetDescriptor()->full_name();
@@ -209,7 +232,8 @@ void InitGeneratedTypeResolver() {
}
TypeResolver* GetGeneratedTypeResolver() {
- ::google::protobuf::GoogleOnceInit(&generated_type_resolver_init_, &InitGeneratedTypeResolver);
+ PROTOBUF_NAMESPACE_ID::internal::call_once(generated_type_resolver_init_,
+ InitGeneratedTypeResolver);
return generated_type_resolver_;
}
} // namespace
@@ -230,7 +254,7 @@ util::Status MessageToJsonString(const Message& message, string* output,
return result;
}
-util::Status JsonStringToMessage(const string& input, Message* message,
+util::Status JsonStringToMessage(StringPiece input, Message* message,
const JsonParseOptions& options) {
const DescriptorPool* pool = message->GetDescriptor()->file()->pool();
TypeResolver* resolver =
diff --git a/src/google/protobuf/util/json_util.h b/src/google/protobuf/util/json_util.h
index b1c69813..f62e7f0f 100644
--- a/src/google/protobuf/util/json_util.h
+++ b/src/google/protobuf/util/json_util.h
@@ -37,6 +37,9 @@
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/bytestream.h>
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace io {
@@ -77,26 +80,25 @@ struct JsonPrintOptions {
// DEPRECATED. Use JsonPrintOptions instead.
typedef JsonPrintOptions JsonOptions;
-// Converts from protobuf message to JSON. This is a simple wrapper of
-// BinaryToJsonString(). It will use the DescriptorPool of the passed-in
-// message to resolve Any types.
-LIBPROTOBUF_EXPORT util::Status MessageToJsonString(const Message& message,
- string* output,
- const JsonOptions& options);
+// Converts from protobuf message to JSON and appends it to |output|. This is a
+// simple wrapper of BinaryToJsonString(). It will use the DescriptorPool of the
+// passed-in message to resolve Any types.
+PROTOBUF_EXPORT util::Status MessageToJsonString(const Message& message,
+ std::string* output,
+ const JsonOptions& options);
inline util::Status MessageToJsonString(const Message& message,
- string* output) {
+ std::string* output) {
return MessageToJsonString(message, output, JsonOptions());
}
// Converts from JSON to protobuf message. This is a simple wrapper of
// JsonStringToBinary(). It will use the DescriptorPool of the passed-in
// message to resolve Any types.
-LIBPROTOBUF_EXPORT util::Status JsonStringToMessage(const string& input,
- Message* message,
- const JsonParseOptions& options);
+PROTOBUF_EXPORT util::Status JsonStringToMessage(
+ StringPiece input, Message* message, const JsonParseOptions& options);
-inline util::Status JsonStringToMessage(const string& input,
+inline util::Status JsonStringToMessage(StringPiece input,
Message* message) {
return JsonStringToMessage(input, message, JsonParseOptions());
}
@@ -107,32 +109,27 @@ inline util::Status JsonStringToMessage(const string& input,
// 2. input is not valid protobuf wire format, or conflicts with the type
// information returned by TypeResolver.
// Note that unknown fields will be discarded silently.
-LIBPROTOBUF_EXPORT util::Status BinaryToJsonStream(
- TypeResolver* resolver,
- const string& type_url,
+PROTOBUF_EXPORT util::Status BinaryToJsonStream(
+ TypeResolver* resolver, const std::string& type_url,
io::ZeroCopyInputStream* binary_input,
- io::ZeroCopyOutputStream* json_output,
- const JsonPrintOptions& options);
+ io::ZeroCopyOutputStream* json_output, const JsonPrintOptions& options);
inline util::Status BinaryToJsonStream(
- TypeResolver* resolver, const string& type_url,
+ TypeResolver* resolver, const std::string& type_url,
io::ZeroCopyInputStream* binary_input,
io::ZeroCopyOutputStream* json_output) {
return BinaryToJsonStream(resolver, type_url, binary_input, json_output,
JsonPrintOptions());
}
-LIBPROTOBUF_EXPORT util::Status BinaryToJsonString(
- TypeResolver* resolver,
- const string& type_url,
- const string& binary_input,
- string* json_output,
- const JsonPrintOptions& options);
+PROTOBUF_EXPORT util::Status BinaryToJsonString(
+ TypeResolver* resolver, const std::string& type_url, const std::string& binary_input,
+ std::string* json_output, const JsonPrintOptions& options);
inline util::Status BinaryToJsonString(TypeResolver* resolver,
- const string& type_url,
- const string& binary_input,
- string* json_output) {
+ const std::string& type_url,
+ const std::string& binary_input,
+ std::string* json_output) {
return BinaryToJsonString(resolver, type_url, binary_input, json_output,
JsonPrintOptions());
}
@@ -142,47 +139,42 @@ inline util::Status BinaryToJsonString(TypeResolver* resolver,
// 1. TypeResolver fails to resolve a type.
// 2. input is not valid JSON format, or conflicts with the type
// information returned by TypeResolver.
-LIBPROTOBUF_EXPORT util::Status JsonToBinaryStream(
- TypeResolver* resolver,
- const string& type_url,
+PROTOBUF_EXPORT util::Status JsonToBinaryStream(
+ TypeResolver* resolver, const std::string& type_url,
io::ZeroCopyInputStream* json_input,
- io::ZeroCopyOutputStream* binary_output,
- const JsonParseOptions& options);
+ io::ZeroCopyOutputStream* binary_output, const JsonParseOptions& options);
inline util::Status JsonToBinaryStream(
TypeResolver* resolver,
- const string& type_url,
+ const std::string& type_url,
io::ZeroCopyInputStream* json_input,
io::ZeroCopyOutputStream* binary_output) {
return JsonToBinaryStream(resolver, type_url, json_input, binary_output,
JsonParseOptions());
}
-LIBPROTOBUF_EXPORT util::Status JsonToBinaryString(
- TypeResolver* resolver,
- const string& type_url,
- const string& json_input,
- string* binary_output,
+PROTOBUF_EXPORT util::Status JsonToBinaryString(
+ TypeResolver* resolver, const std::string& type_url,
+ StringPiece json_input, std::string* binary_output,
const JsonParseOptions& options);
-inline util::Status JsonToBinaryString(
- TypeResolver* resolver,
- const string& type_url,
- const string& json_input,
- string* binary_output) {
+inline util::Status JsonToBinaryString(TypeResolver* resolver,
+ const std::string& type_url,
+ StringPiece json_input,
+ std::string* binary_output) {
return JsonToBinaryString(resolver, type_url, json_input, binary_output,
JsonParseOptions());
}
namespace internal {
// Internal helper class. Put in the header so we can write unit-tests for it.
-class LIBPROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
+class PROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
public:
explicit ZeroCopyStreamByteSink(io::ZeroCopyOutputStream* stream)
: stream_(stream), buffer_(NULL), buffer_size_(0) {}
~ZeroCopyStreamByteSink();
- virtual void Append(const char* bytes, size_t len);
+ void Append(const char* bytes, size_t len) override;
private:
io::ZeroCopyOutputStream* stream_;
@@ -195,6 +187,8 @@ class LIBPROTOBUF_EXPORT ZeroCopyStreamByteSink : public strings::ByteSink {
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index ed9092df..125d4d4a 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -38,6 +38,7 @@
#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.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>
@@ -49,12 +50,13 @@ namespace util {
namespace {
using google::protobuf::testing::MapIn;
-using proto3::FOO;
using proto3::BAR;
-using proto3::TestMessage;
+using proto3::FOO;
+using proto3::TestEnumValue;
using proto3::TestMap;
+using proto3::TestMessage;
using proto3::TestOneof;
-using proto3::TestEnumValue;
+using proto3::TestAny;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
@@ -220,7 +222,7 @@ TEST_F(JsonUtilTest, TestAlwaysPrintEnumsAsInts) {
TEST_F(JsonUtilTest, TestPrintEnumsAsIntsWithDefaultValue) {
TestEnumValue orig;
- //orig.set_enum_value1(proto3::FOO)
+ // orig.set_enum_value1(proto3::FOO)
orig.set_enum_value2(proto3::FOO);
orig.set_enum_value3(proto3::BAR);
@@ -238,7 +240,6 @@ TEST_F(JsonUtilTest, TestPrintEnumsAsIntsWithDefaultValue) {
EXPECT_EQ(proto3::FOO, parsed.enum_value1());
EXPECT_EQ(proto3::FOO, parsed.enum_value2());
EXPECT_EQ(proto3::BAR, parsed.enum_value3());
-
}
TEST_F(JsonUtilTest, ParseMessage) {
@@ -284,7 +285,7 @@ TEST_F(JsonUtilTest, ParsePrimitiveMapIn) {
JsonPrintOptions print_options;
print_options.always_print_primitive_fields = true;
JsonParseOptions parse_options;
- EXPECT_EQ("{\"other\":\"\",\"things\":[],\"mapInput\":{}}",
+ EXPECT_EQ("{\"other\":\"\",\"things\":[],\"mapInput\":{},\"mapAny\":{}}",
ToJson(message, print_options));
MapIn other;
ASSERT_TRUE(FromJson(ToJson(message, print_options), &other, parse_options));
@@ -357,30 +358,66 @@ TEST_F(JsonUtilTest, TestDynamicMessage) {
EXPECT_EQ(ToJson(generated, options), ToJson(*message, options));
}
-TEST_F(JsonUtilTest, TestParsingUnknownEnumsAs0) {
+TEST_F(JsonUtilTest, TestParsingUnknownAnyFields) {
+ string input =
+ "{\n"
+ " \"value\": {\n"
+ " \"@type\": \"type.googleapis.com/proto3.TestMessage\",\n"
+ " \"unknown_field\": \"UNKOWN_VALUE\",\n"
+ " \"string_value\": \"expected_value\"\n"
+ " }\n"
+ "}";
+
+ TestAny m;
+ JsonParseOptions options;
+ EXPECT_FALSE(FromJson(input, &m, options));
+
+ options.ignore_unknown_fields = true;
+ EXPECT_TRUE(FromJson(input, &m, options));
+
+ TestMessage t;
+ EXPECT_TRUE(m.value().UnpackTo(&t));
+ EXPECT_EQ("expected_value", t.string_value());
+}
+
+TEST_F(JsonUtilTest, TestParsingUnknownEnumsProto2) {
+ string input =
+ "{\n"
+ " \"a\": \"UNKNOWN_VALUE\"\n"
+ "}";
+ TestNumbers m;
+ JsonParseOptions options;
+ EXPECT_FALSE(FromJson(input, &m, options));
+
+ options.ignore_unknown_fields = true;
+ EXPECT_TRUE(FromJson(input, &m, options));
+ EXPECT_FALSE(m.has_a());
+}
+
+TEST_F(JsonUtilTest, TestParsingUnknownEnumsProto3) {
TestMessage m;
{
JsonParseOptions options;
ASSERT_FALSE(options.ignore_unknown_fields);
string input =
- "{\n"
- " \"enum_value\":\"UNKNOWN_VALUE\"\n"
- "}";
+ "{\n"
+ " \"enum_value\":\"UNKNOWN_VALUE\"\n"
+ "}";
m.set_enum_value(proto3::BAR);
EXPECT_FALSE(FromJson(input, &m, options));
- ASSERT_EQ(proto3::BAR, m.enum_value()); // Keep previous value
+ ASSERT_EQ(proto3::BAR, m.enum_value()); // Keep previous value
options.ignore_unknown_fields = true;
EXPECT_TRUE(FromJson(input, &m, options));
- EXPECT_EQ(0, m.enum_value()); // Unknown enum value must be decoded as 0
+ EXPECT_EQ(0, m.enum_value()); // Unknown enum value must be decoded as 0
}
// Integer values are read as usual
{
JsonParseOptions options;
string input =
- "{\n"
- " \"enum_value\":12345\n"
- "}";
+ "{\n"
+ " \"enum_value\":12345\n"
+ "}";
m.set_enum_value(proto3::BAR);
EXPECT_TRUE(FromJson(input, &m, options));
ASSERT_EQ(12345, m.enum_value());
@@ -390,25 +427,27 @@ TEST_F(JsonUtilTest, TestParsingUnknownEnumsAs0) {
EXPECT_EQ(12345, m.enum_value());
}
- // Trying to pass an object as an enum field value is always treated as an error
+ // Trying to pass an object as an enum field value is always treated as an
+ // error
{
JsonParseOptions options;
string input =
- "{\n"
- " \"enum_value\":{}\n"
- "}";
+ "{\n"
+ " \"enum_value\":{}\n"
+ "}";
options.ignore_unknown_fields = true;
EXPECT_FALSE(FromJson(input, &m, options));
options.ignore_unknown_fields = false;
EXPECT_FALSE(FromJson(input, &m, options));
}
- // Trying to pass an array as an enum field value is always treated as an error
+ // Trying to pass an array as an enum field value is always treated as an
+ // error
{
JsonParseOptions options;
string input =
- "{\n"
- " \"enum_value\":[]\n"
- "}";
+ "{\n"
+ " \"enum_value\":[]\n"
+ "}";
EXPECT_FALSE(FromJson(input, &m, options));
options.ignore_unknown_fields = true;
EXPECT_FALSE(FromJson(input, &m, options));
@@ -559,6 +598,13 @@ TEST_F(JsonUtilTest, TestWrongJsonInput) {
util::error::INVALID_ARGUMENT);
}
+TEST_F(JsonUtilTest, HtmlEscape) {
+ TestMessage m;
+ m.set_string_value("</script>");
+ JsonPrintOptions options;
+ EXPECT_EQ("{\"stringValue\":\"\\u003c/script\\u003e\"}", ToJson(m, options));
+}
+
} // namespace
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index 9842f64c..8a09400b 100644
--- a/src/google/protobuf/util/message_differencer.cc
+++ b/src/google/protobuf/util/message_differencer.cc
@@ -31,10 +31,6 @@
// Author: jschorr@google.com (Joseph Schorr)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// This file defines static methods and classes for comparing Protocol
-// Messages (see //google/protobuf/util/message_differencer.h for more
-// information).
#include <google/protobuf/util/message_differencer.h>
@@ -56,6 +52,7 @@
#include <google/protobuf/util/field_comparator.h>
#include <google/protobuf/stubs/strutil.h>
+
namespace google {
namespace protobuf {
@@ -87,10 +84,8 @@ class MessageDifferencer::MultipleFieldsMapKeyComparator
key_field_path.push_back(key);
key_field_paths_.push_back(key_field_path);
}
- virtual bool IsMatch(
- const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& parent_fields) const {
+ bool IsMatch(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const override {
for (int i = 0; i < key_field_paths_.size(); ++i) {
if (!IsMatchInternal(message1, message2, parent_fields,
key_field_paths_[i], 0)) {
@@ -99,6 +94,7 @@ class MessageDifferencer::MultipleFieldsMapKeyComparator
}
return true;
}
+
private:
bool IsMatchInternal(
const Message& message1,
@@ -218,6 +214,7 @@ MessageDifferencer::MessageDifferencer()
map_entry_key_comparator_(this),
report_matches_(false),
report_moves_(true),
+ report_ignores_(true),
output_string_(NULL) {}
MessageDifferencer::~MessageDifferencer() {
@@ -533,9 +530,9 @@ bool MessageDifferencer::Compare(
bool unknown_compare_result = true;
// Ignore unknown fields in EQUIVALENT mode
if (message_field_comparison_ != EQUIVALENT) {
- const google::protobuf::UnknownFieldSet* unknown_field_set1 =
+ const UnknownFieldSet* unknown_field_set1 =
&reflection1->GetUnknownFields(message1);
- const google::protobuf::UnknownFieldSet* unknown_field_set2 =
+ const UnknownFieldSet* unknown_field_set2 =
&reflection2->GetUnknownFields(message2);
if (!CompareUnknownFields(message1, message2,
*unknown_field_set1, *unknown_field_set2,
@@ -660,7 +657,9 @@ bool MessageDifferencer::CompareWithFieldsInternal(
specific_field.field = field1;
parent_fields->push_back(specific_field);
- reporter_->ReportIgnored(message1, message2, *parent_fields);
+ if (report_ignores_) {
+ reporter_->ReportIgnored(message1, message2, *parent_fields);
+ }
parent_fields->pop_back();
}
++field_index1;
@@ -699,7 +698,9 @@ bool MessageDifferencer::CompareWithFieldsInternal(
specific_field.field = field2;
parent_fields->push_back(specific_field);
- reporter_->ReportIgnored(message1, message2, *parent_fields);
+ if (report_ignores_) {
+ reporter_->ReportIgnored(message1, message2, *parent_fields);
+ }
parent_fields->pop_back();
}
++field_index2;
@@ -739,7 +740,9 @@ bool MessageDifferencer::CompareWithFieldsInternal(
specific_field.field = field1;
parent_fields->push_back(specific_field);
- reporter_->ReportIgnored(message1, message2, *parent_fields);
+ if (report_ignores_) {
+ reporter_->ReportIgnored(message1, message2, *parent_fields);
+ }
parent_fields->pop_back();
}
@@ -1078,7 +1081,7 @@ bool MessageDifferencer::UnpackAny(const Message& any,
return false;
}
- const google::protobuf::Descriptor* desc =
+ const Descriptor* desc =
any.GetDescriptor()->file()->pool()->FindMessageTypeByName(
full_type_name);
if (desc == NULL) {
@@ -1100,8 +1103,8 @@ bool MessageDifferencer::UnpackAny(const Message& any,
bool MessageDifferencer::CompareUnknownFields(
const Message& message1, const Message& message2,
- const google::protobuf::UnknownFieldSet& unknown_field_set1,
- const google::protobuf::UnknownFieldSet& unknown_field_set2,
+ const UnknownFieldSet& unknown_field_set1,
+ const UnknownFieldSet& unknown_field_set2,
std::vector<SpecificField>* parent_field) {
// Ignore unknown fields in EQUIVALENT mode.
if (message_field_comparison_ == EQUIVALENT) return true;
@@ -1434,6 +1437,13 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
match_list1->assign(count1, -1);
match_list2->assign(count2, -1);
+ // Ensure that we don't report differences during the matching process. Since
+ // field comparators could potentially use this message differencer object to
+ // perform further comparisons, turn off reporting here and re-enable it
+ // before returning.
+ Reporter* reporter = reporter_;
+ reporter_ = NULL;
+
bool success = true;
// Find potential match if this is a special repeated field.
if (key_comparator != NULL || IsTreatedAsSet(repeated_field)) {
@@ -1451,9 +1461,9 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
match_list2);
// If diff info is not needed, we should end the matching process as
// soon as possible if not all items can be matched.
- bool early_return = (reporter_ == NULL);
+ bool early_return = (reporter == NULL);
int match_count = matcher.FindMaximumMatch(early_return);
- if (match_count != count1 && reporter_ == NULL) return false;
+ if (match_count != count1 && reporter == NULL) return false;
success = success && (match_count == count1);
} else {
int start_offset = 0;
@@ -1488,7 +1498,7 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
break;
}
}
- if (!match && reporter_ == NULL) return false;
+ if (!match && reporter == NULL) return false;
success = success && match;
}
}
@@ -1500,6 +1510,8 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
}
}
+ reporter_ = reporter;
+
return success;
}
@@ -1567,13 +1579,16 @@ void MessageDifferencer::StreamReporter::PrintPath(
continue;
}
} else {
- printer_->PrintRaw(SimpleItoa(specific_field.unknown_field_number));
+ printer_->PrintRaw(
+ SimpleItoa(specific_field.unknown_field_number));
}
if (left_side && specific_field.index >= 0) {
- printer_->Print("[$name$]", "name", SimpleItoa(specific_field.index));
+ printer_->Print("[$name$]", "name",
+ SimpleItoa(specific_field.index));
}
if (!left_side && specific_field.new_index >= 0) {
- printer_->Print("[$name$]", "name", SimpleItoa(specific_field.new_index));
+ printer_->Print("[$name$]", "name",
+ SimpleItoa(specific_field.new_index));
}
}
}
@@ -1631,12 +1646,12 @@ StreamReporter::PrintUnknownFieldValue(const UnknownField* unknown_field) {
output = SimpleItoa(unknown_field->varint());
break;
case UnknownField::TYPE_FIXED32:
- output = StrCat("0x", strings::Hex(unknown_field->fixed32(),
- strings::ZERO_PAD_8));
+ output = StrCat(
+ "0x", strings::Hex(unknown_field->fixed32(), strings::ZERO_PAD_8));
break;
case UnknownField::TYPE_FIXED64:
- output = StrCat("0x", strings::Hex(unknown_field->fixed64(),
- strings::ZERO_PAD_16));
+ output = StrCat(
+ "0x", strings::Hex(unknown_field->fixed64(), strings::ZERO_PAD_16));
break;
case UnknownField::TYPE_LENGTH_DELIMITED:
output = StringPrintf("\"%s\"",
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index bbcf8498..9419267e 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -51,6 +51,8 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/util/field_comparator.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
@@ -60,7 +62,7 @@ class FieldDescriptor;
namespace io {
class ZeroCopyOutputStream;
class Printer;
-}
+} // namespace io
namespace util {
@@ -106,7 +108,7 @@ class FieldContext; // declared below MessageDifferencer
// guard it with a lock to use the same MessageDifferencer instance from
// multiple threads. Note that it's fine to call static comparison methods
// (like MessageDifferencer::Equals) concurrently.
-class LIBPROTOBUF_EXPORT MessageDifferencer {
+class PROTOBUF_EXPORT MessageDifferencer {
public:
// Determines whether the supplied messages are equal. Equality is defined as
// all fields within the two messages being set to the same value. Primitive
@@ -212,7 +214,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// FieldDescriptors. The first will be the field of the embedded message
// itself and the second will be the actual field in the embedded message
// that was added/deleted/modified.
- class LIBPROTOBUF_EXPORT Reporter {
+ class PROTOBUF_EXPORT Reporter {
public:
Reporter();
virtual ~Reporter();
@@ -290,7 +292,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// MapKeyComparator is used to determine if two elements have the same key
// when comparing elements of a repeated field as a map.
- class LIBPROTOBUF_EXPORT MapKeyComparator {
+ class PROTOBUF_EXPORT MapKeyComparator {
public:
MapKeyComparator();
virtual ~MapKeyComparator();
@@ -313,7 +315,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// field IsIgnored is called on each added IgnoreCriteria until one returns
// true or all return false.
// IsIgnored is called for fields where at least one side has a value.
- class LIBPROTOBUF_EXPORT IgnoreCriteria {
+ class PROTOBUF_EXPORT IgnoreCriteria {
public:
IgnoreCriteria();
virtual ~IgnoreCriteria();
@@ -533,6 +535,12 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
report_moves_ = report_moves;
}
+ // Tells the differencer whether or not to report ignored values. This method
+ // must be called before Compare. The default for a new differencer is true.
+ void set_report_ignores(bool report_ignores) {
+ report_ignores_ = report_ignores;
+ }
+
// 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.
@@ -573,7 +581,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// Automatically creates a reporter that will output the differences
// found (if any) to the specified output string pointer. Note that this
// method must be called before Compare.
- void ReportDifferencesToString(string* output);
+ void ReportDifferencesToString(std::string* output);
// Tells the MessageDifferencer to report differences via the specified
// reporter. Note that this method must be called before Compare for
@@ -593,11 +601,11 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// complete until after you destroy the reporter. For example, if you use a
// StreamReporter to write to a StringOutputStream, the target string may
// contain uninitialized data until the reporter is destroyed.
- class LIBPROTOBUF_EXPORT StreamReporter : public Reporter {
+ class PROTOBUF_EXPORT StreamReporter : public Reporter {
public:
explicit StreamReporter(io::ZeroCopyOutputStream* output);
explicit StreamReporter(io::Printer* printer); // delimiter '$'
- virtual ~StreamReporter();
+ ~StreamReporter() override;
// When set to true, the stream reporter will also output aggregates nodes
// (i.e. messages and groups) whose subfields have been modified. When
@@ -607,32 +615,28 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
}
// The following are implementations of the methods described above.
- virtual void ReportAdded(const Message& message1, const Message& message2,
- const std::vector<SpecificField>& field_path);
- virtual void ReportDeleted(const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path);
+ void ReportAdded(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportModified(const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path);
+ void ReportDeleted(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportMoved(const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path);
+ void ReportModified(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportMatched(const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path);
+ void ReportMoved(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportIgnored(const Message& message1,
- const Message& message2,
- const std::vector<SpecificField>& field_path);
+ void ReportMatched(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
- virtual void ReportUnknownFieldIgnored(
+ void ReportIgnored(const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& field_path) override;
+
+ void ReportUnknownFieldIgnored(
const Message& message1, const Message& message2,
- const std::vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path) override;
protected:
// Prints the specified path of fields to the buffer. message is used to
@@ -657,7 +661,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual void PrintUnknownFieldValue(const UnknownField* unknown_field);
// Just print a string
- void Print(const string& str);
+ void Print(const std::string& str);
private:
io::Printer* printer_;
@@ -677,11 +681,12 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
class MultipleFieldsMapKeyComparator;
// A MapKeyComparator for use with map_entries.
- class LIBPROTOBUF_EXPORT MapEntryKeyComparator : public MapKeyComparator {
+ class PROTOBUF_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;
+ bool IsMatch(
+ const Message& message1, const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const override;
private:
MessageDifferencer* message_differencer_;
@@ -711,8 +716,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// Compares all the unknown fields in two messages.
bool CompareUnknownFields(const Message& message1, const Message& message2,
- const google::protobuf::UnknownFieldSet&,
- const google::protobuf::UnknownFieldSet&,
+ const UnknownFieldSet&, const UnknownFieldSet&,
std::vector<SpecificField>* parent_fields);
// Compares the specified messages for the requested field lists. The field
@@ -859,8 +863,9 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
bool report_matches_;
bool report_moves_;
+ bool report_ignores_;
- string* output_string_;
+ std::string* output_string_;
std::unique_ptr<DynamicMessageFactory> dynamic_message_factory_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageDifferencer);
@@ -868,7 +873,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// This class provides extra information to the FieldComparator::Compare
// function.
-class LIBPROTOBUF_EXPORT FieldContext {
+class PROTOBUF_EXPORT FieldContext {
public:
explicit FieldContext(
std::vector<MessageDifferencer::SpecificField>* parent_fields)
@@ -882,8 +887,10 @@ class LIBPROTOBUF_EXPORT FieldContext {
std::vector<MessageDifferencer::SpecificField>* parent_fields_;
};
-}
-}
-
+} // namespace util
+} // namespace protobuf
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_MESSAGE_DIFFERENCER_H__
diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc
index a263d983..848290b1 100755..100644
--- a/src/google/protobuf/util/message_differencer_unittest.cc
+++ b/src/google/protobuf/util/message_differencer_unittest.cc
@@ -35,6 +35,7 @@
// TODO(ksroka): Move some of these tests to field_comparator_test.cc.
#include <algorithm>
+#include <random>
#include <string>
#include <vector>
@@ -906,8 +907,9 @@ TEST(MessageDifferencerTest, SpecifiedFieldsEqualityAllShuffledTest) {
msg1.GetReflection()->ListFields(msg1, &fields1);
msg2.GetReflection()->ListFields(msg2, &fields2);
- std::random_shuffle(fields1.begin(), fields1.end());
- std::random_shuffle(fields2.begin(), fields2.end());
+ std::default_random_engine rng;
+ std::shuffle(fields1.begin(), fields1.end(), rng);
+ std::shuffle(fields2.begin(), fields2.end(), rng);
util::MessageDifferencer differencer;
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields1, fields2));
@@ -1936,6 +1938,45 @@ TEST(MessageDifferencerTest, IgnoreField_TrumpsCompareWithFields) {
EXPECT_TRUE(differencer.CompareWithFields(msg1, msg2, fields, fields));
}
+TEST(MessageDifferencerTest, IgnoreField_SetReportIgnoresFalse) {
+ protobuf_unittest::TestField msg1;
+ protobuf_unittest::TestField msg2;
+
+ msg1.set_a(1);
+ msg1.set_b(2);
+ msg1.set_c(3);
+ msg1.add_rc(1);
+ msg1.add_rc(2);
+
+ msg2.set_a(1);
+ msg2.set_b(1);
+
+ const FieldDescriptor* a = GetFieldDescriptor(msg1, "a");
+ const FieldDescriptor* b = GetFieldDescriptor(msg1, "b");
+ const FieldDescriptor* c = GetFieldDescriptor(msg1, "c");
+ const FieldDescriptor* rc = GetFieldDescriptor(msg1, "rc");
+
+ std::vector<const FieldDescriptor*> fields;
+ fields.push_back(a);
+ fields.push_back(b);
+ fields.push_back(c);
+ fields.push_back(rc);
+
+ string diff_report;
+ util::MessageDifferencer differencer;
+ differencer.set_report_ignores(false);
+ differencer.set_report_matches(true);
+ differencer.ReportDifferencesToString(&diff_report);
+ differencer.IgnoreField(c);
+ differencer.IgnoreField(rc);
+ differencer.set_scope(util::MessageDifferencer::FULL);
+ EXPECT_FALSE(differencer.CompareWithFields(msg1, msg2, fields, fields));
+
+ EXPECT_EQ(diff_report,
+ "matched: a : 1\n"
+ "modified: b: 2 -> 1\n");
+}
+
// Test class to save a copy of the last field_context.parent_fields() vector
// passed to the comparison function.
@@ -1943,12 +1984,11 @@ class ParentSavingFieldComparator : public util::FieldComparator {
public:
ParentSavingFieldComparator() {}
- virtual ComparisonResult Compare(
- const google::protobuf::Message& message_1,
- const google::protobuf::Message& message_2,
- const google::protobuf::FieldDescriptor* field,
- int index_1, int index_2,
- const google::protobuf::util::FieldContext* field_context) {
+ virtual ComparisonResult Compare(const Message& message_1,
+ const Message& message_2,
+ const FieldDescriptor* field, int index_1,
+ int index_2,
+ const util::FieldContext* field_context) {
if (field_context)
parent_fields_ = *(field_context->parent_fields());
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
@@ -1958,12 +1998,12 @@ class ParentSavingFieldComparator : public util::FieldComparator {
}
}
- std::vector<google::protobuf::util::MessageDifferencer::SpecificField> parent_fields() {
+ std::vector<util::MessageDifferencer::SpecificField> parent_fields() {
return parent_fields_;
}
private:
- std::vector<google::protobuf::util::MessageDifferencer::SpecificField> parent_fields_;
+ std::vector<util::MessageDifferencer::SpecificField> parent_fields_;
};
// Tests if MessageDifferencer sends the parent fields in the FieldContext
@@ -2894,7 +2934,7 @@ TEST_F(ComparisonTest, MapIgnoreKeyTest) {
}
TEST_F(ComparisonTest, MapRoundTripSyncTest) {
- google::protobuf::TextFormat::Parser parser;
+ TextFormat::Parser parser;
unittest::TestMap map_reflection1;
// By setting via reflection, data exists in repeated field.
@@ -2910,7 +2950,7 @@ TEST_F(ComparisonTest, MapRoundTripSyncTest) {
}
TEST_F(ComparisonTest, MapEntryPartialTest) {
- google::protobuf::TextFormat::Parser parser;
+ TextFormat::Parser parser;
unittest::TestMap map1;
unittest::TestMap map2;
@@ -2932,7 +2972,7 @@ TEST_F(ComparisonTest, MapEntryPartialTest) {
}
TEST_F(ComparisonTest, MapEntryPartialEmptyKeyTest) {
- google::protobuf::TextFormat::Parser parser;
+ TextFormat::Parser parser;
unittest::TestMap map1;
unittest::TestMap map2;
ASSERT_TRUE(parser.ParseFromString("map_int32_foreign_message {}", &map1));
@@ -2961,7 +3001,7 @@ class LengthMapKeyComparator
};
TEST_F(ComparisonTest, MapEntryCustomMapKeyComparator) {
- google::protobuf::TextFormat::Parser parser;
+ TextFormat::Parser parser;
protobuf_unittest::TestMap msg1;
protobuf_unittest::TestMap msg2;
diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc
index d4912837..a7cba004 100644
--- a/src/google/protobuf/util/time_util.cc
+++ b/src/google/protobuf/util/time_util.cc
@@ -38,6 +38,8 @@
#include <google/protobuf/timestamp.pb.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
@@ -368,12 +370,13 @@ timeval TimeUtil::DurationToTimeval(const Duration& value) {
} // namespace util
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
namespace {
-using google::protobuf::util::kNanosPerSecond;
-using google::protobuf::util::CreateNormalized;
+using ::PROTOBUF_NAMESPACE_ID::util::CreateNormalized;
+using ::PROTOBUF_NAMESPACE_ID::util::kNanosPerSecond;
// Convert a Duration to uint128.
void ToUint128(const Duration& value, uint128* result, bool* negative) {
@@ -389,7 +392,8 @@ void ToUint128(const Duration& value, uint128* result, bool* negative) {
}
void ToDuration(const uint128& value, bool negative, Duration* duration) {
- int64 seconds = static_cast<int64>(Uint128Low64(value / kNanosPerSecond));
+ int64 seconds =
+ static_cast<int64>(Uint128Low64(value / kNanosPerSecond));
int32 nanos = static_cast<int32>(Uint128Low64(value % kNanosPerSecond));
if (negative) {
seconds = -seconds;
@@ -501,5 +505,4 @@ Duration operator-(const Timestamp& t1, const Timestamp& t2) {
t1.nanos() - t2.nanos());
}
} // namespace protobuf
-
} // namespace google
diff --git a/src/google/protobuf/util/time_util.h b/src/google/protobuf/util/time_util.h
index b8846935..bbda5380 100644
--- a/src/google/protobuf/util/time_util.h
+++ b/src/google/protobuf/util/time_util.h
@@ -45,12 +45,14 @@
#include <google/protobuf/duration.pb.h>
#include <google/protobuf/timestamp.pb.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace util {
// Utility functions for Timestamp and Duration.
-class LIBPROTOBUF_EXPORT TimeUtil {
+class PROTOBUF_EXPORT TimeUtil {
typedef google::protobuf::Timestamp Timestamp;
typedef google::protobuf::Duration Duration;
@@ -79,8 +81,8 @@ class LIBPROTOBUF_EXPORT TimeUtil {
//
// Example of accepted format:
// "1972-01-01T10:00:20.021-05:00"
- static string ToString(const Timestamp& timestamp);
- static bool FromString(const string& value, Timestamp* timestamp);
+ static std::string ToString(const Timestamp& timestamp);
+ static bool FromString(const std::string& value, Timestamp* timestamp);
// Converts Duration to/from string format. The string format will contains
// 3, 6, or 9 fractional digits depending on the precision required to
@@ -88,8 +90,8 @@ class LIBPROTOBUF_EXPORT TimeUtil {
// "1s", "1.010s", "1.000000100s", "-3.100s"
// The range that can be represented by Duration is from -315,576,000,000
// to +315,576,000,000 inclusive (in seconds).
- static string ToString(const Duration& duration);
- static bool FromString(const string& value, Duration* timestamp);
+ static std::string ToString(const Duration& duration);
+ static bool FromString(const std::string& value, Duration* timestamp);
#ifdef GetCurrentTime
#undef GetCurrentTime // Visual Studio has macro GetCurrentTime
@@ -156,18 +158,21 @@ class LIBPROTOBUF_EXPORT TimeUtil {
} // namespace util
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
// Overloaded operators for Duration.
//
// Assignment operators.
-LIBPROTOBUF_EXPORT Duration& operator+=(Duration& d1, const Duration& d2); // NOLINT
-LIBPROTOBUF_EXPORT Duration& operator-=(Duration& d1, const Duration& d2); // NOLINT
-LIBPROTOBUF_EXPORT Duration& operator*=(Duration& d, int64 r); // NOLINT
-LIBPROTOBUF_EXPORT Duration& operator*=(Duration& d, double r); // NOLINT
-LIBPROTOBUF_EXPORT Duration& operator/=(Duration& d, int64 r); // NOLINT
-LIBPROTOBUF_EXPORT Duration& operator/=(Duration& d, double r); // NOLINT
+PROTOBUF_EXPORT Duration& operator+=(Duration& d1,
+ const Duration& d2); // NOLINT
+PROTOBUF_EXPORT Duration& operator-=(Duration& d1,
+ const Duration& d2); // NOLINT
+PROTOBUF_EXPORT Duration& operator*=(Duration& d, int64 r); // NOLINT
+PROTOBUF_EXPORT Duration& operator*=(Duration& d, double r); // NOLINT
+PROTOBUF_EXPORT Duration& operator/=(Duration& d, int64 r); // NOLINT
+PROTOBUF_EXPORT Duration& operator/=(Duration& d, double r); // NOLINT
// Overload for other integer types.
template <typename T>
Duration& operator*=(Duration& d, T r) { // NOLINT
@@ -179,7 +184,8 @@ Duration& operator/=(Duration& d, T r) { // NOLINT
int64 x = r;
return d /= x;
}
-LIBPROTOBUF_EXPORT Duration& operator%=(Duration& d1, const Duration& d2); // NOLINT
+PROTOBUF_EXPORT Duration& operator%=(Duration& d1,
+ const Duration& d2); // NOLINT
// Relational operators.
inline bool operator<(const Duration& d1, const Duration& d2) {
if (d1.seconds() == d2.seconds()) {
@@ -230,7 +236,7 @@ template<typename T>
inline Duration operator/(Duration d, T r) {
return d /= r;
}
-LIBPROTOBUF_EXPORT int64 operator/(const Duration& d1, const Duration& d2);
+PROTOBUF_EXPORT int64 operator/(const Duration& d1, const Duration& d2);
inline Duration operator%(const Duration& d1, const Duration& d2) {
Duration result = d1;
@@ -238,15 +244,17 @@ inline Duration operator%(const Duration& d1, const Duration& d2) {
}
inline std::ostream& operator<<(std::ostream& out, const Duration& d) {
- out << google::protobuf::util::TimeUtil::ToString(d);
+ out << ::PROTOBUF_NAMESPACE_ID::util::TimeUtil::ToString(d);
return out;
}
// Overloaded operators for Timestamp
//
// Assignement operators.
-LIBPROTOBUF_EXPORT Timestamp& operator+=(Timestamp& t, const Duration& d); // NOLINT
-LIBPROTOBUF_EXPORT Timestamp& operator-=(Timestamp& t, const Duration& d); // NOLINT
+PROTOBUF_EXPORT Timestamp& operator+=(Timestamp& t,
+ const Duration& d); // NOLINT
+PROTOBUF_EXPORT Timestamp& operator-=(Timestamp& t,
+ const Duration& d); // NOLINT
// Relational operators.
inline bool operator<(const Timestamp& t1, const Timestamp& t2) {
if (t1.seconds() == t2.seconds()) {
@@ -282,15 +290,16 @@ inline Timestamp operator-(const Timestamp& t, const Duration& d) {
Timestamp result = t;
return result -= d;
}
-LIBPROTOBUF_EXPORT Duration operator-(const Timestamp& t1, const Timestamp& t2);
+PROTOBUF_EXPORT Duration operator-(const Timestamp& t1, const Timestamp& t2);
inline std::ostream& operator<<(std::ostream& out, const Timestamp& t) {
- out << google::protobuf::util::TimeUtil::ToString(t);
+ out << ::PROTOBUF_NAMESPACE_ID::util::TimeUtil::ToString(t);
return out;
}
} // namespace protobuf
+} // namespace google
+#include <google/protobuf/port_undef.inc>
-} // namespace google
#endif // GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
diff --git a/src/google/protobuf/util/type_resolver.h b/src/google/protobuf/util/type_resolver.h
index 959f3c79..bc5f0960 100644
--- a/src/google/protobuf/util/type_resolver.h
+++ b/src/google/protobuf/util/type_resolver.h
@@ -38,14 +38,16 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/status.h>
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class Type;
class Enum;
} // namespace protobuf
+} // namespace google
-
+namespace google {
namespace protobuf {
class DescriptorPool;
namespace util {
@@ -53,17 +55,17 @@ namespace util {
// Abstract interface for a type resovler.
//
// Implementations of this interface must be thread-safe.
-class LIBPROTOBUF_EXPORT TypeResolver {
+class PROTOBUF_EXPORT TypeResolver {
public:
TypeResolver() {}
virtual ~TypeResolver() {}
// Resolves a type url for a message type.
virtual util::Status ResolveMessageType(
- const string& type_url, google::protobuf::Type* message_type) = 0;
+ const std::string& type_url, google::protobuf::Type* message_type) = 0;
// Resolves a type url for an enum type.
- virtual util::Status ResolveEnumType(const string& type_url,
+ virtual util::Status ResolveEnumType(const std::string& type_url,
google::protobuf::Enum* enum_type) = 0;
private:
@@ -72,6 +74,8 @@ class LIBPROTOBUF_EXPORT TypeResolver {
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_H__
diff --git a/src/google/protobuf/util/type_resolver_util.cc b/src/google/protobuf/util/type_resolver_util.cc
index a69ed58c..3a3eba4b 100644
--- a/src/google/protobuf/util/type_resolver_util.cc
+++ b/src/google/protobuf/util/type_resolver_util.cc
@@ -37,6 +37,7 @@
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/strutil.h>
+
#include <google/protobuf/stubs/status.h>
namespace google {
@@ -60,7 +61,7 @@ class DescriptorPoolTypeResolver : public TypeResolver {
const DescriptorPool* pool)
: url_prefix_(url_prefix), pool_(pool) {}
- Status ResolveMessageType(const string& type_url, Type* type) {
+ Status ResolveMessageType(const string& type_url, Type* type) override {
string type_name;
Status status = ParseTypeUrl(type_url, &type_name);
if (!status.ok()) {
@@ -75,7 +76,7 @@ class DescriptorPoolTypeResolver : public TypeResolver {
return Status();
}
- Status ResolveEnumType(const string& type_url, Enum* enum_type) {
+ Status ResolveEnumType(const string& type_url, Enum* enum_type) override {
string type_name;
Status status = ParseTypeUrl(type_url, &type_name);
if (!status.ok()) {
@@ -179,9 +180,10 @@ class DescriptorPoolTypeResolver : public TypeResolver {
Status ParseTypeUrl(const string& type_url, string* type_name) {
if (type_url.substr(0, url_prefix_.size() + 1) != url_prefix_ + "/") {
- return Status(INVALID_ARGUMENT,
- StrCat("Invalid type URL, type URLs must be of the form '",
- url_prefix_, "/<typename>', got: ", type_url));
+ return Status(
+ INVALID_ARGUMENT,
+ StrCat("Invalid type URL, type URLs must be of the form '",
+ url_prefix_, "/<typename>', got: ", type_url));
}
*type_name = type_url.substr(url_prefix_.size() + 1);
return Status();
diff --git a/src/google/protobuf/util/type_resolver_util.h b/src/google/protobuf/util/type_resolver_util.h
index c17366fc..fa912b60 100644
--- a/src/google/protobuf/util/type_resolver_util.h
+++ b/src/google/protobuf/util/type_resolver_util.h
@@ -35,20 +35,23 @@
#include <string>
-#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
class DescriptorPool;
namespace util {
class TypeResolver;
+#include <google/protobuf/port_def.inc>
+
// Creates a TypeResolver that serves type information in the given descriptor
// pool. Caller takes ownership of the returned TypeResolver.
-LIBPROTOBUF_EXPORT TypeResolver* NewTypeResolverForDescriptorPool(
- const string& url_prefix, const DescriptorPool* pool);
+PROTOBUF_EXPORT TypeResolver* NewTypeResolverForDescriptorPool(
+ const std::string& url_prefix, const DescriptorPool* pool);
} // namespace util
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_UTIL_H__
diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc
index 3fdf84ed..0342a101 100644
--- a/src/google/protobuf/wire_format.cc
+++ b/src/google/protobuf/wire_format.cc
@@ -48,13 +48,14 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/map_field.h>
+#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
-namespace google {
const size_t kMapEntryTagByteSize = 2;
+namespace google {
namespace protobuf {
namespace internal {
@@ -172,8 +173,8 @@ bool WireFormat::ReadPackedEnumPreserveUnknowns(io::CodedInputStream* input,
io::CodedInputStream::Limit limit = input->PushLimit(length);
while (input->BytesUntilLimit() > 0) {
int value;
- if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
- int, WireFormatLite::TYPE_ENUM>(input, &value)) {
+ if (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
+ input, &value)) {
return false;
}
if (is_valid == NULL || is_valid(value)) {
@@ -617,31 +618,10 @@ bool WireFormat::ParseAndMergeField(
int value;
if (!WireFormatLite::ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(
input, &value)) return false;
- if (message->GetDescriptor()->file()->syntax() ==
- FileDescriptor::SYNTAX_PROTO3) {
- if (field->is_repeated()) {
- message_reflection->AddEnumValue(message, field, value);
- } else {
- message_reflection->SetEnumValue(message, field, value);
- }
+ if (field->is_repeated()) {
+ message_reflection->AddEnumValue(message, field, value);
} else {
- const EnumValueDescriptor* enum_value =
- field->enum_type()->FindValueByNumber(value);
- if (enum_value != NULL) {
- if (field->is_repeated()) {
- message_reflection->AddEnum(message, field, enum_value);
- } else {
- message_reflection->SetEnum(message, field, enum_value);
- }
- } else {
- // The enum value is not one of the known values. Add it to the
- // UnknownFieldSet.
- int64 sign_extended_value = static_cast<int64>(value);
- message_reflection->MutableUnknownFields(message)
- ->AddVarint(
- WireFormatLite::GetTagFieldNumber(tag),
- sign_extended_value);
- }
+ message_reflection->SetEnumValue(message, field, value);
}
break;
}
@@ -718,80 +698,23 @@ bool WireFormat::ParseAndMergeField(
bool WireFormat::ParseAndMergeMessageSetItem(
io::CodedInputStream* input,
Message* message) {
- const Reflection* message_reflection = message->GetReflection();
-
- // This method parses a group which should contain two fields:
- // required int32 type_id = 2;
- // required data message = 3;
-
- uint32 last_type_id = 0;
-
- // Once we see a type_id, we'll look up the FieldDescriptor for the
- // extension.
- const FieldDescriptor* field = NULL;
-
- // If we see message data before the type_id, we'll append it to this so
- // we can parse it later.
- string message_data;
-
- while (true) {
- uint32 tag = input->ReadTag();
- if (tag == 0) return false;
-
- switch (tag) {
- case WireFormatLite::kMessageSetTypeIdTag: {
- uint32 type_id;
- if (!input->ReadVarint32(&type_id)) return false;
- last_type_id = type_id;
- field = message_reflection->FindKnownExtensionByNumber(type_id);
-
- if (!message_data.empty()) {
- // We saw some message data before the type_id. Have to parse it
- // now.
- io::ArrayInputStream raw_input(message_data.data(),
- message_data.size());
- io::CodedInputStream sub_input(&raw_input);
- if (!ParseAndMergeMessageSetField(last_type_id, field, message,
- &sub_input)) {
- return false;
- }
- message_data.clear();
- }
-
- break;
- }
-
- case WireFormatLite::kMessageSetMessageTag: {
- if (last_type_id == 0) {
- // We haven't seen a type_id yet. Append this data to message_data.
- string temp;
- uint32 length;
- if (!input->ReadVarint32(&length)) return false;
- if (!input->ReadString(&temp, length)) return false;
- io::StringOutputStream output_stream(&message_data);
- io::CodedOutputStream coded_output(&output_stream);
- coded_output.WriteVarint32(length);
- coded_output.WriteString(temp);
- } else {
- // Already saw type_id, so we can parse this directly.
- if (!ParseAndMergeMessageSetField(last_type_id, field, message,
- input)) {
- return false;
- }
- }
+ struct MSReflective {
+ bool ParseField(int type_id, io::CodedInputStream* input) {
+ const FieldDescriptor* field =
+ message_reflection->FindKnownExtensionByNumber(type_id);
+ return ParseAndMergeMessageSetField(type_id, field, message, input);
+ }
- break;
- }
+ bool SkipField(uint32 tag, io::CodedInputStream* input) {
+ return WireFormat::SkipField(input, tag, NULL);
+ }
- case WireFormatLite::kMessageSetItemEndTag: {
- return true;
- }
+ const Reflection* message_reflection;
+ Message* message;
+ };
- default: {
- if (!SkipField(input, tag, NULL)) return false;
- }
- }
- }
+ return ParseMessageSetItemImpl(
+ input, MSReflective{message->GetReflection(), message});
}
// ===================================================================
diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h
index d602d214..6a658b36 100644
--- a/src/google/protobuf/wire_format.h
+++ b/src/google/protobuf/wire_format.h
@@ -44,16 +44,25 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/stubs/casts.h>
+
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
- namespace io {
- class CodedInputStream; // coded_stream.h
- class CodedOutputStream; // coded_stream.h
- }
- class UnknownFieldSet; // unknown_field_set.h
-}
+namespace io {
+class CodedInputStream; // coded_stream.h
+class CodedOutputStream; // coded_stream.h
+} // namespace io
+class UnknownFieldSet; // unknown_field_set.h
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace internal {
@@ -66,9 +75,8 @@ namespace internal {
// non-reflection based routines.
//
// This class is really a namespace that contains only static methods
-class LIBPROTOBUF_EXPORT WireFormat {
+class PROTOBUF_EXPORT WireFormat {
public:
-
// Given a field return its WireType
static inline WireFormatLite::WireType WireTypeForField(
const FieldDescriptor* field);
@@ -107,9 +115,8 @@ class LIBPROTOBUF_EXPORT WireFormat {
// a parameter to this procedure.
//
// These return false iff the underlying stream returns a write error.
- static void SerializeWithCachedSizes(
- const Message& message,
- int size, io::CodedOutputStream* output);
+ static void SerializeWithCachedSizes(const Message& message, int size,
+ io::CodedOutputStream* output);
// Implements Message::ByteSize() via reflection. WARNING: The result
// of this method is *not* cached anywhere. However, all embedded messages
@@ -127,13 +134,14 @@ class LIBPROTOBUF_EXPORT WireFormat {
static bool SkipField(io::CodedInputStream* input, uint32 tag,
UnknownFieldSet* unknown_fields);
- // Reads and ignores a message from the input. If unknown_fields is non-NULL,
- // the contents will be added to it.
+ // Reads and ignores a message from the input. If unknown_fields is
+ // non-NULL, the contents will be added to it.
static bool SkipMessage(io::CodedInputStream* input,
UnknownFieldSet* unknown_fields);
- // 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.
+ // 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(io::CodedInputStream* input,
uint32 field_number,
bool (*is_valid)(int),
@@ -149,22 +157,19 @@ class LIBPROTOBUF_EXPORT WireFormat {
//
// Returns a pointer past the last written byte.
static uint8* SerializeUnknownFieldsToArray(
- const UnknownFieldSet& unknown_fields,
- uint8* target);
+ const UnknownFieldSet& unknown_fields, uint8* target);
// Same thing except for messages that have the message_set_wire_format
// option.
static void SerializeUnknownMessageSetItems(
- const UnknownFieldSet& unknown_fields,
- io::CodedOutputStream* output);
+ const UnknownFieldSet& unknown_fields, io::CodedOutputStream* output);
// Same as above, except writing directly to the provided buffer.
// Requires that the buffer have sufficient capacity for
// ComputeUnknownMessageSetItemsSize(unknown_fields).
//
// Returns a pointer past the last written byte.
static uint8* SerializeUnknownMessageSetItemsToArray(
- const UnknownFieldSet& unknown_fields,
- uint8* target);
+ const UnknownFieldSet& unknown_fields, uint8* target);
// Compute the size of the UnknownFieldSet on the wire.
static size_t ComputeUnknownFieldsSize(const UnknownFieldSet& unknown_fields);
@@ -174,54 +179,47 @@ class LIBPROTOBUF_EXPORT WireFormat {
static size_t ComputeUnknownMessageSetItemsSize(
const UnknownFieldSet& unknown_fields);
-
// Helper functions for encoding and decoding tags. (Inlined below and in
// _inl.h)
//
- // This is different from MakeTag(field->number(), field->type()) in the case
- // of packed repeated fields.
+ // This is different from MakeTag(field->number(), field->type()) in the
+ // case of packed repeated fields.
static uint32 MakeTag(const FieldDescriptor* field);
// Parse a single field. The input should start out positioned immediately
// after the tag.
static bool ParseAndMergeField(
uint32 tag,
- const FieldDescriptor* field, // May be NULL for unknown
- Message* message,
- io::CodedInputStream* input);
+ const FieldDescriptor* field, // May be NULL for unknown
+ Message* message, io::CodedInputStream* input);
// Serialize a single field.
static void SerializeFieldWithCachedSizes(
- const FieldDescriptor* field, // Cannot be NULL
- const Message& message,
- io::CodedOutputStream* output);
+ const FieldDescriptor* field, // Cannot be NULL
+ const Message& message, io::CodedOutputStream* output);
// Compute size of a single field. If the field is a message type, this
// will call ByteSize() for the embedded message, insuring that it caches
// its size.
- static size_t FieldByteSize(
- const FieldDescriptor* field, // Cannot be NULL
- const Message& message);
+ static size_t FieldByteSize(const FieldDescriptor* field, // Cannot be NULL
+ const Message& message);
// Parse/serialize a MessageSet::Item group. Used with messages that use
// opion message_set_wire_format = true.
- static bool ParseAndMergeMessageSetItem(
- io::CodedInputStream* input,
- Message* message);
+ static bool ParseAndMergeMessageSetItem(io::CodedInputStream* input,
+ Message* message);
static void SerializeMessageSetItemWithCachedSizes(
- const FieldDescriptor* field,
- const Message& message,
+ const FieldDescriptor* field, const Message& message,
io::CodedOutputStream* output);
- static size_t MessageSetItemByteSize(
- const FieldDescriptor* field,
- const Message& message);
+ static size_t MessageSetItemByteSize(const FieldDescriptor* field,
+ const Message& message);
// Computes the byte size of a field, excluding tags. For packed fields, it
// only includes the size of the raw data, and not the size of the total
// length, but for other length-delimited types, the size of the length is
// included.
static size_t FieldDataOnlyByteSize(
- const FieldDescriptor* field, // Cannot be NULL
+ const FieldDescriptor* field, // Cannot be NULL
const Message& message);
enum Operation {
@@ -235,10 +233,8 @@ class LIBPROTOBUF_EXPORT WireFormat {
static void VerifyUTF8String(const char* data, int size, Operation op);
// The NamedField variant takes a field name in order to produce an
// informative error message if verification fails.
- static void VerifyUTF8StringNamedField(const char* data,
- int size,
- Operation op,
- const char* field_name);
+ static void VerifyUTF8StringNamedField(const char* data, int size,
+ Operation op, const char* field_name);
private:
// Skip a MessageSet field.
@@ -256,16 +252,16 @@ class LIBPROTOBUF_EXPORT WireFormat {
};
// Subclass of FieldSkipper which saves skipped fields to an UnknownFieldSet.
-class LIBPROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper {
+class PROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper {
public:
UnknownFieldSetFieldSkipper(UnknownFieldSet* unknown_fields)
: unknown_fields_(unknown_fields) {}
- virtual ~UnknownFieldSetFieldSkipper() {}
+ ~UnknownFieldSetFieldSkipper() override {}
// implements FieldSkipper -----------------------------------------
- virtual bool SkipField(io::CodedInputStream* input, uint32 tag);
- virtual bool SkipMessage(io::CodedInputStream* input);
- virtual void SkipUnknownEnum(int field_number, int value);
+ bool SkipField(io::CodedInputStream* input, uint32 tag) override;
+ bool SkipMessage(io::CodedInputStream* input) override;
+ void SkipUnknownEnum(int field_number, int value) override;
protected:
UnknownFieldSet* unknown_fields_;
@@ -287,8 +283,7 @@ inline WireFormatLite::WireType WireFormat::WireTypeForFieldType(
// Some compilers don't like enum -> enum casts, so we implicit_cast to
// int first.
return WireFormatLite::WireTypeForFieldType(
- static_cast<WireFormatLite::FieldType>(
- implicit_cast<int>(type)));
+ static_cast<WireFormatLite::FieldType>(::google::protobuf::implicit_cast<int>(type)));
}
inline uint32 WireFormat::MakeTag(const FieldDescriptor* field) {
@@ -299,37 +294,54 @@ inline size_t WireFormat::TagSize(int field_number,
FieldDescriptor::Type type) {
// Some compilers don't like enum -> enum casts, so we implicit_cast to
// int first.
- return WireFormatLite::TagSize(field_number,
- static_cast<WireFormatLite::FieldType>(
- implicit_cast<int>(type)));
+ return WireFormatLite::TagSize(
+ field_number,
+ static_cast<WireFormatLite::FieldType>(::google::protobuf::implicit_cast<int>(type)));
}
inline void WireFormat::VerifyUTF8String(const char* data, int size,
- WireFormat::Operation op) {
+ WireFormat::Operation op) {
#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
WireFormatLite::VerifyUtf8String(
data, size, static_cast<WireFormatLite::Operation>(op), NULL);
#else
// Avoid the compiler warning about unused variables.
- (void)data; (void)size; (void)op;
+ (void)data;
+ (void)size;
+ (void)op;
#endif
}
-inline void WireFormat::VerifyUTF8StringNamedField(
- const char* data, int size, WireFormat::Operation op,
- const char* field_name) {
+inline void WireFormat::VerifyUTF8StringNamedField(const char* data, int size,
+ WireFormat::Operation op,
+ const char* field_name) {
#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;
+ (void)data;
+ (void)size;
+ (void)op;
+ (void)field_name;
#endif
}
+inline void SerializeUnknownMessageSetItems(
+ const UnknownFieldSet& unknown_fields, io::CodedOutputStream* output) {
+ WireFormat::SerializeUnknownMessageSetItems(unknown_fields, output);
+}
+
+inline size_t ComputeUnknownMessageSetItemsSize(
+ const UnknownFieldSet& unknown_fields) {
+ return WireFormat::ComputeUnknownMessageSetItemsSize(unknown_fields);
+}
+
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_H__
diff --git a/src/google/protobuf/wire_format_lite.cc b/src/google/protobuf/wire_format_lite.cc
index 1d8cda5a..a393f367 100644
--- a/src/google/protobuf/wire_format_lite.cc
+++ b/src/google/protobuf/wire_format_lite.cc
@@ -43,6 +43,7 @@
#include <google/protobuf/io/coded_stream_inl.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
+#include <google/protobuf/port_def.inc>
namespace google {
@@ -301,8 +302,7 @@ bool WireFormatLite::ReadPackedEnumNoInline(io::CodedInputStream* input,
io::CodedInputStream::Limit limit = input->PushLimit(length);
while (input->BytesUntilLimit() > 0) {
int value;
- if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
- int, WireFormatLite::TYPE_ENUM>(input, &value)) {
+ if (!ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(input, &value)) {
return false;
}
if (is_valid == NULL || is_valid(value)) {
@@ -324,8 +324,7 @@ bool WireFormatLite::ReadPackedEnumPreserveUnknowns(
io::CodedInputStream::Limit limit = input->PushLimit(length);
while (input->BytesUntilLimit() > 0) {
int value;
- if (!google::protobuf::internal::WireFormatLite::ReadPrimitive<
- int, WireFormatLite::TYPE_ENUM>(input, &value)) {
+ if (!ReadPrimitive<int, WireFormatLite::TYPE_ENUM>(input, &value)) {
return false;
}
if (is_valid == NULL || is_valid(value)) {
@@ -583,7 +582,7 @@ void WireFormatLite::WriteMessageMaybeToArray(int field_number,
}
}
-GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static bool ReadBytesToString(
+PROTOBUF_ALWAYS_INLINE static bool ReadBytesToString(
io::CodedInputStream* input, string* value);
inline static bool ReadBytesToString(io::CodedInputStream* input,
string* value) {
@@ -597,12 +596,25 @@ bool WireFormatLite::ReadBytes(io::CodedInputStream* input, string* value) {
}
bool WireFormatLite::ReadBytes(io::CodedInputStream* input, string** p) {
- if (*p == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ if (*p == &GetEmptyStringAlreadyInited()) {
*p = new ::std::string();
}
return ReadBytesToString(input, *p);
}
+void PrintUTF8ErrorLog(const char* field_name, const char* operation_str,
+ bool emit_stacktrace) {
+ string stacktrace;
+ string quoted_field_name = "";
+ if (field_name != nullptr) {
+ quoted_field_name = StringPrintf(" '%s'", field_name);
+ }
+ GOOGLE_LOG(ERROR) << "String field" << quoted_field_name << " contains invalid "
+ << "UTF-8 data when " << operation_str << " a protocol "
+ << "buffer. Use the 'bytes' type if you intend to send raw "
+ << "bytes. " << stacktrace;
+}
+
bool WireFormatLite::VerifyUtf8String(const char* data,
int size,
Operation op,
@@ -618,15 +630,7 @@ bool WireFormatLite::VerifyUtf8String(const char* data,
break;
// no default case: have the compiler warn if a case is not covered.
}
- string quoted_field_name = "";
- if (field_name != NULL) {
- quoted_field_name = StringPrintf(" '%s'", field_name);
- }
- // no space below to avoid double space when the field name is missing.
- GOOGLE_LOG(ERROR) << "String field" << quoted_field_name << " contains invalid "
- << "UTF-8 data when " << operation_str << " a protocol "
- << "buffer. Use the 'bytes' type if you intend to send raw "
- << "bytes. ";
+ PrintUTF8ErrorLog(field_name, operation_str, false);
return false;
}
return true;
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index 77eaa9a6..60cadaee 100644
--- a/src/google/protobuf/wire_format_lite.h
+++ b/src/google/protobuf/wire_format_lite.h
@@ -45,7 +45,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/message_lite.h>
-#include <google/protobuf/stubs/port.h>
+#include <google/protobuf/port.h>
#include <google/protobuf/repeated_field.h>
// Do UTF-8 validation on string type in Debug build only
@@ -55,25 +55,30 @@
// 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.
+// 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 {
+namespace google {
namespace protobuf {
- template <typename T> class RepeatedField; // repeated_field.h
-}
+template <typename T>
+class RepeatedField; // repeated_field.h
+} // namespace protobuf
+} // namespace google
+namespace google {
namespace protobuf {
namespace internal {
class StringPieceField;
+#include <google/protobuf/port_def.inc>
+
// This class is for internal use by the protocol buffer library and by
// protocol-complier-generated message classes. It must not be called
// directly by clients.
@@ -83,9 +88,8 @@ class StringPieceField;
// reflection.
//
// This class is really a namespace that contains only static methods.
-class LIBPROTOBUF_EXPORT WireFormatLite {
+class PROTOBUF_EXPORT WireFormatLite {
public:
-
// -----------------------------------------------------------------
// Helper constants and functions related to the format. These are
// mostly meant for internal and generated code to use.
@@ -102,50 +106,50 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// unrecognized fields for forwards compatibility.
enum WireType {
- WIRETYPE_VARINT = 0,
- WIRETYPE_FIXED64 = 1,
+ WIRETYPE_VARINT = 0,
+ WIRETYPE_FIXED64 = 1,
WIRETYPE_LENGTH_DELIMITED = 2,
- WIRETYPE_START_GROUP = 3,
- WIRETYPE_END_GROUP = 4,
- WIRETYPE_FIXED32 = 5,
+ WIRETYPE_START_GROUP = 3,
+ WIRETYPE_END_GROUP = 4,
+ WIRETYPE_FIXED32 = 5,
};
// Lite alternative to FieldDescriptor::Type. Must be kept in sync.
enum FieldType {
- TYPE_DOUBLE = 1,
- TYPE_FLOAT = 2,
- TYPE_INT64 = 3,
- TYPE_UINT64 = 4,
- TYPE_INT32 = 5,
- TYPE_FIXED64 = 6,
- TYPE_FIXED32 = 7,
- TYPE_BOOL = 8,
- TYPE_STRING = 9,
- TYPE_GROUP = 10,
- TYPE_MESSAGE = 11,
- TYPE_BYTES = 12,
- TYPE_UINT32 = 13,
- TYPE_ENUM = 14,
- TYPE_SFIXED32 = 15,
- TYPE_SFIXED64 = 16,
- TYPE_SINT32 = 17,
- TYPE_SINT64 = 18,
- MAX_FIELD_TYPE = 18,
+ TYPE_DOUBLE = 1,
+ TYPE_FLOAT = 2,
+ TYPE_INT64 = 3,
+ TYPE_UINT64 = 4,
+ TYPE_INT32 = 5,
+ TYPE_FIXED64 = 6,
+ TYPE_FIXED32 = 7,
+ TYPE_BOOL = 8,
+ TYPE_STRING = 9,
+ TYPE_GROUP = 10,
+ TYPE_MESSAGE = 11,
+ TYPE_BYTES = 12,
+ TYPE_UINT32 = 13,
+ TYPE_ENUM = 14,
+ TYPE_SFIXED32 = 15,
+ TYPE_SFIXED64 = 16,
+ TYPE_SINT32 = 17,
+ TYPE_SINT64 = 18,
+ MAX_FIELD_TYPE = 18,
};
// Lite alternative to FieldDescriptor::CppType. Must be kept in sync.
enum CppType {
- CPPTYPE_INT32 = 1,
- CPPTYPE_INT64 = 2,
- CPPTYPE_UINT32 = 3,
- CPPTYPE_UINT64 = 4,
- CPPTYPE_DOUBLE = 5,
- CPPTYPE_FLOAT = 6,
- CPPTYPE_BOOL = 7,
- CPPTYPE_ENUM = 8,
- CPPTYPE_STRING = 9,
- CPPTYPE_MESSAGE = 10,
- MAX_CPPTYPE = 10,
+ CPPTYPE_INT32 = 1,
+ CPPTYPE_INT64 = 2,
+ CPPTYPE_UINT32 = 3,
+ CPPTYPE_UINT64 = 4,
+ CPPTYPE_DOUBLE = 5,
+ CPPTYPE_FLOAT = 6,
+ CPPTYPE_BOOL = 7,
+ CPPTYPE_ENUM = 8,
+ CPPTYPE_STRING = 9,
+ CPPTYPE_MESSAGE = 10,
+ MAX_CPPTYPE = 10,
};
// Helper method to get the CppType for a particular Type.
@@ -165,8 +169,8 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// Helper functions for encoding and decoding tags. (Inlined below and in
// _inl.h)
//
- // This is different from MakeTag(field->number(), field->type()) in the case
- // of packed repeated fields.
+ // This is different from MakeTag(field->number(), field->type()) in the
+ // case of packed repeated fields.
static uint32 MakeTag(int field_number, WireType type);
static WireType GetTagWireType(uint32 tag);
static int GetTagFieldNumber(uint32 tag);
@@ -177,9 +181,9 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
WireFormatLite::FieldType type);
// Skips a field value with the given tag. The input should start
- // positioned immediately after the tag. Skipped values are simply discarded,
- // not recorded anywhere. See WireFormat::SkipField() for a version that
- // records to an UnknownFieldSet.
+ // positioned immediately after the tag. Skipped values are simply
+ // discarded, not recorded anywhere. See WireFormat::SkipField() for a
+ // version that records to an UnknownFieldSet.
static bool SkipField(io::CodedInputStream* input, uint32 tag);
// Skips a field value with the given tag. The input should start
@@ -198,14 +202,12 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static bool SkipMessage(io::CodedInputStream* input,
io::CodedOutputStream* output);
-// This macro does the same thing as WireFormatLite::MakeTag(), but the
-// result is usable as a compile-time constant, which makes it usable
-// as a switch case or a template input. WireFormatLite::MakeTag() is more
-// type-safe, though, so prefer it if possible.
-#define GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(FIELD_NUMBER, TYPE) \
- static_cast<uint32>( \
- (static_cast<uint32>(FIELD_NUMBER) << ::google::protobuf::internal::WireFormatLite::kTagTypeBits) \
- | (TYPE))
+ // This macro does the same thing as WireFormatLite::MakeTag(), but the
+ // result is usable as a compile-time constant, which makes it usable
+ // as a switch case or a template input. WireFormatLite::MakeTag() is more
+ // type-safe, though, so prefer it if possible.
+#define GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(FIELD_NUMBER, TYPE) \
+ static_cast<uint32>((static_cast<uint32>(FIELD_NUMBER) << 3) | (TYPE))
// These are the tags for the old MessageSet format, which was defined as:
// message MessageSet {
@@ -217,18 +219,14 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static const int kMessageSetItemNumber = 1;
static const int kMessageSetTypeIdNumber = 2;
static const int kMessageSetMessageNumber = 3;
- static const int kMessageSetItemStartTag =
- GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetItemNumber,
- WireFormatLite::WIRETYPE_START_GROUP);
- static const int kMessageSetItemEndTag =
- GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetItemNumber,
- WireFormatLite::WIRETYPE_END_GROUP);
- static const int kMessageSetTypeIdTag =
- GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetTypeIdNumber,
- WireFormatLite::WIRETYPE_VARINT);
- static const int kMessageSetMessageTag =
- GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetMessageNumber,
- WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
+ static const int kMessageSetItemStartTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
+ kMessageSetItemNumber, WireFormatLite::WIRETYPE_START_GROUP);
+ static const int kMessageSetItemEndTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
+ kMessageSetItemNumber, WireFormatLite::WIRETYPE_END_GROUP);
+ static const int kMessageSetTypeIdTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
+ kMessageSetTypeIdNumber, WireFormatLite::WIRETYPE_VARINT);
+ static const int kMessageSetMessageTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
+ kMessageSetMessageNumber, WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
// Byte size of all tags of a MessageSet::Item combined.
static const size_t kMessageSetItemTagsSize;
@@ -248,9 +246,9 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// the purpose of varint. So, for the "sint32" and "sint64" field types,
// we ZigZag-encode the values.
static uint32 ZigZagEncode32(int32 n);
- static int32 ZigZagDecode32(uint32 n);
+ static int32 ZigZagDecode32(uint32 n);
static uint64 ZigZagEncode64(int64 n);
- static int64 ZigZagDecode64(uint64 n);
+ static int64 ZigZagDecode64(uint64 n);
// =================================================================
// Methods for reading/writing individual field. The implementations
@@ -258,7 +256,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// that file to use these.
#ifdef NDEBUG
-#define INL GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
+#define INL PROTOBUF_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
@@ -296,8 +294,9 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
//
// This is only implemented for the types with fixed wire size, e.g.
// float, double, and the (s)fixed* types.
- template <typename CType, enum FieldType DeclaredType> INL
- static const uint8* ReadPrimitiveFromArray(const uint8* buffer, CType* value);
+ template <typename CType, enum FieldType DeclaredType>
+ INL static const uint8* ReadPrimitiveFromArray(const uint8* buffer,
+ CType* value);
// Reads a primitive packed field.
//
@@ -325,16 +324,16 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
io::CodedOutputStream* unknown_fields_stream, RepeatedField<int>* values);
// Read a string. ReadString(..., string* value) requires an existing string.
- static inline bool ReadString(io::CodedInputStream* input, string* value);
+ static inline bool ReadString(io::CodedInputStream* input, std::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(io::CodedInputStream* input, *p). This is useful for reducing
// code size.
- static inline bool ReadString(io::CodedInputStream* input, string** p);
+ static inline bool ReadString(io::CodedInputStream* input, std::string** p);
// Analogous to ReadString().
- static bool ReadBytes(io::CodedInputStream* input, string* value);
- static bool ReadBytes(io::CodedInputStream* input, string** p);
+ static bool ReadBytes(io::CodedInputStream* input, std::string* value);
+ static bool ReadBytes(io::CodedInputStream* input, std::string** p);
enum Operation {
PARSE = 0,
@@ -342,8 +341,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
};
// Returns true if the data is valid UTF-8.
- static bool VerifyUtf8String(const char* data, int size,
- Operation op,
+ static bool VerifyUtf8String(const char* data, int size, Operation op,
const char* field_name);
template <typename MessageType>
@@ -362,7 +360,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
return ReadGroup(field_number, input, value);
}
- template<typename MessageType>
+ template <typename MessageType>
static inline bool ReadMessageNoVirtual(io::CodedInputStream* input,
MessageType* value) {
return ReadMessage(input, value);
@@ -440,13 +438,13 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
static void WriteEnum(int field_number, int value,
io::CodedOutputStream* output);
- static void WriteString(int field_number, const string& value,
+ static void WriteString(int field_number, const std::string& value,
io::CodedOutputStream* output);
- static void WriteBytes(int field_number, const string& value,
+ static void WriteBytes(int field_number, const std::string& value,
io::CodedOutputStream* output);
- static void WriteStringMaybeAliased(int field_number, const string& value,
+ static void WriteStringMaybeAliased(int field_number, const std::string& value,
io::CodedOutputStream* output);
- static void WriteBytesMaybeAliased(int field_number, const string& value,
+ static void WriteBytesMaybeAliased(int field_number, const std::string& value,
io::CodedOutputStream* output);
static void WriteGroup(int field_number, const MessageLite& value,
@@ -494,43 +492,43 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
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);
+ 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(int field_number, int32 value,
@@ -562,44 +560,58 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
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,
+ 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 std::string& value,
uint8* target);
- INL static uint8* WriteBytesToArray(int field_number, const string& value,
+ INL static uint8* WriteBytesToArray(int field_number, const std::string& value,
uint8* target);
// Whether to serialize deterministically (e.g., map keys are
@@ -607,12 +619,12 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// 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.
- template<typename MessageType>
+ template <typename MessageType>
INL static uint8* InternalWriteGroupToArray(int field_number,
const MessageType& value,
bool deterministic,
uint8* target);
- template<typename MessageType>
+ template <typename MessageType>
INL static uint8* InternalWriteMessageToArray(int field_number,
const MessageType& value,
bool deterministic,
@@ -663,45 +675,45 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// 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
// count, but you may have to call XxSize() for each individual element.)
- static inline size_t Int32Size ( int32 value);
- static inline size_t Int64Size ( int64 value);
- static inline size_t UInt32Size (uint32 value);
- static inline size_t UInt64Size (uint64 value);
- static inline size_t SInt32Size ( int32 value);
- static inline size_t SInt64Size ( int64 value);
- static inline size_t EnumSize ( int value);
-
- static size_t Int32Size (const RepeatedField< int32>& value);
- static size_t Int64Size (const RepeatedField< int64>& value);
+ static inline size_t Int32Size(int32 value);
+ static inline size_t Int64Size(int64 value);
+ static inline size_t UInt32Size(uint32 value);
+ static inline size_t UInt64Size(uint64 value);
+ static inline size_t SInt32Size(int32 value);
+ static inline size_t SInt64Size(int64 value);
+ static inline size_t EnumSize(int value);
+
+ static size_t Int32Size(const RepeatedField<int32>& value);
+ static size_t Int64Size(const RepeatedField<int64>& value);
static size_t UInt32Size(const RepeatedField<uint32>& value);
static size_t UInt64Size(const RepeatedField<uint64>& value);
- static size_t SInt32Size(const RepeatedField< int32>& value);
- static size_t SInt64Size(const RepeatedField< int64>& value);
- static size_t EnumSize (const RepeatedField< int>& value);
+ static size_t SInt32Size(const RepeatedField<int32>& value);
+ static 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;
+ static const size_t kFixed32Size = 4;
+ static const size_t kFixed64Size = 8;
static const size_t kSFixed32Size = 4;
static const size_t kSFixed64Size = 8;
- static const size_t kFloatSize = 4;
- static const size_t kDoubleSize = 8;
- static const size_t kBoolSize = 1;
+ static const size_t kFloatSize = 4;
+ static const size_t kDoubleSize = 8;
+ static const size_t kBoolSize = 1;
- static inline size_t StringSize(const string& value);
- static inline size_t BytesSize (const string& value);
+ static inline size_t StringSize(const std::string& value);
+ static inline size_t BytesSize(const std::string& value);
- template<typename MessageType>
- static inline size_t GroupSize (const MessageType& value);
- template<typename MessageType>
+ template <typename MessageType>
+ static inline size_t GroupSize(const MessageType& value);
+ template <typename MessageType>
static inline size_t MessageSize(const MessageType& value);
// Like above, but de-virtualize the call to ByteSize(). The
// pointer must point at an instance of MessageType, *not* a subclass (or
// the subclass must not override ByteSize()).
- template<typename MessageType>
- static inline size_t GroupSizeNoVirtual (const MessageType& value);
- template<typename MessageType>
+ template <typename MessageType>
+ static inline size_t GroupSizeNoVirtual(const MessageType& value);
+ template <typename MessageType>
static inline size_t MessageSizeNoVirtual(const MessageType& value);
// Given the length of data, calculate the byte size of the data on the
@@ -713,18 +725,14 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// 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_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static bool ReadRepeatedFixedSizePrimitive(
- int tag_size,
- uint32 tag,
- google::protobuf::io::CodedInputStream* input,
+ PROTOBUF_ALWAYS_INLINE static bool ReadRepeatedFixedSizePrimitive(
+ int tag_size, uint32 tag, io::CodedInputStream* input,
RepeatedField<CType>* value);
// Like ReadRepeatedFixedSizePrimitive but for packed primitive fields.
template <typename CType, enum FieldType DeclaredType>
- GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
- static bool ReadPackedFixedSizePrimitive(
- google::protobuf::io::CodedInputStream* input, RepeatedField<CType>* value);
+ PROTOBUF_ALWAYS_INLINE static bool ReadPackedFixedSizePrimitive(
+ io::CodedInputStream* input, RepeatedField<CType>* value);
static const CppType kFieldTypeToCppTypeMap[];
static const WireFormatLite::WireType kWireTypeForFieldType[];
@@ -736,7 +744,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// discards them. WireFormat defines a subclass which writes to an
// UnknownFieldSet. This class is used by ExtensionSet::ParseField(), since
// ExtensionSet is part of the lite library but UnknownFieldSet is not.
-class LIBPROTOBUF_EXPORT FieldSkipper {
+class PROTOBUF_EXPORT FieldSkipper {
public:
FieldSkipper() {}
virtual ~FieldSkipper() {}
@@ -756,26 +764,25 @@ class LIBPROTOBUF_EXPORT FieldSkipper {
// Subclass of FieldSkipper which saves skipped fields to a CodedOutputStream.
-class LIBPROTOBUF_EXPORT CodedOutputStreamFieldSkipper : public FieldSkipper {
+class PROTOBUF_EXPORT CodedOutputStreamFieldSkipper : public FieldSkipper {
public:
explicit CodedOutputStreamFieldSkipper(io::CodedOutputStream* unknown_fields)
: unknown_fields_(unknown_fields) {}
virtual ~CodedOutputStreamFieldSkipper() {}
// implements FieldSkipper -----------------------------------------
- virtual bool SkipField(io::CodedInputStream* input, uint32 tag);
- virtual bool SkipMessage(io::CodedInputStream* input);
- virtual void SkipUnknownEnum(int field_number, int value);
+ bool SkipField(io::CodedInputStream* input, uint32 tag) override;
+ bool SkipMessage(io::CodedInputStream* input) override;
+ void SkipUnknownEnum(int field_number, int value) override;
protected:
io::CodedOutputStream* unknown_fields_;
};
-
// inline methods ====================================================
-inline WireFormatLite::CppType
-WireFormatLite::FieldTypeToCppType(FieldType type) {
+inline WireFormatLite::CppType WireFormatLite::FieldTypeToCppType(
+ FieldType type) {
return kFieldTypeToCppTypeMap[type];
}
@@ -794,7 +801,7 @@ inline int WireFormatLite::GetTagFieldNumber(uint32 tag) {
inline size_t WireFormatLite::TagSize(int field_number,
WireFormatLite::FieldType type) {
size_t result = io::CodedOutputStream::VarintSize32(
- static_cast<uint32>(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;
@@ -804,25 +811,37 @@ inline size_t WireFormatLite::TagSize(int field_number,
}
inline uint32 WireFormatLite::EncodeFloat(float value) {
- union {float f; uint32 i;};
+ union {
+ float f;
+ uint32 i;
+ };
f = value;
return i;
}
inline float WireFormatLite::DecodeFloat(uint32 value) {
- union {float f; uint32 i;};
+ union {
+ float f;
+ uint32 i;
+ };
i = value;
return f;
}
inline uint64 WireFormatLite::EncodeDouble(double value) {
- union {double f; uint64 i;};
+ union {
+ double f;
+ uint64 i;
+ };
f = value;
return i;
}
inline double WireFormatLite::DecodeDouble(uint64 value) {
- union {double f; uint64 i;};
+ union {
+ double f;
+ uint64 i;
+ };
i = value;
return f;
}
@@ -877,17 +896,28 @@ inline int64 WireFormatLite::ZigZagDecode64(uint64 n) {
// call ReadBytes().
inline bool WireFormatLite::ReadString(io::CodedInputStream* input,
- string* value) {
+ std::string* value) {
return ReadBytes(input, value);
}
inline bool WireFormatLite::ReadString(io::CodedInputStream* input,
- string** p) {
+ std::string** p) {
return ReadBytes(input, p);
}
+inline void SerializeUnknownMessageSetItems(const std::string& unknown_fields,
+ io::CodedOutputStream* output) {
+ output->WriteString(unknown_fields);
+}
+
+inline size_t ComputeUnknownMessageSetItemsSize(const std::string& unknown_fields) {
+ return unknown_fields.size();
+}
+
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_H__
diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h
index 6cd2c2fb..44c4b5ca 100644
--- a/src/google/protobuf/wire_format_lite_inl.h
+++ b/src/google/protobuf/wire_format_lite_inl.h
@@ -40,13 +40,19 @@
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/arenastring.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite.h>
-#include <google/protobuf/io/coded_stream.h>
-#include <google/protobuf/arenastring.h>
+#ifdef SWIG
+#error "You cannot SWIG proto headers"
+#endif
+
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -866,7 +872,7 @@ inline uint8* WireFormatLite::WriteEnumToArray(
return WritePrimitiveToArray(field_number, value, WriteEnumToArray, target);
}
inline uint8* WireFormatLite::WriteStringToArray(int field_number,
- const string& value,
+ const std::string& value,
uint8* target) {
// String is for UTF-8 text only
// WARNING: In wire_format.cc, both strings and bytes are handled by
@@ -876,7 +882,7 @@ inline uint8* WireFormatLite::WriteStringToArray(int field_number,
return io::CodedOutputStream::WriteStringWithSizeToArray(value, target);
}
inline uint8* WireFormatLite::WriteBytesToArray(int field_number,
- const string& value,
+ const std::string& value,
uint8* target) {
target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target);
return io::CodedOutputStream::WriteStringWithSizeToArray(value, target);
@@ -949,10 +955,10 @@ inline size_t WireFormatLite::EnumSize(int value) {
return io::CodedOutputStream::VarintSize32SignExtended(value);
}
-inline size_t WireFormatLite::StringSize(const string& value) {
+inline size_t WireFormatLite::StringSize(const std::string& value) {
return LengthDelimitedSize(value.size());
}
-inline size_t WireFormatLite::BytesSize(const string& value) {
+inline size_t WireFormatLite::BytesSize(const std::string& value) {
return LengthDelimitedSize(value.size());
}
@@ -989,8 +995,80 @@ inline size_t WireFormatLite::LengthDelimitedSize(size_t length) {
static_cast<uint32>(length));
}
+template <typename MS>
+bool ParseMessageSetItemImpl(io::CodedInputStream* input, MS ms) {
+ // This method parses a group which should contain two fields:
+ // required int32 type_id = 2;
+ // required data message = 3;
+
+ uint32 last_type_id = 0;
+
+ // If we see message data before the type_id, we'll append it to this so
+ // we can parse it later.
+ std::string message_data;
+
+ while (true) {
+ const uint32 tag = input->ReadTagNoLastTag();
+ if (tag == 0) return false;
+
+ switch (tag) {
+ case WireFormatLite::kMessageSetTypeIdTag: {
+ uint32 type_id;
+ if (!input->ReadVarint32(&type_id)) return false;
+ last_type_id = type_id;
+
+ if (!message_data.empty()) {
+ // We saw some message data before the type_id. Have to parse it
+ // now.
+ io::CodedInputStream sub_input(
+ reinterpret_cast<const uint8*>(message_data.data()),
+ static_cast<int>(message_data.size()));
+ if (!ms.ParseField(last_type_id, &sub_input)) {
+ return false;
+ }
+ message_data.clear();
+ }
+
+ break;
+ }
+
+ case WireFormatLite::kMessageSetMessageTag: {
+ if (last_type_id == 0) {
+ // We haven't seen a type_id yet. Append this data to message_data.
+ uint32 length;
+ if (!input->ReadVarint32(&length)) return false;
+ if (static_cast<int32>(length) < 0) return false;
+ uint32 size = static_cast<uint32>(length +
+ io::CodedOutputStream::VarintSize32(length));
+ message_data.resize(size);
+ auto ptr = reinterpret_cast<uint8*>(&message_data[0]);
+ ptr = io::CodedOutputStream::WriteVarint32ToArray(length, ptr);
+ if (!input->ReadRaw(ptr, length)) return false;
+ } else {
+ // Already saw type_id, so we can parse this directly.
+ if (!ms.ParseField(last_type_id, input)) {
+ return false;
+ }
+ }
+
+ break;
+ }
+
+ case WireFormatLite::kMessageSetItemEndTag: {
+ return true;
+ }
+
+ default: {
+ if (!ms.SkipField(tag, input)) return false;
+ }
+ }
+ }
+}
+
} // namespace internal
} // namespace protobuf
-
} // namespace google
+
+#include <google/protobuf/port_undef.inc>
+
#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__
diff --git a/src/google/protobuf/wire_format_unittest.cc b/src/google/protobuf/wire_format_unittest.cc
index 736a1282..babdcc65 100644
--- a/src/google/protobuf/wire_format_unittest.cc
+++ b/src/google/protobuf/wire_format_unittest.cc
@@ -48,8 +48,11 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
+#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/port_def.inc>
+
namespace google {
namespace protobuf {
namespace internal {
@@ -59,17 +62,16 @@ TEST(WireFormatTest, EnumsInSync) {
// Verify that WireFormatLite::FieldType and WireFormatLite::CppType match
// FieldDescriptor::Type and FieldDescriptor::CppType.
- EXPECT_EQ(implicit_cast<int>(FieldDescriptor::MAX_TYPE),
- implicit_cast<int>(WireFormatLite::MAX_FIELD_TYPE));
- EXPECT_EQ(implicit_cast<int>(FieldDescriptor::MAX_CPPTYPE),
- implicit_cast<int>(WireFormatLite::MAX_CPPTYPE));
+ EXPECT_EQ(::google::protobuf::implicit_cast<int>(FieldDescriptor::MAX_TYPE),
+ ::google::protobuf::implicit_cast<int>(WireFormatLite::MAX_FIELD_TYPE));
+ EXPECT_EQ(::google::protobuf::implicit_cast<int>(FieldDescriptor::MAX_CPPTYPE),
+ ::google::protobuf::implicit_cast<int>(WireFormatLite::MAX_CPPTYPE));
for (int i = 1; i <= WireFormatLite::MAX_FIELD_TYPE; i++) {
- EXPECT_EQ(
- implicit_cast<int>(FieldDescriptor::TypeToCppType(
- static_cast<FieldDescriptor::Type>(i))),
- implicit_cast<int>(WireFormatLite::FieldTypeToCppType(
- static_cast<WireFormatLite::FieldType>(i))));
+ EXPECT_EQ(::google::protobuf::implicit_cast<int>(FieldDescriptor::TypeToCppType(
+ static_cast<FieldDescriptor::Type>(i))),
+ ::google::protobuf::implicit_cast<int>(WireFormatLite::FieldTypeToCppType(
+ static_cast<WireFormatLite::FieldType>(i))));
}
}
@@ -485,14 +487,15 @@ TEST(WireFormatTest, SerializeMessageSetVariousWaysAreEqual) {
// Serialize to flat array
{
- uint8* target = reinterpret_cast<uint8*>(string_as_array(&flat_data));
+ uint8* target = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&flat_data));
uint8* end = message_set.SerializeWithCachedSizesToArray(target);
EXPECT_EQ(size, end - target);
}
// Serialize to buffer
{
- io::ArrayOutputStream array_stream(string_as_array(&stream_data), size, 1);
+ io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&stream_data), size,
+ 1);
io::CodedOutputStream output_stream(&array_stream);
message_set.SerializeWithCachedSizes(&output_stream);
ASSERT_FALSE(output_stream.HadError());
@@ -664,8 +667,8 @@ TEST(WireFormatTest, UnknownFieldRecursionLimit) {
TEST(WireFormatTest, ZigZag) {
// avoid line-wrapping
-#define LL(x) GOOGLE_LONGLONG(x)
-#define ULL(x) GOOGLE_ULONGLONG(x)
+#define LL(x) PROTOBUF_LONGLONG(x)
+#define ULL(x) PROTOBUF_ULONGLONG(x)
#define ZigZagEncode32(x) WireFormatLite::ZigZagEncode32(x)
#define ZigZagDecode32(x) WireFormatLite::ZigZagDecode32(x)
#define ZigZagEncode64(x) WireFormatLite::ZigZagEncode64(x)
@@ -745,8 +748,8 @@ TEST(WireFormatTest, RepeatedScalarsDifferentTagSizes) {
}
// Make sure that we have a variety of tag sizes.
- const google::protobuf::Descriptor* desc = msg1.GetDescriptor();
- const google::protobuf::FieldDescriptor* field;
+ const Descriptor* desc = msg1.GetDescriptor();
+ const FieldDescriptor* field;
field = desc->FindFieldByName("repeated_fixed32");
ASSERT_TRUE(field != NULL);
ASSERT_EQ(1, WireFormat::TagSize(field->number(), field->type()));
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index ffd905f5..3d7e7cb9 100644
--- a/src/google/protobuf/wrappers.pb.cc
+++ b/src/google/protobuf/wrappers.pb.cc
@@ -6,70 +6,57 @@
#include <algorithm>
#include <google/protobuf/stubs/common.h>
-#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#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)
+#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class DoubleValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<DoubleValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<DoubleValue> _instance;
} _DoubleValue_default_instance_;
class FloatValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<FloatValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<FloatValue> _instance;
} _FloatValue_default_instance_;
class Int64ValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Int64Value>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Int64Value> _instance;
} _Int64Value_default_instance_;
class UInt64ValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<UInt64Value>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<UInt64Value> _instance;
} _UInt64Value_default_instance_;
class Int32ValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<Int32Value>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<Int32Value> _instance;
} _Int32Value_default_instance_;
class UInt32ValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<UInt32Value>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<UInt32Value> _instance;
} _UInt32Value_default_instance_;
class BoolValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<BoolValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<BoolValue> _instance;
} _BoolValue_default_instance_;
class StringValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<StringValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<StringValue> _instance;
} _StringValue_default_instance_;
class BytesValueDefaultTypeInternal {
public:
- ::google::protobuf::internal::ExplicitlyConstructed<BytesValue>
- _instance;
+ ::google::protobuf::internal::ExplicitlyConstructed<BytesValue> _instance;
} _BytesValue_default_instance_;
} // namespace protobuf
} // namespace google
-namespace protobuf_google_2fprotobuf_2fwrappers_2eproto {
-static void InitDefaultsDoubleValue() {
+static void InitDefaultsDoubleValue_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -80,10 +67,10 @@ static void InitDefaultsDoubleValue() {
::google::protobuf::DoubleValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DoubleValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDoubleValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_DoubleValue_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsDoubleValue_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsFloatValue() {
+static void InitDefaultsFloatValue_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -94,10 +81,10 @@ static void InitDefaultsFloatValue() {
::google::protobuf::FloatValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FloatValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_FloatValue_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatValue_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsInt64Value() {
+static void InitDefaultsInt64Value_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -108,10 +95,10 @@ static void InitDefaultsInt64Value() {
::google::protobuf::Int64Value::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int64Value =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64Value}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int64Value_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64Value_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsUInt64Value() {
+static void InitDefaultsUInt64Value_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -122,10 +109,10 @@ static void InitDefaultsUInt64Value() {
::google::protobuf::UInt64Value::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt64Value =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt64Value}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt64Value_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt64Value_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsInt32Value() {
+static void InitDefaultsInt32Value_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -136,10 +123,10 @@ static void InitDefaultsInt32Value() {
::google::protobuf::Int32Value::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int32Value =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt32Value}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Int32Value_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt32Value_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsUInt32Value() {
+static void InitDefaultsUInt32Value_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -150,10 +137,10 @@ static void InitDefaultsUInt32Value() {
::google::protobuf::UInt32Value::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt32Value =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt32Value}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_UInt32Value_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsUInt32Value_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsBoolValue() {
+static void InitDefaultsBoolValue_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -164,10 +151,10 @@ static void InitDefaultsBoolValue() {
::google::protobuf::BoolValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BoolValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBoolValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BoolValue_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBoolValue_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsStringValue() {
+static void InitDefaultsStringValue_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -178,10 +165,10 @@ static void InitDefaultsStringValue() {
::google::protobuf::StringValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_StringValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStringValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_StringValue_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsStringValue_google_2fprotobuf_2fwrappers_2eproto}, {}};
-static void InitDefaultsBytesValue() {
+static void InitDefaultsBytesValue_google_2fprotobuf_2fwrappers_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
@@ -192,80 +179,82 @@ static void InitDefaultsBytesValue() {
::google::protobuf::BytesValue::InitAsDefaultInstance();
}
-LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BytesValue =
- {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesValue}, {}};
+PROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_BytesValue_google_2fprotobuf_2fwrappers_2eproto =
+ {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesValue_google_2fprotobuf_2fwrappers_2eproto}, {}};
-void InitDefaults() {
- ::google::protobuf::internal::InitSCC(&scc_info_DoubleValue.base);
- ::google::protobuf::internal::InitSCC(&scc_info_FloatValue.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Int64Value.base);
- ::google::protobuf::internal::InitSCC(&scc_info_UInt64Value.base);
- ::google::protobuf::internal::InitSCC(&scc_info_Int32Value.base);
- ::google::protobuf::internal::InitSCC(&scc_info_UInt32Value.base);
- ::google::protobuf::internal::InitSCC(&scc_info_BoolValue.base);
- ::google::protobuf::internal::InitSCC(&scc_info_StringValue.base);
- ::google::protobuf::internal::InitSCC(&scc_info_BytesValue.base);
+void InitDefaults_google_2fprotobuf_2fwrappers_2eproto() {
+ ::google::protobuf::internal::InitSCC(&scc_info_DoubleValue_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_FloatValue_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Int64Value_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_UInt64Value_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_Int32Value_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_UInt32Value_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_BoolValue_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_StringValue_google_2fprotobuf_2fwrappers_2eproto.base);
+ ::google::protobuf::internal::InitSCC(&scc_info_BytesValue_google_2fprotobuf_2fwrappers_2eproto.base);
}
-::google::protobuf::Metadata file_level_metadata[9];
+::google::protobuf::Metadata file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[9];
+constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr;
+constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr;
-const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+const ::google::protobuf::uint32 TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::DoubleValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::DoubleValue, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::FloatValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::FloatValue, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int64Value, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Int64Value, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt64Value, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UInt64Value, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Int32Value, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::Int32Value, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::UInt32Value, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::UInt32Value, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BoolValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::BoolValue, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::StringValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::StringValue, value_),
~0u, // no _has_bits_
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::BytesValue, _internal_metadata_),
+ PROTOBUF_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_),
+ PROTOBUF_FIELD_OFFSET(::google::protobuf::BytesValue, value_),
};
-static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
+static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::DoubleValue)},
{ 6, -1, sizeof(::google::protobuf::FloatValue)},
{ 12, -1, sizeof(::google::protobuf::Int64Value)},
@@ -289,57 +278,39 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_BytesValue_default_instance_),
};
-void protobuf_AssignDescriptors() {
- AddDescriptors();
- AssignDescriptors(
- "google/protobuf/wrappers.proto", schemas, file_default_instances, TableStruct::offsets,
- file_level_metadata, NULL, NULL);
-}
-
-void protobuf_AssignDescriptorsOnce() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
-}
-
-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);
-}
-
-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"
- "ue\022\r\n\005value\030\001 \001(\003\"\034\n\013UInt64Value\022\r\n\005valu"
- "e\030\001 \001(\004\"\033\n\nInt32Value\022\r\n\005value\030\001 \001(\005\"\034\n\013"
- "UInt32Value\022\r\n\005value\030\001 \001(\r\"\032\n\tBoolValue\022"
- "\r\n\005value\030\001 \001(\010\"\034\n\013StringValue\022\r\n\005value\030\001"
- " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B|\n\023com"
- ".google.protobufB\rWrappersProtoP\001Z*githu"
- "b.com/golang/protobuf/ptypes/wrappers\370\001\001"
- "\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypesb"
- "\006proto3"
+::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto = {
+ {}, AddDescriptors_google_2fprotobuf_2fwrappers_2eproto, "google/protobuf/wrappers.proto", schemas,
+ file_default_instances, TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets,
+ file_level_metadata_google_2fprotobuf_2fwrappers_2eproto, 9, file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto, file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto,
+};
+
+::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fwrappers_2eproto = {
+ false, InitDefaults_google_2fprotobuf_2fwrappers_2eproto,
+ "\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"
+ "ue\022\r\n\005value\030\001 \001(\003\"\034\n\013UInt64Value\022\r\n\005valu"
+ "e\030\001 \001(\004\"\033\n\nInt32Value\022\r\n\005value\030\001 \001(\005\"\034\n\013"
+ "UInt32Value\022\r\n\005value\030\001 \001(\r\"\032\n\tBoolValue\022"
+ "\r\n\005value\030\001 \001(\010\"\034\n\013StringValue\022\r\n\005value\030\001"
+ " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B|\n\023com"
+ ".google.protobufB\rWrappersProtoP\001Z*githu"
+ "b.com/golang/protobuf/ptypes/wrappers\370\001\001"
+ "\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypesb"
+ "\006proto3"
+,
+ "google/protobuf/wrappers.proto", &assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto, 447,
+};
+
+void AddDescriptors_google_2fprotobuf_2fwrappers_2eproto() {
+ static constexpr ::google::protobuf::internal::InitFunc deps[1] =
+ {
};
- ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
- descriptor, 447);
- ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
- "google/protobuf/wrappers.proto", &protobuf_RegisterTypes);
+ ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fwrappers_2eproto, deps, 0);
}
-void AddDescriptors() {
- static ::google::protobuf::internal::once_flag once;
- ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
-}
-// Force AddDescriptors() to be called at dynamic initialization time.
-struct StaticDescriptorInitializer {
- StaticDescriptorInitializer() {
- AddDescriptors();
- }
-} static_descriptor_initializer;
-} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_google_2fprotobuf_2fwrappers_2eproto = []() { AddDescriptors_google_2fprotobuf_2fwrappers_2eproto(); return true; }();
namespace google {
namespace protobuf {
@@ -347,21 +318,22 @@ namespace protobuf {
void DoubleValue::InitAsDefaultInstance() {
}
+class DoubleValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DoubleValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DoubleValue::DoubleValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DoubleValue)
}
DoubleValue::DoubleValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue)
@@ -391,18 +363,13 @@ void DoubleValue::ArenaDtor(void* object) {
DoubleValue* _this = reinterpret_cast< DoubleValue* >(object);
(void)_this;
}
-void DoubleValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void DoubleValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void DoubleValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* DoubleValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const DoubleValue& DoubleValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_DoubleValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_DoubleValue_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -417,9 +384,55 @@ void DoubleValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* DoubleValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<DoubleValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // double value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 9) goto handle_unusual;
+ double val;
+ ::std::memcpy(&val, ptr, 8);
+ ptr += 8;
+ msg->set_value(val);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool DoubleValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.DoubleValue)
for (;;) {
@@ -429,8 +442,7 @@ bool DoubleValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// double value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(9u /* 9 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (9 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -460,6 +472,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void DoubleValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -472,9 +485,9 @@ void DoubleValue::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.DoubleValue)
}
@@ -491,9 +504,9 @@ void DoubleValue::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.DoubleValue)
return target;
@@ -503,11 +516,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// double value = 1;
if (this->value() != 0) {
total_size += 1 + 8;
@@ -522,7 +539,7 @@ void DoubleValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DoubleValue)
GOOGLE_DCHECK_NE(&from, this);
const DoubleValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const DoubleValue>(
+ ::google::protobuf::DynamicCastToGenerated<DoubleValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.DoubleValue)
@@ -584,13 +601,13 @@ void DoubleValue::UnsafeArenaSwap(DoubleValue* other) {
}
void DoubleValue::InternalSwap(DoubleValue* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata DoubleValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -598,21 +615,22 @@ void DoubleValue::InternalSwap(DoubleValue* other) {
void FloatValue::InitAsDefaultInstance() {
}
+class FloatValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FloatValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FloatValue::FloatValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FloatValue)
}
FloatValue::FloatValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue)
@@ -642,18 +660,13 @@ void FloatValue::ArenaDtor(void* object) {
FloatValue* _this = reinterpret_cast< FloatValue* >(object);
(void)_this;
}
-void FloatValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void FloatValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void FloatValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* FloatValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const FloatValue& FloatValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_FloatValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_FloatValue_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -668,9 +681,55 @@ void FloatValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* FloatValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<FloatValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // float value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 13) goto handle_unusual;
+ float val;
+ std::memcpy(&val, ptr, 4);
+ ptr += 4;
+ msg->set_value(val);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool FloatValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.FloatValue)
for (;;) {
@@ -680,8 +739,7 @@ bool FloatValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// float value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(13u /* 13 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (13 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
@@ -711,6 +769,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void FloatValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -723,9 +782,9 @@ void FloatValue::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteFloat(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.FloatValue)
}
@@ -742,9 +801,9 @@ void FloatValue::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.FloatValue)
return target;
@@ -754,11 +813,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// float value = 1;
if (this->value() != 0) {
total_size += 1 + 4;
@@ -773,7 +836,7 @@ void FloatValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FloatValue)
GOOGLE_DCHECK_NE(&from, this);
const FloatValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const FloatValue>(
+ ::google::protobuf::DynamicCastToGenerated<FloatValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.FloatValue)
@@ -835,13 +898,13 @@ void FloatValue::UnsafeArenaSwap(FloatValue* other) {
}
void FloatValue::InternalSwap(FloatValue* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata FloatValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -849,21 +912,22 @@ void FloatValue::InternalSwap(FloatValue* other) {
void Int64Value::InitAsDefaultInstance() {
}
+class Int64Value::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Int64Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Int64Value::Int64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int64Value)
}
Int64Value::Int64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value)
@@ -877,7 +941,7 @@ Int64Value::Int64Value(const Int64Value& from)
}
void Int64Value::SharedCtor() {
- value_ = GOOGLE_LONGLONG(0);
+ value_ = PROTOBUF_LONGLONG(0);
}
Int64Value::~Int64Value() {
@@ -893,18 +957,13 @@ void Int64Value::ArenaDtor(void* object) {
Int64Value* _this = reinterpret_cast< Int64Value* >(object);
(void)_this;
}
-void Int64Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Int64Value::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Int64Value::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Int64Value::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Int64Value& Int64Value::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int64Value.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Int64Value_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -915,13 +974,60 @@ void Int64Value::Clear() {
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- value_ = GOOGLE_LONGLONG(0);
+ value_ = PROTOBUF_LONGLONG(0);
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Int64Value::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Int64Value*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // int64 value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int64 value = val;
+ msg->set_value(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Int64Value::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Int64Value)
for (;;) {
@@ -931,8 +1037,7 @@ bool Int64Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int64 value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
@@ -962,6 +1067,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Int64Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -974,9 +1080,9 @@ void Int64Value::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Int64Value)
}
@@ -993,9 +1099,9 @@ void Int64Value::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int64Value)
return target;
@@ -1005,11 +1111,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// int64 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1026,7 +1136,7 @@ void Int64Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Int64Value)
GOOGLE_DCHECK_NE(&from, this);
const Int64Value* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Int64Value>(
+ ::google::protobuf::DynamicCastToGenerated<Int64Value>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Int64Value)
@@ -1088,13 +1198,13 @@ void Int64Value::UnsafeArenaSwap(Int64Value* other) {
}
void Int64Value::InternalSwap(Int64Value* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata Int64Value::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -1102,21 +1212,22 @@ void Int64Value::InternalSwap(Int64Value* other) {
void UInt64Value::InitAsDefaultInstance() {
}
+class UInt64Value::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UInt64Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
UInt64Value::UInt64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt64Value)
}
UInt64Value::UInt64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value)
@@ -1130,7 +1241,7 @@ UInt64Value::UInt64Value(const UInt64Value& from)
}
void UInt64Value::SharedCtor() {
- value_ = GOOGLE_ULONGLONG(0);
+ value_ = PROTOBUF_ULONGLONG(0);
}
UInt64Value::~UInt64Value() {
@@ -1146,18 +1257,13 @@ void UInt64Value::ArenaDtor(void* object) {
UInt64Value* _this = reinterpret_cast< UInt64Value* >(object);
(void)_this;
}
-void UInt64Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void UInt64Value::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void UInt64Value::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* UInt64Value::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const UInt64Value& UInt64Value::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt64Value.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_UInt64Value_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -1168,13 +1274,60 @@ void UInt64Value::Clear() {
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
- value_ = GOOGLE_ULONGLONG(0);
+ value_ = PROTOBUF_ULONGLONG(0);
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* UInt64Value::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<UInt64Value*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // uint64 value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::uint64 value = val;
+ msg->set_value(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool UInt64Value::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UInt64Value)
for (;;) {
@@ -1184,8 +1337,7 @@ bool UInt64Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint64 value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
@@ -1215,6 +1367,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void UInt64Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1227,9 +1380,9 @@ void UInt64Value::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.UInt64Value)
}
@@ -1246,9 +1399,9 @@ void UInt64Value::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt64Value)
return target;
@@ -1258,11 +1411,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// uint64 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1279,7 +1436,7 @@ void UInt64Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UInt64Value)
GOOGLE_DCHECK_NE(&from, this);
const UInt64Value* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const UInt64Value>(
+ ::google::protobuf::DynamicCastToGenerated<UInt64Value>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UInt64Value)
@@ -1341,13 +1498,13 @@ void UInt64Value::UnsafeArenaSwap(UInt64Value* other) {
}
void UInt64Value::InternalSwap(UInt64Value* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata UInt64Value::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -1355,21 +1512,22 @@ void UInt64Value::InternalSwap(UInt64Value* other) {
void Int32Value::InitAsDefaultInstance() {
}
+class Int32Value::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Int32Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Int32Value::Int32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int32Value)
}
Int32Value::Int32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value)
@@ -1399,18 +1557,13 @@ void Int32Value::ArenaDtor(void* object) {
Int32Value* _this = reinterpret_cast< Int32Value* >(object);
(void)_this;
}
-void Int32Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void Int32Value::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void Int32Value::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* Int32Value::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const Int32Value& Int32Value::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_Int32Value.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_Int32Value_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -1425,9 +1578,56 @@ void Int32Value::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* Int32Value::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<Int32Value*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // int32 value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::int32 value = val;
+ msg->set_value(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Int32Value::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Int32Value)
for (;;) {
@@ -1437,8 +1637,7 @@ bool Int32Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
@@ -1468,6 +1667,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Int32Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1480,9 +1680,9 @@ void Int32Value::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Int32Value)
}
@@ -1499,9 +1699,9 @@ void Int32Value::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Int32Value)
return target;
@@ -1511,11 +1711,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// int32 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1532,7 +1736,7 @@ void Int32Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Int32Value)
GOOGLE_DCHECK_NE(&from, this);
const Int32Value* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const Int32Value>(
+ ::google::protobuf::DynamicCastToGenerated<Int32Value>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Int32Value)
@@ -1594,13 +1798,13 @@ void Int32Value::UnsafeArenaSwap(Int32Value* other) {
}
void Int32Value::InternalSwap(Int32Value* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata Int32Value::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -1608,21 +1812,22 @@ void Int32Value::InternalSwap(Int32Value* other) {
void UInt32Value::InitAsDefaultInstance() {
}
+class UInt32Value::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int UInt32Value::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
UInt32Value::UInt32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt32Value)
}
UInt32Value::UInt32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value)
@@ -1652,18 +1857,13 @@ void UInt32Value::ArenaDtor(void* object) {
UInt32Value* _this = reinterpret_cast< UInt32Value* >(object);
(void)_this;
}
-void UInt32Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void UInt32Value::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void UInt32Value::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* UInt32Value::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const UInt32Value& UInt32Value::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_UInt32Value.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_UInt32Value_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -1678,9 +1878,56 @@ void UInt32Value::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* UInt32Value::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<UInt32Value*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // uint32 value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ::google::protobuf::uint32 value = val;
+ msg->set_value(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool UInt32Value::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.UInt32Value)
for (;;) {
@@ -1690,8 +1937,7 @@ bool UInt32Value::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint32 value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
@@ -1721,6 +1967,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void UInt32Value::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1733,9 +1980,9 @@ void UInt32Value::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.UInt32Value)
}
@@ -1752,9 +1999,9 @@ void UInt32Value::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.UInt32Value)
return target;
@@ -1764,11 +2011,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// uint32 value = 1;
if (this->value() != 0) {
total_size += 1 +
@@ -1785,7 +2036,7 @@ void UInt32Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UInt32Value)
GOOGLE_DCHECK_NE(&from, this);
const UInt32Value* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const UInt32Value>(
+ ::google::protobuf::DynamicCastToGenerated<UInt32Value>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.UInt32Value)
@@ -1847,13 +2098,13 @@ void UInt32Value::UnsafeArenaSwap(UInt32Value* other) {
}
void UInt32Value::InternalSwap(UInt32Value* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata UInt32Value::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -1861,21 +2112,22 @@ void UInt32Value::InternalSwap(UInt32Value* other) {
void BoolValue::InitAsDefaultInstance() {
}
+class BoolValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BoolValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BoolValue::BoolValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BoolValue)
}
BoolValue::BoolValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue)
@@ -1905,18 +2157,13 @@ void BoolValue::ArenaDtor(void* object) {
BoolValue* _this = reinterpret_cast< BoolValue* >(object);
(void)_this;
}
-void BoolValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void BoolValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void BoolValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* BoolValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const BoolValue& BoolValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BoolValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_BoolValue_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -1931,9 +2178,56 @@ void BoolValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* BoolValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<BoolValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // bool value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
+ ::google::protobuf::uint64 val;
+ ptr = Varint::Parse64(ptr, &val);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ bool value = val;
+ msg->set_value(value);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool BoolValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.BoolValue)
for (;;) {
@@ -1943,8 +2237,7 @@ bool BoolValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bool value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -1974,6 +2267,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void BoolValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -1986,9 +2280,9 @@ void BoolValue::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteBool(1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.BoolValue)
}
@@ -2005,9 +2299,9 @@ void BoolValue::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BoolValue)
return target;
@@ -2017,11 +2311,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// bool value = 1;
if (this->value() != 0) {
total_size += 1 + 1;
@@ -2036,7 +2334,7 @@ void BoolValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.BoolValue)
GOOGLE_DCHECK_NE(&from, this);
const BoolValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const BoolValue>(
+ ::google::protobuf::DynamicCastToGenerated<BoolValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.BoolValue)
@@ -2098,13 +2396,13 @@ void BoolValue::UnsafeArenaSwap(BoolValue* other) {
}
void BoolValue::InternalSwap(BoolValue* other) {
using std::swap;
- swap(value_, other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
+ swap(value_, other->value_);
}
::google::protobuf::Metadata BoolValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -2112,21 +2410,22 @@ void BoolValue::InternalSwap(BoolValue* other) {
void StringValue::InitAsDefaultInstance() {
}
+class StringValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int StringValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
StringValue::StringValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.StringValue)
}
StringValue::StringValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue)
@@ -2144,6 +2443,8 @@ StringValue::StringValue(const StringValue& from)
}
void StringValue::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_StringValue_google_2fprotobuf_2fwrappers_2eproto.base);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -2161,18 +2462,13 @@ void StringValue::ArenaDtor(void* object) {
StringValue* _this = reinterpret_cast< StringValue* >(object);
(void)_this;
}
-void StringValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void StringValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void StringValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* StringValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const StringValue& StringValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_StringValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_StringValue_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -2187,9 +2483,62 @@ void StringValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* StringValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<StringValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // string value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ ctx->extra_parse_data().SetFieldName("google.protobuf.StringValue.value");
+ parser_till_end = ::google::protobuf::internal::StringParserUTF8;
+ ::std::string* str = msg->mutable_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ auto newend = ptr + size;
+ if (size) ptr = parser_till_end(ptr, newend, object, ctx);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool StringValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.StringValue)
for (;;) {
@@ -2199,8 +2548,7 @@ bool StringValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -2232,6 +2580,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void StringValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2249,9 +2598,9 @@ void StringValue::SerializeWithCachedSizes(
1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.StringValue)
}
@@ -2274,9 +2623,9 @@ void StringValue::SerializeWithCachedSizes(
1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.StringValue)
return target;
@@ -2286,11 +2635,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// string value = 1;
if (this->value().size() > 0) {
total_size += 1 +
@@ -2307,7 +2660,7 @@ void StringValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.StringValue)
GOOGLE_DCHECK_NE(&from, this);
const StringValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const StringValue>(
+ ::google::protobuf::DynamicCastToGenerated<StringValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.StringValue)
@@ -2369,14 +2722,14 @@ void StringValue::UnsafeArenaSwap(StringValue* other) {
}
void StringValue::InternalSwap(StringValue* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata StringValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -2384,21 +2737,22 @@ void StringValue::InternalSwap(StringValue* other) {
void BytesValue::InitAsDefaultInstance() {
}
+class BytesValue::HasBitSetters {
+ public:
+};
+
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BytesValue::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BytesValue::BytesValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
- ::google::protobuf::internal::InitSCC(
- &protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BytesValue)
}
BytesValue::BytesValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base);
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue)
@@ -2416,6 +2770,8 @@ BytesValue::BytesValue(const BytesValue& from)
}
void BytesValue::SharedCtor() {
+ ::google::protobuf::internal::InitSCC(
+ &scc_info_BytesValue_google_2fprotobuf_2fwrappers_2eproto.base);
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
@@ -2433,18 +2789,13 @@ void BytesValue::ArenaDtor(void* object) {
BytesValue* _this = reinterpret_cast< BytesValue* >(object);
(void)_this;
}
-void BytesValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+void BytesValue::RegisterArenaDtor(::google::protobuf::Arena*) {
}
void BytesValue::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
-const ::google::protobuf::Descriptor* BytesValue::descriptor() {
- ::protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
-}
-
const BytesValue& BytesValue::default_instance() {
- ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fwrappers_2eproto::scc_info_BytesValue.base);
+ ::google::protobuf::internal::InitSCC(&::scc_info_BytesValue_google_2fprotobuf_2fwrappers_2eproto.base);
return *internal_default_instance();
}
@@ -2459,9 +2810,60 @@ void BytesValue::Clear() {
_internal_metadata_.Clear();
}
+#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+const char* BytesValue::_InternalParse(const char* begin, const char* end, void* object,
+ ::google::protobuf::internal::ParseContext* ctx) {
+ auto msg = static_cast<BytesValue*>(object);
+ ::google::protobuf::uint32 size; (void)size;
+ int depth; (void)depth;
+ ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
+ auto ptr = begin;
+ while (ptr < end) {
+ ::google::protobuf::uint32 tag;
+ ptr = Varint::Parse32Inline(ptr, &tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ switch (tag >> 3) {
+ // bytes value = 1;
+ case 1: {
+ if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
+ ptr = Varint::Parse32Inline(ptr, &size);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
+ parser_till_end = ::google::protobuf::internal::StringParser;
+ ::std::string* str = msg->mutable_value();
+ str->clear();
+ object = str;
+ if (size > end - ptr) goto len_delim_till_end;
+ str->append(ptr, size);
+ ptr += size;
+ break;
+ }
+ default: {
+ handle_unusual: (void)&&handle_unusual;
+ if ((tag & 7) == 4 || tag == 0) {
+ bool ok = ctx->ValidEndGroup(tag);
+ GOOGLE_PROTOBUF_PARSER_ASSERT(ok);
+ return ptr;
+ }
+ auto res = UnknownFieldParse(tag, {_InternalParse, msg},
+ ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
+ ptr = res.first;
+ if (res.second) return ptr;
+ }
+ } // switch
+ } // while
+ return ptr;
+len_delim_till_end: (void)&&len_delim_till_end;
+ return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
+ {parser_till_end, object}, size);
+group_continues: (void)&&group_continues;
+ GOOGLE_DCHECK(ptr >= end);
+ ctx->StoreGroup({_InternalParse, msg}, {parser_till_end, object}, depth);
+ return ptr;
+}
+#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool BytesValue::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
-#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
+#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.BytesValue)
for (;;) {
@@ -2471,8 +2873,7 @@ bool BytesValue::MergePartialFromCodedStream(
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// bytes value = 1;
case 1: {
- if (static_cast< ::google::protobuf::uint8>(tag) ==
- static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
+ if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
@@ -2500,6 +2901,7 @@ failure:
return false;
#undef DO_
}
+#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void BytesValue::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
@@ -2513,9 +2915,9 @@ void BytesValue::SerializeWithCachedSizes(
1, this->value(), output);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
+ _internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.BytesValue)
}
@@ -2534,9 +2936,9 @@ void BytesValue::SerializeWithCachedSizes(
1, this->value(), target);
}
- if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
+ if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
+ _internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.BytesValue)
return target;
@@ -2546,11 +2948,15 @@ 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())) {
+ if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
- (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
+ _internal_metadata_.unknown_fields());
}
+ ::google::protobuf::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
// bytes value = 1;
if (this->value().size() > 0) {
total_size += 1 +
@@ -2567,7 +2973,7 @@ void BytesValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.BytesValue)
GOOGLE_DCHECK_NE(&from, this);
const BytesValue* source =
- ::google::protobuf::internal::DynamicCastToGenerated<const BytesValue>(
+ ::google::protobuf::DynamicCastToGenerated<BytesValue>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.BytesValue)
@@ -2629,14 +3035,14 @@ void BytesValue::UnsafeArenaSwap(BytesValue* other) {
}
void BytesValue::InternalSwap(BytesValue* other) {
using std::swap;
+ _internal_metadata_.Swap(&other->_internal_metadata_);
value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
- _internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata BytesValue::GetMetadata() const {
- protobuf_google_2fprotobuf_2fwrappers_2eproto::protobuf_AssignDescriptorsOnce();
- return ::protobuf_google_2fprotobuf_2fwrappers_2eproto::file_level_metadata[kIndexInFileMessages];
+ ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprotobuf_2fwrappers_2eproto);
+ return ::file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[kIndexInFileMessages];
}
@@ -2645,34 +3051,35 @@ void BytesValue::InternalSwap(BytesValue* other) {
} // namespace google
namespace google {
namespace protobuf {
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage< ::google::protobuf::DoubleValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage< ::google::protobuf::DoubleValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::DoubleValue >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::FloatValue* Arena::CreateMaybeMessage< ::google::protobuf::FloatValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::FloatValue* Arena::CreateMaybeMessage< ::google::protobuf::FloatValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::FloatValue >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int64Value* Arena::CreateMaybeMessage< ::google::protobuf::Int64Value >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Int64Value* Arena::CreateMaybeMessage< ::google::protobuf::Int64Value >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Int64Value >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt64Value >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt64Value >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::UInt64Value >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Int32Value* Arena::CreateMaybeMessage< ::google::protobuf::Int32Value >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::Int32Value* Arena::CreateMaybeMessage< ::google::protobuf::Int32Value >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::Int32Value >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt32Value >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage< ::google::protobuf::UInt32Value >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::UInt32Value >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BoolValue* Arena::CreateMaybeMessage< ::google::protobuf::BoolValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::BoolValue* Arena::CreateMaybeMessage< ::google::protobuf::BoolValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::BoolValue >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::StringValue* Arena::CreateMaybeMessage< ::google::protobuf::StringValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::StringValue* Arena::CreateMaybeMessage< ::google::protobuf::StringValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::StringValue >(arena);
}
-template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMaybeMessage< ::google::protobuf::BytesValue >(Arena* arena) {
+template<> PROTOBUF_NOINLINE ::google::protobuf::BytesValue* Arena::CreateMaybeMessage< ::google::protobuf::BytesValue >(Arena* arena) {
return Arena::CreateMessageInternal< ::google::protobuf::BytesValue >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index 82f5627f..5b1d70a7 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -4,21 +4,22 @@
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
+#include <limits>
#include <string>
-#include <google/protobuf/stubs/common.h>
-
-#if GOOGLE_PROTOBUF_VERSION < 3006001
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3006001
#error This file was generated by a newer version of protoc which is
-#error incompatible with your Protocol Buffer headers. Please update
+#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3006001 < 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 incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
+#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
@@ -31,62 +32,60 @@
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
-#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fwrappers_2eproto LIBPROTOBUF_EXPORT
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fwrappers_2eproto PROTOBUF_EXPORT
-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];
+struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fwrappers_2eproto {
+ static const ::google::protobuf::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::google::protobuf::internal::ParseTable schema[9]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
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();
-} // namespace protobuf_google_2fprotobuf_2fwrappers_2eproto
+void PROTOBUF_EXPORT AddDescriptors_google_2fprotobuf_2fwrappers_2eproto();
namespace google {
namespace protobuf {
class BoolValue;
class BoolValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern BoolValueDefaultTypeInternal _BoolValue_default_instance_;
+PROTOBUF_EXPORT extern BoolValueDefaultTypeInternal _BoolValue_default_instance_;
class BytesValue;
class BytesValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern BytesValueDefaultTypeInternal _BytesValue_default_instance_;
+PROTOBUF_EXPORT extern BytesValueDefaultTypeInternal _BytesValue_default_instance_;
class DoubleValue;
class DoubleValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern DoubleValueDefaultTypeInternal _DoubleValue_default_instance_;
+PROTOBUF_EXPORT extern DoubleValueDefaultTypeInternal _DoubleValue_default_instance_;
class FloatValue;
class FloatValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern FloatValueDefaultTypeInternal _FloatValue_default_instance_;
+PROTOBUF_EXPORT extern FloatValueDefaultTypeInternal _FloatValue_default_instance_;
class Int32Value;
class Int32ValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern Int32ValueDefaultTypeInternal _Int32Value_default_instance_;
+PROTOBUF_EXPORT extern Int32ValueDefaultTypeInternal _Int32Value_default_instance_;
class Int64Value;
class Int64ValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern Int64ValueDefaultTypeInternal _Int64Value_default_instance_;
+PROTOBUF_EXPORT extern Int64ValueDefaultTypeInternal _Int64Value_default_instance_;
class StringValue;
class StringValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern StringValueDefaultTypeInternal _StringValue_default_instance_;
+PROTOBUF_EXPORT extern StringValueDefaultTypeInternal _StringValue_default_instance_;
class UInt32Value;
class UInt32ValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_;
+PROTOBUF_EXPORT extern UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_;
class UInt64Value;
class UInt64ValueDefaultTypeInternal;
-LIBPROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_;
-} // namespace protobuf
-} // namespace google
-namespace google {
-namespace protobuf {
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMaybeMessage<::google::protobuf::BoolValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMaybeMessage<::google::protobuf::BytesValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage<::google::protobuf::DoubleValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMaybeMessage<::google::protobuf::FloatValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMaybeMessage<::google::protobuf::Int32Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMaybeMessage<::google::protobuf::Int64Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMaybeMessage<::google::protobuf::StringValue>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage<::google::protobuf::UInt32Value>(Arena*);
-template<> LIBPROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage<::google::protobuf::UInt64Value>(Arena*);
+PROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_;
+template<> PROTOBUF_EXPORT ::google::protobuf::BoolValue* Arena::CreateMaybeMessage<::google::protobuf::BoolValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::BytesValue* Arena::CreateMaybeMessage<::google::protobuf::BytesValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::DoubleValue* Arena::CreateMaybeMessage<::google::protobuf::DoubleValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::FloatValue* Arena::CreateMaybeMessage<::google::protobuf::FloatValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Int32Value* Arena::CreateMaybeMessage<::google::protobuf::Int32Value>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::Int64Value* Arena::CreateMaybeMessage<::google::protobuf::Int64Value>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::StringValue* Arena::CreateMaybeMessage<::google::protobuf::StringValue>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::UInt32Value* Arena::CreateMaybeMessage<::google::protobuf::UInt32Value>(Arena*);
+template<> PROTOBUF_EXPORT ::google::protobuf::UInt64Value* Arena::CreateMaybeMessage<::google::protobuf::UInt64Value>(Arena*);
} // namespace protobuf
} // namespace google
namespace google {
@@ -94,7 +93,7 @@ namespace protobuf {
// ===================================================================
-class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DoubleValue) */ {
+class PROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DoubleValue) */ {
public:
DoubleValue();
virtual ~DoubleValue();
@@ -126,7 +125,9 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const DoubleValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -160,8 +161,13 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -201,6 +207,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
// @@protoc_insertion_point(class_scope:google.protobuf.DoubleValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -208,11 +215,11 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
typedef void DestructorSkippable_;
double value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FloatValue) */ {
+class PROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FloatValue) */ {
public:
FloatValue();
virtual ~FloatValue();
@@ -244,7 +251,9 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const FloatValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -278,8 +287,13 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -319,6 +333,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
// @@protoc_insertion_point(class_scope:google.protobuf.FloatValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -326,11 +341,11 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
typedef void DestructorSkippable_;
float value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int64Value) */ {
+class PROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int64Value) */ {
public:
Int64Value();
virtual ~Int64Value();
@@ -362,7 +377,9 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Int64Value& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -396,8 +413,13 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -437,6 +459,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
// @@protoc_insertion_point(class_scope:google.protobuf.Int64Value)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -444,11 +467,11 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
typedef void DestructorSkippable_;
::google::protobuf::int64 value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt64Value) */ {
+class PROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt64Value) */ {
public:
UInt64Value();
virtual ~UInt64Value();
@@ -480,7 +503,9 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const UInt64Value& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -514,8 +539,13 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -555,6 +585,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
// @@protoc_insertion_point(class_scope:google.protobuf.UInt64Value)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -562,11 +593,11 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
typedef void DestructorSkippable_;
::google::protobuf::uint64 value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int32Value) */ {
+class PROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int32Value) */ {
public:
Int32Value();
virtual ~Int32Value();
@@ -598,7 +629,9 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const Int32Value& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -632,8 +665,13 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -673,6 +711,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
// @@protoc_insertion_point(class_scope:google.protobuf.Int32Value)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -680,11 +719,11 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
typedef void DestructorSkippable_;
::google::protobuf::int32 value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt32Value) */ {
+class PROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt32Value) */ {
public:
UInt32Value();
virtual ~UInt32Value();
@@ -716,7 +755,9 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const UInt32Value& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -750,8 +791,13 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -791,6 +837,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
// @@protoc_insertion_point(class_scope:google.protobuf.UInt32Value)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -798,11 +845,11 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
typedef void DestructorSkippable_;
::google::protobuf::uint32 value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BoolValue) */ {
+class PROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BoolValue) */ {
public:
BoolValue();
virtual ~BoolValue();
@@ -834,7 +881,9 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const BoolValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -868,8 +917,13 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -909,6 +963,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
// @@protoc_insertion_point(class_scope:google.protobuf.BoolValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -916,11 +971,11 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
typedef void DestructorSkippable_;
bool value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.StringValue) */ {
+class PROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.StringValue) */ {
public:
StringValue();
virtual ~StringValue();
@@ -952,7 +1007,9 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const StringValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -986,8 +1043,13 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1032,11 +1094,11 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
::std::string* mutable_value();
::std::string* release_value();
void set_allocated_value(::std::string* value);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1044,6 +1106,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
// @@protoc_insertion_point(class_scope:google.protobuf.StringValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1051,11 +1114,11 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// -------------------------------------------------------------------
-class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BytesValue) */ {
+class PROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BytesValue) */ {
public:
BytesValue();
virtual ~BytesValue();
@@ -1087,7 +1150,9 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
- static const ::google::protobuf::Descriptor* descriptor();
+ static const ::google::protobuf::Descriptor* descriptor() {
+ return default_instance().GetDescriptor();
+ }
static const BytesValue& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
@@ -1121,8 +1186,13 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
+ #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
+ static const char* _InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx);
+ ::google::protobuf::internal::ParseFunc _ParseFunc() const final { return _InternalParse; }
+ #else
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) final;
+ #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
@@ -1167,11 +1237,11 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
::std::string* mutable_value();
::std::string* release_value();
void set_allocated_value(::std::string* value);
- PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ GOOGLE_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"
+ GOOGLE_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(
@@ -1179,6 +1249,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
// @@protoc_insertion_point(class_scope:google.protobuf.BytesValue)
private:
+ class HasBitSetters;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::google::protobuf::Arena::InternalHelper;
@@ -1186,7 +1257,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
- friend struct ::protobuf_google_2fprotobuf_2fwrappers_2eproto::TableStruct;
+ friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto;
};
// ===================================================================
@@ -1237,7 +1308,7 @@ inline void FloatValue::set_value(float value) {
// int64 value = 1;
inline void Int64Value::clear_value() {
- value_ = GOOGLE_LONGLONG(0);
+ value_ = PROTOBUF_LONGLONG(0);
}
inline ::google::protobuf::int64 Int64Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Int64Value.value)
@@ -1255,7 +1326,7 @@ inline void Int64Value::set_value(::google::protobuf::int64 value) {
// uint64 value = 1;
inline void UInt64Value::clear_value() {
- value_ = GOOGLE_ULONGLONG(0);
+ value_ = PROTOBUF_ULONGLONG(0);
}
inline ::google::protobuf::uint64 UInt64Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UInt64Value.value)
@@ -1506,4 +1577,5 @@ inline void BytesValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto
diff --git a/src/google/protobuf/wrappers.proto b/src/google/protobuf/wrappers.proto
index 01947639..9ee41e38 100644
--- a/src/google/protobuf/wrappers.proto
+++ b/src/google/protobuf/wrappers.proto
@@ -32,6 +32,11 @@
// for embedding primitives in the `google.protobuf.Any` type and for places
// where we need to distinguish between the absence of a primitive
// typed field and its default value.
+//
+// These wrappers have no meaningful use within repeated fields as they lack
+// the ability to detect presence on individual elements.
+// These wrappers have no meaningful use within a map or a oneof since
+// individual entries of a map or fields of a oneof can already detect presence.
syntax = "proto3";
diff --git a/tests.sh b/tests.sh
index 73be5c1d..49534137 100755
--- a/tests.sh
+++ b/tests.sh
@@ -18,12 +18,12 @@ internal_build_cpp() {
./autogen.sh
./configure CXXFLAGS="-fPIC" # -fPIC is needed for python cpp test.
# See python/setup.py for more details
- make -j2
+ make -j4
}
build_cpp() {
internal_build_cpp
- make check -j2 || (cat src/test-suite.log; false)
+ make check -j4 || (cat src/test-suite.log; false)
cd conformance && make test_cpp && cd ..
# The benchmark code depends on cmake, so test if it is installed before
@@ -56,10 +56,10 @@ build_cpp_distcheck() {
# Check if every file exists in the dist tar file.
FILES_MISSING=""
for FILE in $(<../dist.lst); do
- if ! file $FILE &>/dev/null; then
+ [ -f "$FILE" ] || {
echo "$FILE is not found!"
FILES_MISSING="$FILE $FILES_MISSING"
- fi
+ }
done
cd ..
if [ ! -z "$FILES_MISSING" ]; then
@@ -68,7 +68,7 @@ build_cpp_distcheck() {
fi
# Do the regular dist-check for C++.
- make distcheck -j2
+ make distcheck -j4
}
build_csharp() {
@@ -105,9 +105,9 @@ build_golang() {
export PATH="`pwd`/src:$PATH"
export GOPATH="$HOME/gocode"
- mkdir -p "$GOPATH/src/github.com/google"
- rm -f "$GOPATH/src/github.com/google/protobuf"
- ln -s "`pwd`" "$GOPATH/src/github.com/google/protobuf"
+ mkdir -p "$GOPATH/src/github.com/protocolbuffers"
+ rm -f "$GOPATH/src/github.com/protocolbuffers/protobuf"
+ ln -s "`pwd`" "$GOPATH/src/github.com/protocolbuffers/protobuf"
export PATH="$GOPATH/bin:$PATH"
go get github.com/golang/protobuf/protoc-gen-go
@@ -507,18 +507,21 @@ build_php7.1() {
phpunit
popd
pushd conformance
- # TODO(teboring): Add it back
- # make test_php
+ make test_php
popd
}
build_php7.1_c() {
+ ENABLE_CONFORMANCE_TEST=$1
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 7.1 && cd ../..
- pushd conformance
- # make test_php_c
- popd
+ if [ "$ENABLE_CONFORMANCE_TEST" = "true" ]
+ then
+ pushd conformance
+ make test_php_c
+ popd
+ fi
}
build_php7.1_zts_c() {
@@ -538,7 +541,7 @@ build_php_all_32() {
build_php5.5_c
build_php5.6_c
build_php7.0_c
- build_php7.1_c
+ build_php7.1_c $1
build_php5.5_zts_c
build_php5.6_zts_c
build_php7.0_zts_c
@@ -546,7 +549,7 @@ build_php_all_32() {
}
build_php_all() {
- build_php_all_32
+ build_php_all_32 true
build_php_compatibility
}